@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
@@ -0,0 +1,431 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { displayName } from "../../domain/display-names.js";
3
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
4
+ import { fold } from "../normalize.js";
5
+ import { groupByDomain, releaseDomainHolds } from "./domain-organizations.js";
6
+ import { currentPerson } from "./merged-persons.js";
7
+ import { isOwner, mergePerson, move, recordOf, renameAfterLeaving } from "./person-links.js";
8
+ import { senderSignalsOf, sentMailOf } from "./sender-signals.js";
9
+ import { read, write } from "./transaction.js";
10
+ const MIN_QUERY = 3;
11
+ const HOLDS = "EXISTS (SELECT 1 FROM sender_bot_identities h WHERE h.bot_id = b.id)";
12
+ const SHOWN = "coalesce(b.name, (SELECT coalesce(i.name, i.username, i.external_id) FROM sender_bot_identities s " +
13
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id ORDER BY i.name IS NULL, i.id LIMIT 1))";
14
+ const refOf = (side) => side.person !== undefined
15
+ ? `person:${side.person}`
16
+ : side.bot !== undefined
17
+ ? `${SENDER_BOT_PREFIX}${side.bot}`
18
+ : null;
19
+ const holderOf = (database, identity) => {
20
+ const linked = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
21
+ if (linked !== undefined)
22
+ return { person: Number(linked.person_id) };
23
+ const held = database.prepare("SELECT bot_id FROM sender_bot_identities WHERE identity_id = ?").get(identity);
24
+ return held === undefined ? {} : { bot: Number(held.bot_id) };
25
+ };
26
+ const identitiesOf = (database, person) => database
27
+ .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
28
+ .all(person)
29
+ .map((row) => Number(row.identity_id));
30
+ const botIdentitiesOf = (database, bot) => database
31
+ .prepare("SELECT identity_id FROM sender_bot_identities WHERE bot_id = ? ORDER BY identity_id")
32
+ .all(bot)
33
+ .map((row) => Number(row.identity_id));
34
+ const logMove = (database, identity, from, to, { author, reason, at }) => database
35
+ .prepare("INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, " +
36
+ "reason, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
37
+ .run(identity, from.person ?? null, from.bot ?? null, to.person ?? null, to.bot ?? null, author, reason, at);
38
+ /** `person_id` only keeps builds before version 75 from reading the bot as a person: a negative one names none. */
39
+ const createBot = (database, { author, reason, at }, name = null) => Number(database
40
+ .prepare("INSERT INTO sender_bots (person_id, name, author, reason, created_at, updated_at) " +
41
+ "VALUES ((SELECT min(0, coalesce(min(person_id), 0)) - 1 FROM sender_bots), ?, ?, ?, ?, ?) RETURNING id")
42
+ .get(name, author, reason, at, at)?.id);
43
+ /** A person every identity left for a bot is stored as a merge's emptied person is: no list shows them. */
44
+ const retireEmptied = (database, people) => {
45
+ const retire = database.prepare("UPDATE persons SET kind = 'merged' WHERE id = ? AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = ?)");
46
+ for (const person of people)
47
+ retire.run(person, person);
48
+ };
49
+ /**
50
+ * Moves identities to a bot, off a person or another bot, each move logged. Answers the people each left, and which
51
+ * identities. The caller holds the write lock.
52
+ */
53
+ const intoBot = (database, identities, bot, log) => {
54
+ const left = new Map();
55
+ for (const identity of identities) {
56
+ const from = holderOf(database, identity);
57
+ if (from.bot === bot)
58
+ continue;
59
+ if (from.person !== undefined) {
60
+ database.prepare("DELETE FROM identity_links WHERE identity_id = ?").run(identity);
61
+ left.set(from.person, [...(left.get(from.person) ?? []), identity]);
62
+ }
63
+ if (from.bot !== undefined)
64
+ database.prepare("UPDATE sender_bot_identities SET bot_id = ? WHERE identity_id = ?").run(bot, identity);
65
+ else
66
+ database
67
+ .prepare("INSERT INTO sender_bot_identities (identity_id, bot_id, created_at) VALUES (?, ?, ?)")
68
+ .run(identity, bot, log.at);
69
+ logMove(database, identity, from, { bot }, log);
70
+ }
71
+ retireEmptied(database, left.keys());
72
+ return left;
73
+ };
74
+ /** The person an identity last left for a bot, as that person is now; `undefined` when it came from none. */
75
+ const originOf = (database, identity) => {
76
+ const row = database
77
+ .prepare("SELECT m.from_person_id FROM sender_bot_moves m JOIN persons p ON p.id = m.from_person_id " +
78
+ "WHERE m.identity_id = ? AND m.to_bot_id IS NOT NULL ORDER BY m.id DESC LIMIT 1")
79
+ .get(identity);
80
+ return row === undefined ? undefined : currentPerson(database, Number(row.from_person_id));
81
+ };
82
+ const newPerson = (database, identity, at) => Number(database
83
+ .prepare("INSERT INTO persons (name, created_at, updated_at) VALUES ((SELECT name FROM identities WHERE id = ?), ?, ?) " +
84
+ "RETURNING id")
85
+ .get(identity, at, at)?.id);
86
+ /**
87
+ * Gives a bot's identities to a person: `to`, else the person each came from, else a person row of its own. The bot
88
+ * goes with its last identity. Answers the person each went to. The caller holds the write lock.
89
+ */
90
+ const outOfBot = (database, identities, to, log) => {
91
+ const by = log.author === "owner" ? "owner" : "rules";
92
+ const went = new Map();
93
+ for (const identity of identities) {
94
+ const from = holderOf(database, identity);
95
+ if (from.bot === undefined)
96
+ continue;
97
+ database.prepare("DELETE FROM sender_bot_identities WHERE identity_id = ?").run(identity);
98
+ const target = to ?? originOf(database, identity) ?? newPerson(database, identity, log.at);
99
+ database
100
+ .prepare("INSERT INTO identity_links (identity_id, person_id, method, confidence, created_at, author, updated_at) " +
101
+ "VALUES (?, ?, 'bot', 1, ?, ?, ?)")
102
+ .run(identity, target, log.at, by, log.at);
103
+ database
104
+ .prepare("INSERT INTO identity_link_events (identity_id, from_person_id, to_person_id, method, created_at, author) " +
105
+ "VALUES (?, NULL, ?, 'bot', ?, ?)")
106
+ .run(identity, target, log.at, by);
107
+ logMove(database, identity, from, { person: target }, log);
108
+ went.set(identity, target);
109
+ }
110
+ return went;
111
+ };
112
+ /**
113
+ * The source re-keyed `from` onto `to`, both stored: a bot holding `from` takes `to` from its person, since one
114
+ * account is one program. The person it leaves is hidden as `intoBot` hides one. The caller holds the write lock.
115
+ */
116
+ export const rekeyIntoBot = (database, from, to, at) => {
117
+ const bot = holderOf(database, from).bot;
118
+ if (bot === undefined || holderOf(database, to).bot !== undefined)
119
+ return;
120
+ intoBot(database, [to], bot, { author: "rules", reason: "the source re-keyed the identity", at });
121
+ };
122
+ /** People holding an identity the owner last moved to a person, or kept as one: no rule makes them a bot. */
123
+ export const ownerPeopleOf = (database) => new Set(database
124
+ .prepare("SELECT DISTINCT l.person_id AS person FROM sender_bot_moves m JOIN identity_links l ON l.identity_id = m.identity_id " +
125
+ "WHERE m.author = 'owner' AND m.to_bot_id IS NULL " +
126
+ "AND m.id = (SELECT max(id) FROM sender_bot_moves WHERE identity_id = m.identity_id)")
127
+ .all()
128
+ .map((row) => Number(row.person)));
129
+ /** A person every identity left for a bot is no one's assignee: the bot has no tasks. */
130
+ export const refuseBotAssignee = (database, person) => {
131
+ const bot = database
132
+ .prepare("SELECT m.to_bot_id FROM sender_bot_moves m WHERE m.from_person_id = ? AND m.to_bot_id IS NOT NULL " +
133
+ "AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = ?) ORDER BY m.id DESC LIMIT 1")
134
+ .get(person, person);
135
+ if (bot !== undefined)
136
+ throw new CliError("validation_error", `person:${person} moved to ${SENDER_BOT_PREFIX}${bot.to_bot_id}, which is no one's assignee`, { reason: "sender-bot.assignee" });
137
+ };
138
+ /** A rule's move of a whole person to a new bot; answers the bot. The caller holds the write lock. */
139
+ export const ruleToBot = (database, person, reason, at) => {
140
+ const log = { author: "rules", reason, at };
141
+ const bot = createBot(database, log);
142
+ intoBot(database, identitiesOf(database, person), bot, log);
143
+ return bot;
144
+ };
145
+ /**
146
+ * A rule's bot the owner wrote to, by mail or in a private chat both wrote in, goes back to the people its identities
147
+ * came from; a messenger's own bot flag holds anyway. The caller holds the write lock.
148
+ */
149
+ export const ruleBotsBack = (database, at) => {
150
+ const back = database
151
+ .prepare("SELECT b.id FROM sender_bots b WHERE b.author = 'rules' AND NOT EXISTS (SELECT 1 FROM sender_bot_identities s " +
152
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id AND i.bot = 1) " +
153
+ "AND EXISTS (SELECT 1 FROM sender_bot_identities s WHERE s.bot_id = b.id AND (" +
154
+ "EXISTS (SELECT 1 FROM email_recipients r JOIN emails e ON e.id = r.email_id WHERE r.identity_id = s.identity_id " +
155
+ "AND e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1) OR " +
156
+ "EXISTS (SELECT 1 FROM messages m JOIN chats c ON c.id = m.chat_id WHERE m.sender_identity_id = s.identity_id " +
157
+ "AND m.outgoing IS NOT 1 AND c.kind = 'dialog' AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id " +
158
+ "AND o.outgoing = 1))))")
159
+ .all();
160
+ const log = { author: "rules", reason: "the owner wrote to it", at };
161
+ for (const row of back)
162
+ outOfBot(database, botIdentitiesOf(database, Number(row.id)), undefined, log);
163
+ };
164
+ /** Whether a build before version 75 sorted a bot onto a person row since the last kept list. */
165
+ export const hasLegacyBots = (database) => database.prepare("SELECT 1 FROM sender_bots WHERE person_id > 0 LIMIT 1").get() !== undefined;
166
+ /**
167
+ * A bot a build before version 75 sorted after the upgrade holds its person row's identities there: they move to the
168
+ * bot, as the upgrade moved the others. The caller holds the write lock.
169
+ */
170
+ export const settleLegacyBots = (database, at) => {
171
+ const legacy = database.prepare("SELECT id, person_id, author, reason FROM sender_bots WHERE person_id > 0").all();
172
+ for (const row of legacy) {
173
+ const bot = Number(row.id);
174
+ const identities = identitiesOf(database, Number(row.person_id));
175
+ database
176
+ .prepare("UPDATE sender_bots SET person_id = (SELECT min(0, coalesce(min(person_id), 0)) - 1 FROM sender_bots) WHERE id = ?")
177
+ .run(bot);
178
+ const log = { author: row.author, reason: "sorted by a build before store version 75", at };
179
+ intoBot(database, identities, bot, log);
180
+ if (identities.length === 0)
181
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
182
+ }
183
+ };
184
+ const botIdOf = (database, ref) => {
185
+ const id = ref.startsWith(SENDER_BOT_PREFIX) ? ref.slice(SENDER_BOT_PREFIX.length) : "";
186
+ const row = /^[1-9]\d*$/.test(id)
187
+ ? database.prepare("SELECT id FROM sender_bots WHERE id = ?").get(Number(id))
188
+ : undefined;
189
+ if (row === undefined)
190
+ throw new CliError("not_found", `no ${ref} in the store`, { reason: "sender-bot.not-found", reference: ref });
191
+ return Number(row.id);
192
+ };
193
+ const personIdOf = (database, ref) => {
194
+ const uid = ref.startsWith("person:") ? ref.slice("person:".length) : "";
195
+ const found = /^[1-9]\d*$/.test(uid) ? database.prepare("SELECT id FROM persons WHERE id = ?").get(uid) : undefined;
196
+ if (found === undefined)
197
+ throw new CliError("not_found", `no ${ref} in the store`, { reference: ref });
198
+ return currentPerson(database, Number(found.id));
199
+ };
200
+ const identityIdOf = (database, { provider, id }) => {
201
+ const row = database.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?").get(provider, id);
202
+ if (row === undefined)
203
+ throw new CliError("not_found", `no ${provider} identity ${id} in the store`);
204
+ return Number(row.id);
205
+ };
206
+ /** What a move names: a person's identities, a bot's, or one identity. */
207
+ const subjectOf = (database, subject) => {
208
+ if (typeof subject !== "string")
209
+ return { identities: [identityIdOf(database, subject)] };
210
+ if (subject.startsWith(SENDER_BOT_PREFIX)) {
211
+ const bot = botIdOf(database, subject);
212
+ return { bot, identities: botIdentitiesOf(database, bot) };
213
+ }
214
+ const person = personIdOf(database, subject);
215
+ const identities = identitiesOf(database, person);
216
+ const took = identities.length === 0 ? botThatTook(database, person) : undefined;
217
+ return took === undefined ? { person, identities } : { bot: took, identities: botIdentitiesOf(database, took) };
218
+ };
219
+ /** The bot that took every identity of a person, so their `person:` ref still names it. */
220
+ const botThatTook = (database, person) => {
221
+ const row = database
222
+ .prepare("SELECT s.bot_id FROM sender_bot_moves m JOIN sender_bot_identities s ON s.identity_id = m.identity_id " +
223
+ "WHERE m.from_person_id = ? AND m.to_bot_id IS NOT NULL ORDER BY m.id DESC LIMIT 1")
224
+ .get(person);
225
+ return row === undefined ? undefined : Number(row.bot_id);
226
+ };
227
+ const botsOf = (database, ids) => {
228
+ if (ids.length === 0)
229
+ return [];
230
+ const json = JSON.stringify(ids);
231
+ const rows = new Map(database
232
+ .prepare("SELECT id, name, organization_id, author, reason FROM sender_bots WHERE id IN (SELECT value FROM json_each(?))")
233
+ .all(json)
234
+ .map((row) => [Number(row.id), row]));
235
+ const identities = new Map();
236
+ for (const row of database
237
+ .prepare("SELECT s.bot_id, i.provider, i.external_id, i.name, i.username, i.phone FROM sender_bot_identities s " +
238
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) ORDER BY i.id")
239
+ .all(json)) {
240
+ const held = identities.get(Number(row.bot_id)) ?? [];
241
+ held.push({
242
+ provider: String(row.provider),
243
+ id: String(row.external_id),
244
+ name: row.name == null ? null : String(row.name),
245
+ username: row.username == null ? null : String(row.username),
246
+ phone: row.phone == null ? null : String(row.phone),
247
+ });
248
+ identities.set(Number(row.bot_id), held);
249
+ }
250
+ const counts = new Map();
251
+ for (const row of database
252
+ .prepare("SELECT s.bot_id AS bot, count(*) AS n, max(m.sent_at) AS at FROM sender_bot_identities s " +
253
+ "JOIN messages m ON m.sender_identity_id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) " +
254
+ "AND m.deleted_at IS NULL AND m.outgoing IS NOT 1 GROUP BY 1 UNION ALL " +
255
+ "SELECT s.bot_id, count(*), max(coalesce(e.sent_at, e.received_at)) FROM sender_bot_identities s " +
256
+ "JOIN emails e ON e.from_identity_id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) " +
257
+ "AND e.deleted_at IS NULL AND e.outgoing IS NOT 1 GROUP BY 1")
258
+ .all(json, json)) {
259
+ const was = counts.get(Number(row.bot)) ?? { n: 0, at: null };
260
+ const at = row.at == null ? was.at : Math.max(Number(row.at), was.at ?? 0);
261
+ counts.set(Number(row.bot), { n: was.n + Number(row.n), at });
262
+ }
263
+ const sent = sentMailOf(database, ids, "bot");
264
+ return ids.flatMap((id) => {
265
+ const row = rows.get(id);
266
+ if (row === undefined)
267
+ return [];
268
+ const held = identities.get(id) ?? [];
269
+ const first = held.find((one) => one.name !== null) ?? held[0];
270
+ const emails = held.flatMap((one) => (one.provider === "email" ? [one.id] : []));
271
+ const name = row.name == null ? null : String(row.name);
272
+ const counted = counts.get(id);
273
+ return [
274
+ {
275
+ bot: `${SENDER_BOT_PREFIX}${id}`,
276
+ name,
277
+ displayName: displayName(name, {
278
+ name: first?.name ?? null,
279
+ username: first?.username ?? null,
280
+ phone: first?.phone ?? null,
281
+ email: emails[0] ?? null,
282
+ }),
283
+ organization: row.organization_id == null ? null : `organization:${Number(row.organization_id)}`,
284
+ author: row.author,
285
+ reason: row.reason == null ? null : String(row.reason),
286
+ identities: held.map(({ phone: _, ...one }) => one),
287
+ messagesFrom: counted?.n ?? 0,
288
+ lastContact: counted?.at == null ? null : new Date(counted.at).toISOString(),
289
+ ...senderSignalsOf(sent.get(id) ?? [], { addresses: emails, ownerWrote: false, chatted: false }),
290
+ },
291
+ ];
292
+ });
293
+ };
294
+ const movesOf = (database, bot) => database
295
+ .prepare("SELECT m.*, i.provider, i.external_id FROM sender_bot_moves m JOIN identities i ON i.id = m.identity_id " +
296
+ "WHERE m.from_bot_id = ? OR m.to_bot_id = ? ORDER BY m.id")
297
+ .all(bot, bot)
298
+ .map((row) => ({
299
+ identity: { provider: String(row.provider), id: String(row.external_id) },
300
+ from: refOf({
301
+ ...(row.from_person_id == null ? {} : { person: Number(row.from_person_id) }),
302
+ ...(row.from_bot_id == null ? {} : { bot: Number(row.from_bot_id) }),
303
+ }),
304
+ to: refOf({
305
+ ...(row.to_person_id == null ? {} : { person: Number(row.to_person_id) }),
306
+ ...(row.to_bot_id == null ? {} : { bot: Number(row.to_bot_id) }),
307
+ }),
308
+ author: row.author,
309
+ reason: row.reason == null ? null : String(row.reason),
310
+ at: new Date(Number(row.created_at)).toISOString(),
311
+ }));
312
+ const detailsOf = (database, bot) => {
313
+ const [found] = botsOf(database, [bot]);
314
+ if (found === undefined)
315
+ throw new CliError("not_found", `no ${SENDER_BOT_PREFIX}${bot} in the store`, { reason: "sender-bot.not-found" });
316
+ return { ...found, moves: movesOf(database, bot) };
317
+ };
318
+ /** The sender bots, by name; a bot a build before version 75 sorted shows once a list has settled it. */
319
+ export const listBots = (database, options) => {
320
+ const { limit, offset = 0 } = options;
321
+ const where = [HOLDS];
322
+ const params = [];
323
+ if (options.query !== undefined) {
324
+ const text = options.query.trim();
325
+ if (text.length < MIN_QUERY)
326
+ throw new CliError("validation_error", `a bots search takes at least ${MIN_QUERY} characters, got "${options.query}"`, { reason: "query.short-text" });
327
+ const like = (form) => `%${form.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
328
+ where.push("(b.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM sender_bot_identities s JOIN identities i ON " +
329
+ "i.id = s.identity_id WHERE s.bot_id = b.id AND (i.name_folded LIKE ? ESCAPE '\\' " +
330
+ "OR i.external_id LIKE ? ESCAPE '\\' OR i.username LIKE ? ESCAPE '\\')))");
331
+ params.push(like(text), like(fold(text)), like(text), like(text));
332
+ }
333
+ if (options.organization !== undefined) {
334
+ const id = options.organization.startsWith("organization:")
335
+ ? options.organization.slice("organization:".length)
336
+ : "";
337
+ if (!/^[1-9]\d*$/.test(id))
338
+ throw new CliError("validation_error", `an organization is organization:<id>, got "${options.organization}"`);
339
+ where.push("b.organization_id = ?");
340
+ params.push(Number(id));
341
+ }
342
+ return read(database, () => {
343
+ const filter = where.join(" AND ");
344
+ const total = Number(database.prepare(`SELECT count(*) AS n FROM sender_bots b WHERE ${filter}`).get(...params)?.n);
345
+ const ids = database
346
+ .prepare(`SELECT b.id FROM sender_bots b WHERE ${filter} ORDER BY ${SHOWN} COLLATE NOCASE, b.id LIMIT ? OFFSET ?`)
347
+ .all(...params, limit, offset)
348
+ .map((row) => Number(row.id));
349
+ return { items: botsOf(database, ids), hasMore: total > offset + limit, total };
350
+ });
351
+ };
352
+ /** One sender bot with its identities and every move to or from it. */
353
+ export const showBot = (database, ref) => read(database, () => detailsOf(database, botIdOf(database, ref)));
354
+ /**
355
+ * The owner's word that a person, a bot or one identity is a program, for its whole history: its messages stay where
356
+ * they are, and no rule gives it back. `bot` joins it to a stored bot; else a bot that already holds it keeps it, or a
357
+ * new one takes it. A person every identity left is hidden, and a move back gives their uid back.
358
+ */
359
+ export const moveToBot = (context, subject, options = {}) => {
360
+ const { database } = context;
361
+ return write(database, () => {
362
+ const at = context.now();
363
+ settleLegacyBots(database, at);
364
+ const log = { author: "owner", reason: options.reason ?? null, at };
365
+ const chosen = subjectOf(database, subject);
366
+ const people = new Set(chosen.identities.flatMap((one) => holderOf(database, one).person ?? []));
367
+ if ([...people].some((person) => isOwner(context, person)))
368
+ throw new CliError("validation_error", "the owner's own person is never a bot", { reason: "sender-bot.owner" });
369
+ if (chosen.identities.length === 0)
370
+ throw new CliError("validation_error", `${String(subject)} holds no identity to move`, {
371
+ reason: "sender-bot.empty",
372
+ });
373
+ const held = new Set(chosen.identities.flatMap((one) => holderOf(database, one).bot ?? []));
374
+ const target = options.bot !== undefined
375
+ ? botIdOf(database, options.bot)
376
+ : (chosen.bot ?? (held.size === 1 && people.size === 0 ? [...held][0] : undefined));
377
+ const bot = target ?? createBot(database, log, options.name ?? null);
378
+ database
379
+ .prepare("UPDATE sender_bots SET author = 'owner', name = coalesce(?, name), updated_at = ? WHERE id = ?")
380
+ .run(options.name ?? null, at, bot);
381
+ const left = intoBot(database, chosen.identities, bot, log);
382
+ for (const [person, gone] of left)
383
+ if (identitiesOf(database, person).length > 0)
384
+ renameAfterLeaving(context, person, gone);
385
+ groupByDomain(database, [{ id: bot, displayName: options.name ?? null, holds: true, bot: true }], at);
386
+ return detailsOf(database, bot);
387
+ });
388
+ };
389
+ /**
390
+ * The owner's word that a bot, a person or one identity is a person, for its whole history; no rule makes it a bot
391
+ * again. `person` takes it; else each identity goes back to the person it came from, or a person of its own. Said of a
392
+ * person, it keeps them one. Answers the person the first identity is on.
393
+ */
394
+ export const moveToPerson = (context, subject, options = {}) => {
395
+ const { database } = context;
396
+ return write(database, () => {
397
+ const at = context.now();
398
+ settleLegacyBots(database, at);
399
+ const log = { author: "owner", reason: options.reason ?? null, at };
400
+ const chosen = subjectOf(database, subject);
401
+ const target = options.person === undefined ? undefined : personIdOf(database, options.person);
402
+ if (chosen.identities.length === 0)
403
+ throw new CliError("validation_error", `${String(subject)} holds no identity to move`, {
404
+ reason: "sender-bot.empty",
405
+ });
406
+ if (chosen.person !== undefined && target !== undefined && target !== chosen.person) {
407
+ for (const identity of chosen.identities)
408
+ logMove(database, identity, { person: chosen.person }, { person: target }, log);
409
+ mergePerson(context, chosen.person, target, { method: "manual", by: "owner" });
410
+ return recordOf(context, target);
411
+ }
412
+ const went = outOfBot(database, chosen.identities, target, log);
413
+ for (const identity of chosen.identities) {
414
+ if (went.has(identity))
415
+ continue;
416
+ const person = holderOf(database, identity).person;
417
+ if (person === undefined)
418
+ continue;
419
+ const to = target ?? person;
420
+ if (to !== person) {
421
+ move(context, identity, person, to, { method: "manual", by: "owner" });
422
+ renameAfterLeaving(context, person, [identity]);
423
+ }
424
+ logMove(database, identity, { person }, { person: to }, log);
425
+ went.set(identity, to);
426
+ }
427
+ releaseDomainHolds(database, chosen.identities);
428
+ const first = went.get(chosen.identities[0]);
429
+ return recordOf(context, first ?? target ?? chosen.person);
430
+ });
431
+ };
@@ -22,6 +22,11 @@ export interface SentMail {
22
22
  }
23
23
  /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
24
24
  export declare const DISCUSSION_SENDERS = 3;
25
+ /** How one email reached the owner, and the signal that says so. */
26
+ export declare const reachOfOne: (mail: SentMail) => {
27
+ reach: Reach;
28
+ signal?: SenderSignal;
29
+ };
25
30
  /**
26
31
  * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
27
32
  * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
@@ -35,8 +40,13 @@ export declare const senderSignalsOf: (mail: readonly SentMail[], { addresses, o
35
40
  signals: SenderSignal[];
36
41
  reach: Reach | null;
37
42
  };
43
+ export declare const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
44
+ /** The senders of each of these List-Ids, through `emails_by_list_id`. */
45
+ export declare const LIST_SENDERS: string;
46
+ /** `bob+news@x` and `bob@x` are one sender. */
47
+ export declare const senderKey: (address: string) => string;
38
48
  /**
39
- * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
40
- * reads every stored email's List-Id once to tell a discussion list from a newsletter.
49
+ * The mail each of these people, or sender bots, sent the owner, as `senderSignalsOf` reads it. Asked for a page
50
+ * only: the senders of their List-Ids tell a discussion list from a newsletter.
41
51
  */
42
- export declare const sentMailOf: (database: CacheDatabase, people: readonly number[]) => Map<number, SentMail[]>;
52
+ export declare const sentMailOf: (database: CacheDatabase, people: readonly number[], holder?: "person" | "bot") => Map<number, SentMail[]>;
@@ -7,7 +7,8 @@ import { SMALL_GROUP_MEMBERS } from "./person-ties.js";
7
7
  export const REACHES = ["direct", "group", "broadcast"];
8
8
  /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
9
9
  export const DISCUSSION_SENDERS = 3;
10
- const reachOfOne = (mail) => {
10
+ /** How one email reached the owner, and the signal that says so. */
11
+ export const reachOfOne = (mail) => {
11
12
  if (mail.discussionList)
12
13
  return { reach: "group", signal: "discussion-list" };
13
14
  if (mail.oneClick)
@@ -52,19 +53,25 @@ export const senderSignalsOf = (mail, { addresses, ownerWrote, chatted }) => {
52
53
  const reach = ownerWrote ? "direct" : (voted ?? (chatted ? "direct" : null));
53
54
  return { signals: [...signals], reach };
54
55
  };
55
- const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
56
+ export const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
57
+ /** The senders of each of these List-Ids, through `emails_by_list_id`. */
58
+ export const LIST_SENDERS = `SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
59
+ `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`;
56
60
  /** `bob+news@x` and `bob@x` are one sender. */
57
- const senderKey = (address) => address.toLowerCase().replace(/\+[^@]*@/, "@");
61
+ export const senderKey = (address) => address.toLowerCase().replace(/\+[^@]*@/, "@");
58
62
  /**
59
- * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
60
- * reads every stored email's List-Id once to tell a discussion list from a newsletter.
63
+ * The mail each of these people, or sender bots, sent the owner, as `senderSignalsOf` reads it. Asked for a page
64
+ * only: the senders of their List-Ids tell a discussion list from a newsletter.
61
65
  */
62
- export const sentMailOf = (database, people) => {
66
+ export const sentMailOf = (database, people, holder = "person") => {
63
67
  const found = new Map();
64
68
  if (people.length === 0)
65
69
  return found;
70
+ const held = holder === "person"
71
+ ? { owner: "l.person_id", join: "identity_links l" }
72
+ : { owner: "l.bot_id", join: "sender_bot_identities l" };
66
73
  const rows = database
67
- .prepare("SELECT l.person_id AS person, " +
74
+ .prepare(`SELECT ${held.owner} AS person, ` +
68
75
  `${LIST_ID} AS list, json_extract(e.headers, '$."auto-submitted"') IS NOT NULL AS auto, ` +
69
76
  "json_extract(e.headers, '$.\"null-return-path\"') IS 1 AS null_return, " +
70
77
  "json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 AS one_click, " +
@@ -73,16 +80,13 @@ export const sentMailOf = (database, people) => {
73
80
  "WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk, " +
74
81
  "CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
75
82
  "(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients " +
76
- "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
77
- "WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND l.person_id IN (SELECT value FROM json_each(?))")
83
+ `FROM emails e JOIN ${held.join} ON l.identity_id = e.from_identity_id ` +
84
+ `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${held.owner} IN (SELECT value FROM json_each(?))`)
78
85
  .all(JSON.stringify(people));
79
86
  const lists = [...new Set(rows.flatMap((row) => (typeof row.list === "string" ? [row.list] : [])))];
80
87
  const senders = new Map();
81
88
  if (lists.length > 0)
82
- for (const row of database
83
- .prepare(`SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
84
- `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`)
85
- .all(JSON.stringify(lists))) {
89
+ for (const row of database.prepare(LIST_SENDERS).all(JSON.stringify(lists))) {
86
90
  const list = String(row.list);
87
91
  const held = senders.get(list) ?? new Set();
88
92
  held.add(senderKey(String(row.address)));
@@ -14,15 +14,15 @@ export interface TrackerItem<K extends TrackerKind = TrackerKind> {
14
14
  export interface TrackerFilter {
15
15
  /** A comment's issue, an issue's, a state's or a label's team. */
16
16
  parent?: string;
17
- /** Issues only. */
18
- assignee?: string | null;
19
- project?: string;
20
- state?: string;
17
+ /** Issues only; several ids match any of them, as a name every team's state has. */
18
+ assignee?: string | readonly string[] | null;
19
+ project?: string | readonly string[];
20
+ state?: string | readonly string[];
21
21
  /** Issues whose state is of one of these types. */
22
22
  stateTypes?: readonly StateType[];
23
- label?: string;
23
+ label?: string | readonly string[];
24
24
  /** Issues only; `null`, the issues in no sprint. */
25
- sprint?: string | null;
25
+ sprint?: string | readonly string[] | null;
26
26
  /** Archived rows too; absent, only the live ones. */
27
27
  archived?: boolean;
28
28
  limit?: number;
@@ -59,16 +59,18 @@ export interface TrackerStore {
59
59
  /**
60
60
  * Upserts records of one kind; a field a record leaves out keeps its stored value, and a record listed again after
61
61
  * the tracker stopped listing it comes back. A record the tracker calls `deleted` is marked deleted, and an issue
62
- * takes its comments with it. Answers how many changed: a row read again as it was stored is not counted.
62
+ * takes its comments with it. Answers how many changed: a row read again as it was stored is not counted. `state`
63
+ * is the account's sync state saved in the same transaction, as a sync's cursor after the page.
63
64
  */
64
- save<K extends TrackerKind>(key: AccountKey, kind: K, records: readonly TrackerRecords[K][], now: number): Promise<number>;
65
+ save<K extends TrackerKind>(key: AccountKey, kind: K, records: readonly TrackerRecords[K][], now: number, state?: Record<string, string>): Promise<number>;
65
66
  /**
66
67
  * After a complete list of the kind's ids: marks deleted every stored one the list lacks that has not been synced
67
68
  * since `before`, so a row saved while the list was read is never taken for a deleted one, and the comments of an
68
- * issue it marks. Answers how many of the kind.
69
+ * issue it marks. Answers how many of the kind. `state` is saved in the same transaction; a dry run writes nothing.
69
70
  */
70
71
  removeUnlisted(key: AccountKey, kind: TrackerKind, listed: readonly string[], before: number, now: number, options?: {
71
72
  dryRun?: boolean;
73
+ state?: Record<string, string>;
72
74
  }): Promise<number>;
73
75
  get<K extends TrackerKind>(key: AccountKey, kind: K, externalId: string): Promise<TrackerItem<K> | undefined>;
74
76
  /** An issue by its readable key (`ENG-12`), in any letter case. */