@wirecat/cli-core 0.628.0 → 0.630.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 (53) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/dist/cli/base-stages-command.d.ts +5 -0
  3. package/dist/cli/base-stages-command.js +75 -1
  4. package/dist/cli/stage-suggest.d.ts +48 -0
  5. package/dist/cli/stage-suggest.js +105 -0
  6. package/dist/domain/name-variants.d.ts +21 -0
  7. package/dist/domain/name-variants.js +147 -0
  8. package/dist/entities/contact-activity.d.ts +2 -0
  9. package/dist/entities/contact-activity.js +2 -0
  10. package/dist/entities/contact-context.d.ts +6 -0
  11. package/dist/entities/identity.d.ts +3 -0
  12. package/dist/entities/identity.js +3 -0
  13. package/dist/entities/index.d.ts +10 -0
  14. package/dist/entities/person.d.ts +2 -0
  15. package/dist/errors/reasons.js +8 -0
  16. package/dist/store/identity-links.d.ts +3 -2
  17. package/dist/store/identity-links.js +3 -2
  18. package/dist/store/people.d.ts +3 -0
  19. package/dist/store/people.js +2 -1
  20. package/dist/store/sqlite/base-suggest.d.ts +4 -1
  21. package/dist/store/sqlite/base-suggest.js +5 -3
  22. package/dist/store/sqlite/chats.d.ts +2 -0
  23. package/dist/store/sqlite/chats.js +11 -11
  24. package/dist/store/sqlite/crm.js +6 -3
  25. package/dist/store/sqlite/identity-link-rows.d.ts +5 -2
  26. package/dist/store/sqlite/identity-link-rows.js +4 -4
  27. package/dist/store/sqlite/identity-proposals.js +10 -6
  28. package/dist/store/sqlite/mail-findings.js +3 -1
  29. package/dist/store/sqlite/manifest.js +3 -0
  30. package/dist/store/sqlite/migrations.generated.js +75 -0
  31. package/dist/store/sqlite/name-traces.d.ts +8 -3
  32. package/dist/store/sqlite/name-traces.js +26 -21
  33. package/dist/store/sqlite/note-index.js +2 -1
  34. package/dist/store/sqlite/own-identities.d.ts +5 -3
  35. package/dist/store/sqlite/own-identities.js +66 -12
  36. package/dist/store/sqlite/people-list.d.ts +5 -1
  37. package/dist/store/sqlite/people-list.js +170 -20
  38. package/dist/store/sqlite/person-links.d.ts +10 -2
  39. package/dist/store/sqlite/person-links.js +54 -10
  40. package/dist/store/sqlite/person-match-scan.js +97 -17
  41. package/dist/store/sqlite/person-merges.js +3 -1
  42. package/dist/store/sqlite/person-ties.d.ts +7 -4
  43. package/dist/store/sqlite/person-ties.js +59 -23
  44. package/dist/store/sqlite/roster.js +3 -4
  45. package/dist/store/sqlite/schema.d.ts +80 -0
  46. package/dist/store/sqlite/schema.js +9 -1
  47. package/dist/store/sqlite/task-candidates.js +2 -2
  48. package/dist/store/sqlite/task-titles.d.ts +12 -0
  49. package/dist/store/sqlite/task-titles.js +42 -0
  50. package/dist/store/sqlite/tasks.js +2 -1
  51. package/dist/store/sqlite/work-tasks.js +2 -1
  52. package/dist/store/types.d.ts +3 -0
  53. package/package.json +2 -2
@@ -1,26 +1,80 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { displayName } from "../../domain/display-names.js";
3
+ import { nameSkeletons } from "../../domain/name-variants.js";
2
4
  import { ownerPerson } from "./actors.js";
5
+ import { openIdentityLink } from "./identity-proposals.js";
3
6
  import { mergePerson, personOf } from "./person-links.js";
7
+ import { RULE } from "./person-match-scan.js";
4
8
  import { separated } from "./person-separation.js";
5
9
  import { write } from "./transaction.js";
10
+ const ACCOUNT_REASON = "an account you connected, under another name: a mailbox or messenger you read may be someone else's";
11
+ const ownerNames = ({ database }, owner) => database
12
+ .prepare("SELECT i.name FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ?")
13
+ .all(owner)
14
+ .map(({ name }) => new Set(nameSkeletons(displayName(typeof name === "string" ? name : null))))
15
+ .filter((words) => words.size > 0);
6
16
  /**
7
- * An account's own identity (same provider and id as the account) is the owner. Messengers save it like anyone
8
- * else's, as a person of its own, so the owner's name counted as a contact's. Links it, and whoever was linked
9
- * with it, to the owner, unless the owner separated that person from themselves; nothing to do once done.
17
+ * Whether an account's own name says it is the owner's: no name to say otherwise, or all of its two or more words are
18
+ * in one of the owner's names, script and spelling aside. Before the owner has a name, only the one account a pass
19
+ * finds counts: of two, one may be a partner's. One word (`Ops`) or another person's name is not.
20
+ */
21
+ const ownersName = (name, owner, alone) => {
22
+ const words = nameSkeletons(displayName(name));
23
+ if (words.length === 0)
24
+ return true;
25
+ if (owner.length === 0)
26
+ return alone;
27
+ return words.length >= 2 && owner.some((known) => words.every((word) => known.has(word)));
28
+ };
29
+ /**
30
+ * An account's own identity (same provider and id as the account) is usually the owner. Messengers save it like anyone
31
+ * else's, as a person of its own, so the owner's name counted as a contact's. Links that person to the owner when every
32
+ * account identity on it carries the owner's name, unless the owner separated that person from themselves. Under
33
+ * another name, such as a partner's mailbox or a spouse's messenger the owner reads, it only proposes: nothing joins
34
+ * anyone to the owner without the owner. A bot is never the owner. Nothing to do once done.
10
35
  */
11
36
  export const linkOwnIdentities = (context) => {
12
37
  const owner = ownerPerson(context.database).id;
13
- const strays = context.database
14
- .prepare("SELECT DISTINCT l.person_id AS person FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
15
- "JOIN accounts a ON a.provider = i.provider AND a.external_id = i.external_id WHERE l.person_id <> ?")
16
- .all(owner);
17
- if (strays.length === 0)
38
+ const byPerson = new Map();
39
+ for (const row of context.database
40
+ .prepare("SELECT DISTINCT l.person_id AS person, i.id AS identity, i.name, " +
41
+ "(i.bot = 1 OR i.provider LIKE '%-bot') AS bot FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
42
+ "JOIN accounts a ON a.provider = i.provider AND a.external_id = i.external_id WHERE l.person_id <> ? " +
43
+ "ORDER BY i.id")
44
+ .all(owner)) {
45
+ const person = Number(row.person);
46
+ if (row.bot === 1)
47
+ continue;
48
+ const own = byPerson.get(person) ?? [];
49
+ own.push({ identity: Number(row.identity), person, name: typeof row.name === "string" ? row.name : null });
50
+ byPerson.set(person, own);
51
+ }
52
+ if (byPerson.size === 0)
18
53
  return 0;
19
54
  return write(context.database, () => {
20
- const joining = strays.map(({ person }) => Number(person)).filter((person) => !separated(context, person, owner));
21
- for (const person of joining)
22
- mergePerson(context, person, owner, { method: "account", by: "rules" });
23
- return joining.length;
55
+ let joined = 0;
56
+ for (const [person, own] of byPerson) {
57
+ if (separated(context, person, owner))
58
+ continue;
59
+ const names = ownerNames(context, owner);
60
+ const other = own.find(({ name }) => !ownersName(name, names, byPerson.size === 1));
61
+ if (other === undefined) {
62
+ mergePerson(context, person, owner, { method: "account", by: "rules" });
63
+ joined += 1;
64
+ continue;
65
+ }
66
+ openIdentityLink(context, {
67
+ identity: other.identity,
68
+ with: null,
69
+ from: person,
70
+ to: owner,
71
+ joins: "person",
72
+ signal: "account",
73
+ by: RULE,
74
+ reason: ACCOUNT_REASON,
75
+ });
76
+ }
77
+ return joined;
24
78
  });
25
79
  };
26
80
  /** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
@@ -1,5 +1,5 @@
1
1
  import { type KindSignal, type PersonKind } from "../../domain/person-kinds.js";
2
- import type { CacheDatabase } from "../driver.js";
2
+ import { type CacheDatabase } from "../driver.js";
3
3
  import { type ShownBecause } from "./person-ties.js";
4
4
  export declare const PEOPLE_SORTS: readonly ["interactions", "recent", "name", "tasks"];
5
5
  export type PeopleSort = (typeof PEOPLE_SORTS)[number];
@@ -29,6 +29,8 @@ export interface ListedPerson {
29
29
  /** The one to show beside the name: the phone, else the email, else `@username`. */
30
30
  contact: string | null;
31
31
  username: string | null;
32
+ /** Where `username` comes from, `telegram` or `max`, so `@name` is shown as that messenger's. */
33
+ usernameSource: string | null;
32
34
  phone: string | null;
33
35
  email: string | null;
34
36
  /** Messages and mail this person sent, every account together. */
@@ -50,6 +52,8 @@ export interface SimilarPerson extends ListedPerson {
50
52
  /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
51
53
  sameName: boolean;
52
54
  }
55
+ /** How many people of each kind match the query, every kind at once. */
56
+ export declare const countPeople: (database: CacheDatabase, query?: string) => Record<PersonKind, number>;
53
57
  /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
54
58
  export declare const listPeople: (database: CacheDatabase, options: PeopleListOptions) => PeopleList;
55
59
  /**
@@ -1,11 +1,14 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
3
3
  import { displayName, isReadable, nameKey } from "../../domain/display-names.js";
4
+ import { spellings, variantKey } from "../../domain/name-variants.js";
4
5
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
6
+ import { isQueryOnly } from "../driver.js";
5
7
  import { fold } from "../normalize.js";
6
8
  import { mergedAwaySql } from "./merged-persons.js";
7
9
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
8
10
  import { mergedAssignees } from "./task-board.js";
11
+ import { read, writeBatch } from "./transaction.js";
9
12
  export const PEOPLE_SORTS = ["interactions", "recent", "name", "tasks"];
10
13
  const MIN_QUERY = 3;
11
14
  const ftsPhrase = (text) => `"${text.replaceAll('"', '""')}"`;
@@ -15,10 +18,14 @@ const matching = (query) => {
15
18
  const text = query.trim();
16
19
  if (text.length < MIN_QUERY)
17
20
  throw new CliError("validation_error", `a people search takes at least ${MIN_QUERY} characters, got "${query}"`);
21
+ const forms = [...new Set([text, ...spellings(text)])];
22
+ const like = (form) => `%${form.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
18
23
  return {
19
24
  sql: " AND (p.id IN (SELECT l.person_id FROM identity_links l WHERE l.identity_id IN " +
20
- "(SELECT rowid FROM identities_fts WHERE identities_fts MATCH ?)) OR p.name LIKE ? ESCAPE '\\')",
21
- params: [ftsPhrase(text), `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`],
25
+ "(SELECT rowid FROM identities_fts WHERE identities_fts MATCH ?)) OR " +
26
+ forms.map(() => "p.name LIKE ? ESCAPE '\\'").join(" OR ") +
27
+ ")",
28
+ params: [forms.map(ftsPhrase).join(" OR "), ...forms.map(like)],
22
29
  };
23
30
  };
24
31
  const TASK_COUNTS = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)) " +
@@ -61,6 +68,7 @@ const factsOf = (database, scope) => {
61
68
  const person = Number(row.person);
62
69
  const one = facts.get(person) ?? {
63
70
  username: null,
71
+ usernameSource: null,
64
72
  phone: null,
65
73
  email: null,
66
74
  emails: [],
@@ -69,7 +77,10 @@ const factsOf = (database, scope) => {
69
77
  organization: false,
70
78
  };
71
79
  const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
72
- one.username ??= text(row.username);
80
+ if (one.username === null && text(row.username) !== null) {
81
+ one.username = text(row.username);
82
+ one.usernameSource = String(row.provider);
83
+ }
73
84
  one.phone ??= text(row.phone) ?? (row.provider === "phone" ? text(row.external_id) : null);
74
85
  one.email ??= email;
75
86
  if (email !== null)
@@ -121,7 +132,7 @@ const kindOf = (shown, facts, ties, mail) => {
121
132
  return { kind: "person", signals: ties };
122
133
  };
123
134
  /** Each person with their kind, contact and counts; the last contact is added for the page alone. */
124
- const classified = (database, people, scope, reasons = shownReasons(database)) => {
135
+ const classified = (database, people, scope, reasons = shownReasons(database, scope === "all" ? undefined : scope)) => {
125
136
  const facts = factsOf(database, scope);
126
137
  const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
127
138
  const messages = countsOf(database, MESSAGE_COUNTS(scope), ...scopeParams(scope));
@@ -147,6 +158,7 @@ const classified = (database, people, scope, reasons = shownReasons(database)) =
147
158
  tasks: tasks.get(id) ?? 0,
148
159
  contact: contact.phone ?? contact.email ?? (contact.username === null ? null : `@${contact.username.replace(/^@/, "")}`),
149
160
  ...contact,
161
+ usernameSource: own?.usernameSource ?? null,
150
162
  messagesFrom: (messages.get(id) ?? 0) + (mail.get(id)?.n ?? 0),
151
163
  ties,
152
164
  };
@@ -163,25 +175,160 @@ const withLastContact = (database, people, known) => {
163
175
  /** Sorted as read, case and accents aside; a name with nothing to read goes last. */
164
176
  const nameOrderOf = (shown) => `${isReadable(shown) ? 0 : 1}${fold(shown ?? "")}`;
165
177
  const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOrder ? 1 : a.id - b.id;
166
- /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
167
- export const listPeople = (database, options) => {
168
- const { kind = "person", sort = "interactions", limit, offset = 0 } = options;
178
+ /**
179
+ * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
180
+ * every stored one is worked out again on the next list.
181
+ */
182
+ const KIND_RULES = "2";
183
+ const RULES_KEY = "people.kind_rules";
184
+ /** Past this many people to work out, one pass over everyone beats a lookup per person. */
185
+ const WHOLE_PASS = 20_000;
186
+ /** About 0.7 s of work on 113,000 people: well inside another writer's 5 s wait for the lock. */
187
+ const UNDER_LOCK = 5_000;
188
+ const TRIES = 3;
189
+ const dataVersion = (database) => Number(Object.values(database.prepare("PRAGMA data_version").get() ?? {})[0]);
190
+ const rulesOf = (database) => {
191
+ const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(RULES_KEY);
192
+ return row === undefined ? undefined : String(row.value);
193
+ };
194
+ const candidateOf = (row) => ({
195
+ id: Number(row.id),
196
+ name: row.name == null ? null : String(row.name),
197
+ owner: Number(row.owner) === 1,
198
+ });
199
+ /** Stored for a person a merge emptied, so a list leaves them out without asking each person. */
200
+ const MERGED = "merged";
201
+ /** The people whose stored kind is not current, worked out; `undefined` when there are none. */
202
+ const workOut = (database, all, most) => {
203
+ const rows = database
204
+ .prepare(`SELECT id, name, owner, ${mergedAwaySql("p")} AS merged FROM persons p` +
205
+ `${all ? "" : " WHERE kind IS NULL"}${most === undefined ? "" : ` LIMIT ${most + 1}`}`)
206
+ .all();
207
+ if (rows.length === 0 && !all)
208
+ return undefined;
209
+ if (most !== undefined && rows.length > most)
210
+ return undefined;
211
+ const merged = new Set(rows.filter((row) => Number(row.merged) === 1).map((row) => Number(row.id)));
212
+ const stale = rows.map(candidateOf);
213
+ const scope = all || stale.length > WHOLE_PASS ? "all" : stale.map(({ id }) => id);
214
+ const contacts = lastContacts(database, scope);
215
+ return classified(database, stale, scope).map((person) => ({
216
+ ...person,
217
+ kind: merged.has(person.id) ? MERGED : person.kind,
218
+ lastContact: contacts.get(person.id),
219
+ }));
220
+ };
221
+ const keep = (database, worked) => {
222
+ const row = database.prepare("UPDATE persons SET kind = ?, name_order = ?, messages_from = ?, task_count = ?, last_contact = ? WHERE id = ?");
223
+ for (const person of worked)
224
+ row.run(person.kind, person.nameOrder, person.messagesFrom, person.tasks, person.lastContact ?? null, person.id);
225
+ database
226
+ .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " +
227
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
228
+ .run(RULES_KEY, KIND_RULES, Date.now());
229
+ };
230
+ /**
231
+ * Works out and keeps the kind, name order and counts of every person whose stored ones the triggers cleared.
232
+ * A few, as a sync leaves, are worked out under the write lock. Everyone, after an upgrade, would hold the lock for
233
+ * seconds: that pass runs outside it and is kept only when no other process wrote meanwhile, else it runs again.
234
+ * Answers whether every stored one is current.
235
+ */
236
+ const storeKinds = (database) => {
237
+ if (isQueryOnly(database))
238
+ return (rulesOf(database) === KIND_RULES &&
239
+ database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
240
+ if (rulesOf(database) === KIND_RULES &&
241
+ database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined)
242
+ return true;
243
+ const few = writeBatch(database, () => {
244
+ if (rulesOf(database) !== KIND_RULES)
245
+ return false;
246
+ const worked = workOut(database, false, UNDER_LOCK);
247
+ if (worked !== undefined)
248
+ keep(database, worked);
249
+ return (worked !== undefined || database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
250
+ });
251
+ if (few)
252
+ return true;
253
+ for (let attempt = 0; attempt < TRIES; attempt++) {
254
+ const before = dataVersion(database);
255
+ const worked = read(database, () => workOut(database, rulesOf(database) !== KIND_RULES));
256
+ if (worked === undefined)
257
+ return true;
258
+ const kept = writeBatch(database, () => {
259
+ if (dataVersion(database) !== before)
260
+ return false;
261
+ keep(database, worked);
262
+ return true;
263
+ });
264
+ if (kept)
265
+ return true;
266
+ }
267
+ return false;
268
+ };
269
+ const STORED_ORDER = {
270
+ interactions: "p.messages_from DESC, ",
271
+ tasks: "p.task_count DESC, ",
272
+ recent: "coalesce(p.last_contact, 0) DESC, ",
273
+ name: "",
274
+ };
275
+ const noCounts = () => Object.fromEntries(PERSON_KINDS.map((one) => [one, 0]));
276
+ const storedCounts = (database, filter) => {
277
+ const counts = noCounts();
278
+ for (const row of database
279
+ .prepare(`SELECT p.kind, count(*) AS n FROM persons p WHERE p.kind <> '${MERGED}'${filter.sql} GROUP BY 1`)
280
+ .all(...filter.params))
281
+ if (PERSON_KINDS.includes(row.kind))
282
+ counts[row.kind] = Number(row.n);
283
+ return counts;
284
+ };
285
+ const checked = (options) => {
286
+ const { kind = "person", sort = "interactions" } = options;
169
287
  if (kind !== "all" && !PERSON_KINDS.includes(kind))
170
288
  throw new CliError("validation_error", `a person's kind is one of ${PERSON_KINDS.join(", ")} or all, got "${kind}"`);
171
289
  if (!PEOPLE_SORTS.includes(sort))
172
290
  throw new CliError("validation_error", `people sort by ${PEOPLE_SORTS.join(", ")}, got "${sort}"`);
173
- const filter = matching(options.query);
291
+ return { kind, sort, filter: matching(options.query) };
292
+ };
293
+ /** How many people of each kind match the query, every kind at once. */
294
+ export const countPeople = (database, query) => {
295
+ const filter = matching(query);
296
+ return storeKinds(database) ? storedCounts(database, filter) : listInMemory(database, { limit: 0, query }).counts;
297
+ };
298
+ /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
299
+ export const listPeople = (database, options) => {
300
+ const { kind, sort, filter } = checked(options);
301
+ if (!storeKinds(database))
302
+ return listInMemory(database, options);
303
+ const { limit, offset = 0 } = options;
304
+ return read(database, () => {
305
+ const counts = storedCounts(database, filter);
306
+ const total = kind === "all" ? Object.values(counts).reduce((a, b) => a + b, 0) : counts[kind];
307
+ const rows = database
308
+ .prepare(`SELECT p.id, p.name, p.owner, p.last_contact FROM persons p WHERE p.kind ${kind === "all" ? "<>" : "="} ?` +
309
+ `${filter.sql} ORDER BY p.owner DESC, ${STORED_ORDER[sort]}p.name_order, p.id LIMIT ? OFFSET ?`)
310
+ .all(kind === "all" ? MERGED : kind, ...filter.params, limit, offset);
311
+ const page = rows.map(candidateOf);
312
+ const contacts = new Map(rows.filter((row) => row.last_contact != null).map((row) => [Number(row.id), Number(row.last_contact)]));
313
+ return {
314
+ items: withLastContact(database, classified(database, page, page.map(({ id }) => id)), contacts),
315
+ hasMore: total > offset + limit,
316
+ total,
317
+ counts,
318
+ };
319
+ });
320
+ };
321
+ /** The list worked out for every person on the call, for a read-only store whose stored kinds are not current. */
322
+ const listInMemory = (database, options) => {
323
+ const { kind, sort, filter } = checked(options);
324
+ const { limit, offset = 0 } = options;
174
325
  const candidates = database
175
326
  .prepare(`SELECT p.id, p.name, p.owner FROM persons p WHERE NOT ${mergedAwaySql("p")}${filter.sql}`)
176
327
  .all(...filter.params)
177
- .map((row) => ({
178
- id: Number(row.id),
179
- name: row.name == null ? null : String(row.name),
180
- owner: Number(row.owner) === 1,
181
- }));
328
+ .map(candidateOf);
182
329
  // A search reads only the people it found; a whole list reads everyone once rather than per person.
183
330
  const everyone = classified(database, candidates, options.query === undefined ? "all" : candidates.map(({ id }) => id));
184
- const counts = Object.fromEntries(PERSON_KINDS.map((one) => [one, 0]));
331
+ const counts = noCounts();
185
332
  for (const person of everyone)
186
333
  counts[person.kind] += 1;
187
334
  const chosen = kind === "all" ? everyone : everyone.filter((person) => person.kind === kind);
@@ -203,9 +350,12 @@ export const listPeople = (database, options) => {
203
350
  };
204
351
  };
205
352
  const words = (key) => (key === null ? [] : key.split(" "));
206
- /** Every typed word starts a word of the name, in any order: «iv pet» finds Petrov Ivan. */
353
+ /**
354
+ * Every typed word starts a word of the name, in any order: «iv pet» finds Petrov Ivan. Script and spelling aside,
355
+ * so «Светлана» finds Svetlana (BUG-678).
356
+ */
207
357
  const startsEach = (typed, name) => {
208
- const own = words(nameKey(name));
358
+ const own = words(variantKey(name));
209
359
  return typed.every((word) => own.some((one) => one.startsWith(word)));
210
360
  };
211
361
  /**
@@ -213,9 +363,9 @@ const startsEach = (typed, name) => {
213
363
  * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
214
364
  */
215
365
  export const similarPeople = (database, typed, limit) => {
216
- const key = nameKey(typed);
366
+ const key = variantKey(typed);
217
367
  const wanted = words(key);
218
- const longest = wanted.reduce((a, b) => (b.length > a.length ? b : a), "");
368
+ const longest = words(nameKey(typed)).reduce((a, b) => (b.length > a.length ? b : a), "");
219
369
  if (longest === "")
220
370
  return [];
221
371
  const named = new Map();
@@ -233,7 +383,7 @@ export const similarPeople = (database, typed, limit) => {
233
383
  ? database
234
384
  .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities_fts f JOIN identities i ON i.id = f.rowid " +
235
385
  "JOIN identity_links l ON l.identity_id = i.id WHERE identities_fts MATCH ?")
236
- .all(ftsPhrase(longest))
386
+ .all(spellings(longest).map(ftsPhrase).join(" OR "))
237
387
  : database
238
388
  .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities i " +
239
389
  "JOIN identity_links l ON l.identity_id = i.id WHERE i.name_folded LIKE ? ESCAPE '\\'")
@@ -247,7 +397,7 @@ export const similarPeople = (database, typed, limit) => {
247
397
  .map(([person, names]) => ({
248
398
  person,
249
399
  name: names[0] ?? "",
250
- same: names.some((name) => nameKey(name) === key),
400
+ same: names.some((name) => variantKey(name) === key),
251
401
  }));
252
402
  if (found.length === 0)
253
403
  return [];
@@ -24,6 +24,7 @@ export declare const linkIdentityToPerson: (context: StoreContext, identityPk: n
24
24
  * name: a caller links only what someone decided belongs together, and says how in `method`.
25
25
  */
26
26
  export declare const linkIdentities: (context: StoreContext, person: IdentityRef, other: IdentityRef, options: LinkOptions) => PersonRecord;
27
+ export declare const isOwner: ({ database }: StoreContext, person: number) => boolean;
27
28
  /** The person `mergePerson(one, other)` keeps: `other`, unless `one` is the owner's. */
28
29
  export declare const survivorOf: (context: StoreContext, one: number, other: number) => number;
29
30
  /**
@@ -38,8 +39,10 @@ export declare const noteAddress: (context: StoreContext, ref: IdentityRef, addr
38
39
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
39
40
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
40
41
  * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart. A role address such
41
- * as `info@` joins no one; the scan proposes its people instead. A pair the owner rejected is not joined either: it is
42
- * given back, so the caller proposes it when the evidence is new to the owner.
42
+ * as `info@` and a company's mailbox join no one, here or in the scan. A pair the owner rejected is not joined either: it is
43
+ * given back, so the caller proposes it when the evidence is new to the owner. Nothing joins the owner, or is
44
+ * proposed to them, from an address: a mailbox the owner reads may be someone else's, and only the owner joins anyone
45
+ * to themselves (SEC-177). A bot or service account joins no one.
43
46
  */
44
47
  export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => {
45
48
  identity: number;
@@ -47,6 +50,11 @@ export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, ad
47
50
  from: number;
48
51
  to: number;
49
52
  } | undefined;
53
+ /**
54
+ * A person named after an identity that left them takes the name of the oldest identity they still have, or none: the
55
+ * owner merged with a partner's CRM contact kept the partner's name after the split (BUG-677).
56
+ */
57
+ export declare const renameAfterLeaving: (context: StoreContext, person: number, left: readonly number[]) => void;
50
58
  /** Gives the identity a person of its own again; the ones left keep theirs. */
51
59
  export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options: LinkOptions) => PersonRecord;
52
60
  /** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */
@@ -31,6 +31,8 @@ export const recordOf = ({ orm }, personPk) => {
31
31
  id: identities.externalId,
32
32
  name: identities.name,
33
33
  username: identities.username,
34
+ phone: identities.phone,
35
+ email: identities.email,
34
36
  isBot: identities.bot,
35
37
  method: identityLinks.method,
36
38
  linkedBy: identityLinks.author,
@@ -147,7 +149,7 @@ export const linkIdentities = (context, person, other, options) => {
147
149
  resolvePersonLinks(context.database, record.identities.flatMap(({ name, username }) => [name, username]));
148
150
  return record;
149
151
  };
150
- const isOwner = ({ database }, person) => Number(database.prepare("SELECT owner FROM persons WHERE id = ?").get(person)?.owner) === 1;
152
+ export const isOwner = ({ database }, person) => Number(database.prepare("SELECT owner FROM persons WHERE id = ?").get(person)?.owner) === 1;
151
153
  /** The person `mergePerson(one, other)` keeps: `other`, unless `one` is the owner's. */
152
154
  export const survivorOf = (context, one, other) => isOwner(context, one) && !isOwner(context, other) ? one : other;
153
155
  /**
@@ -171,13 +173,27 @@ export const mergePerson = (context, one, other, options) => {
171
173
  return to;
172
174
  };
173
175
  /**
174
- * NEED-2446 (safe option until the owner rules): an address that two or more other people hold is a shared one, an
175
- * `office@` or `info@`, and joins no one at import; the scan proposes such people instead.
176
+ * A company's mailbox joins no one at import: two or more other people hold it (NEED-2446), an organization holds it,
177
+ * or another person of the identity's own list has it, such as a second CRM contact (`sharedLine` in the scan).
176
178
  */
177
- const sharedAddress = ({ database }, key, person) => database
178
- .prepare("SELECT count(DISTINCT l.person_id) AS n FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
179
- "WHERE i.email = ? AND i.provider NOT IN ('email', 'org-email') AND l.person_id <> ?")
180
- .get(key, person)?.n >= 2;
179
+ const sharedAddress = ({ database }, key, found) => {
180
+ const others = database
181
+ .prepare("SELECT count(DISTINCT l.person_id) AS n FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
182
+ "WHERE i.email = ? AND i.provider NOT IN ('email', 'org-email') AND l.person_id <> ?")
183
+ .get(key, found.personPk)?.n;
184
+ if (others >= 2)
185
+ return true;
186
+ const self = database.prepare("SELECT provider, external_id FROM identities WHERE id = ?").get(found.pk);
187
+ const list = String(self?.external_id ?? "").replace(/[^/]*$/u, "");
188
+ return (database
189
+ .prepare("SELECT 1 FROM identities i WHERE i.email = ? AND (EXISTS (SELECT 1 FROM organization_identities o " +
190
+ "WHERE o.identity_id = i.id) OR (i.provider = ? AND i.id <> ? AND substr(i.external_id, 1, ?) = ? " +
191
+ "AND instr(substr(i.external_id, ? + 1), '/') = 0 AND NOT EXISTS (SELECT 1 FROM identity_links l " +
192
+ "WHERE l.identity_id = i.id AND l.person_id = ?))) LIMIT 1")
193
+ .get(key, String(self?.provider), found.pk, list.length, list, list.length, found.personPk) !== undefined);
194
+ };
195
+ const isBot = ({ database }, identity) => database.prepare("SELECT 1 FROM identities WHERE id = ? AND (bot = 1 OR provider LIKE '%-bot')").get(identity) !==
196
+ undefined;
181
197
  /** Keeps the address an identity's source gave it, so a later contact with it counts this one. */
182
198
  export const noteAddress = (context, ref, address) => {
183
199
  const key = address.trim().toLowerCase();
@@ -191,8 +207,10 @@ export const noteAddress = (context, ref, address) => {
191
207
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
192
208
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
193
209
  * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart. A role address such
194
- * as `info@` joins no one; the scan proposes its people instead. A pair the owner rejected is not joined either: it is
195
- * given back, so the caller proposes it when the evidence is new to the owner.
210
+ * as `info@` and a company's mailbox join no one, here or in the scan. A pair the owner rejected is not joined either: it is
211
+ * given back, so the caller proposes it when the evidence is new to the owner. Nothing joins the owner, or is
212
+ * proposed to them, from an address: a mailbox the owner reads may be someone else's, and only the owner joins anyone
213
+ * to themselves (SEC-177). A bot or service account joins no one.
196
214
  */
197
215
  export const joinByAddress = (context, ref, address, by) => {
198
216
  const key = address.trim().toLowerCase();
@@ -211,7 +229,9 @@ export const joinByAddress = (context, ref, address, by) => {
211
229
  const contact = required(context, { provider: "email", id: mail ? String(mail.external_id) : key });
212
230
  if (contact.personPk === found.personPk || separated(context, found.personPk, contact.personPk))
213
231
  return;
214
- if (sharedAddress(context, key, found.personPk))
232
+ if (sharedAddress(context, key, found) || isBot(context, found.pk))
233
+ return;
234
+ if (isOwner(context, found.personPk) || isOwner(context, contact.personPk))
215
235
  return;
216
236
  if (rejectedEvidence(context.database, found.personPk, contact.personPk) !== undefined)
217
237
  return { identity: found.pk, with: contact.pk, from: found.personPk, to: contact.personPk };
@@ -219,6 +239,29 @@ export const joinByAddress = (context, ref, address, by) => {
219
239
  resolvePersonLinks(context.database, recordOf(context, kept).identities.flatMap(({ name, username }) => [name, username]));
220
240
  return undefined;
221
241
  };
242
+ /**
243
+ * A person named after an identity that left them takes the name of the oldest identity they still have, or none: the
244
+ * owner merged with a partner's CRM contact kept the partner's name after the split (BUG-677).
245
+ */
246
+ export const renameAfterLeaving = (context, person, left) => {
247
+ const { database } = context;
248
+ const current = database.prepare("SELECT name FROM persons WHERE id = ?").get(person)?.name;
249
+ if (typeof current !== "string")
250
+ return;
251
+ const leaving = database
252
+ .prepare("SELECT name FROM identities WHERE id IN (SELECT value FROM json_each(?))")
253
+ .all(JSON.stringify(left))
254
+ .map(({ name }) => (typeof name === "string" ? name.trim() : ""));
255
+ if (!leaving.includes(current.trim()))
256
+ return;
257
+ const kept = database
258
+ .prepare("SELECT i.name FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
259
+ "WHERE l.person_id = ? AND trim(coalesce(i.name, '')) <> '' ORDER BY l.created_at, i.id LIMIT 1")
260
+ .get(person)?.name;
261
+ database
262
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ?")
263
+ .run(typeof kept === "string" ? kept : null, context.now(), person);
264
+ };
222
265
  /** Gives the identity a person of its own again; the ones left keep theirs. */
223
266
  export const unlinkIdentity = (context, ref, options) => {
224
267
  const found = required(context, ref);
@@ -237,6 +280,7 @@ export const unlinkIdentity = (context, ref, options) => {
237
280
  .returning({ pk: persons.id })
238
281
  .get()?.pk);
239
282
  move(context, found.pk, found.personPk, alone, { ...options, method: "unlink" });
283
+ renameAfterLeaving(context, found.personPk, [found.pk]);
240
284
  return recordOf(context, alone);
241
285
  };
242
286
  /** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */