@wirecat/cli-core 0.629.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 (43) hide show
  1. package/CHANGELOG.md +54 -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/sqlite/base-suggest.d.ts +4 -1
  19. package/dist/store/sqlite/base-suggest.js +5 -3
  20. package/dist/store/sqlite/crm.js +6 -3
  21. package/dist/store/sqlite/mail-findings.js +3 -1
  22. package/dist/store/sqlite/manifest.js +1 -0
  23. package/dist/store/sqlite/migrations.generated.js +15 -0
  24. package/dist/store/sqlite/name-traces.d.ts +8 -3
  25. package/dist/store/sqlite/name-traces.js +26 -21
  26. package/dist/store/sqlite/note-index.js +2 -1
  27. package/dist/store/sqlite/own-identities.d.ts +5 -3
  28. package/dist/store/sqlite/own-identities.js +66 -12
  29. package/dist/store/sqlite/people-list.d.ts +2 -0
  30. package/dist/store/sqlite/people-list.js +23 -10
  31. package/dist/store/sqlite/person-links.d.ts +10 -2
  32. package/dist/store/sqlite/person-links.js +54 -10
  33. package/dist/store/sqlite/person-match-scan.js +97 -17
  34. package/dist/store/sqlite/person-merges.js +3 -1
  35. package/dist/store/sqlite/person-ties.d.ts +1 -1
  36. package/dist/store/sqlite/person-ties.js +53 -21
  37. package/dist/store/sqlite/task-candidates.js +2 -2
  38. package/dist/store/sqlite/task-titles.d.ts +12 -0
  39. package/dist/store/sqlite/task-titles.js +42 -0
  40. package/dist/store/sqlite/tasks.js +2 -1
  41. package/dist/store/sqlite/work-tasks.js +2 -1
  42. package/dist/store/types.d.ts +3 -0
  43. package/package.json +2 -2
@@ -313,6 +313,13 @@ const OTHERS = [
313
313
  ["stage.owner-only", "permission_error", "only the owner confirms mappings and edits a base set, not an agent"],
314
314
  validation("stage.unmapped", "no stage of the row's pipeline maps to that base stage; map one first"),
315
315
  ["stage.not-found", "not_found", "no stored stage has that reference or name"],
316
+ validation("stage.answer-invalid", "the agent's answer to stages suggest is not the JSON stage map it asks for"),
317
+ ["stage.model-answer-invalid", "invalid_response", "the AI model's answer to stages suggest is not the stage map"],
318
+ [
319
+ "stage.model-agent",
320
+ "permission_error",
321
+ "an agent's run does not send stages to the AI model; it answers the task itself with --dry-run and --text-file",
322
+ ],
316
323
  validation("pipeline.ambiguous", "more than one pipeline has that name; name it by its pipeline: reference"),
317
324
  validation("pipeline.duplicate", "a pipeline of that name and kind is already stored"),
318
325
  validation("pipeline.field", "a pipeline needs a name and at least one stage, each named once"),
@@ -392,6 +399,7 @@ const OTHERS = [
392
399
  validation("identity.same", "the two identities are one person already"),
393
400
  validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
394
401
  validation("identity.common-name", "more than six people have the name, so it proposes no one"),
402
+ validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
395
403
  validation("identity.shared-email", "more than six people share the address, so it proposes no one"),
396
404
  validation("identity-link.dedicated-review", "an identity link is staged and decided through the people review"),
397
405
  ["transcription.no-key", "authentication_error", "no OpenAI key is set for transcription"],
@@ -4,9 +4,10 @@ import type { IdentityRef } from "./types.js";
4
4
  export declare const IDENTITY_LINK_KIND = "identity_link";
5
5
  /**
6
6
  * Why two people may be one: an agent said so, they share a phone or an address with others, a meeting guest typed
7
- * an address another person has, or they have one name and share a phone, an address, a chat or a company's domain.
7
+ * an address another person has, they have one name and share a phone, an address, a chat or a company's domain, or
8
+ * an account the owner connected carries another name than the owner's (`account`).
8
9
  */
9
- export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email", "name"];
10
+ export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email", "name", "account"];
10
11
  export type IdentityLinkSignal = (typeof IDENTITY_LINK_SIGNALS)[number];
11
12
  /** An `identity_link` proposal's payload. */
12
13
  export interface IdentityLinkPayload {
@@ -1,6 +1,7 @@
1
1
  export const IDENTITY_LINK_KIND = "identity_link";
2
2
  /**
3
3
  * Why two people may be one: an agent said so, they share a phone or an address with others, a meeting guest typed
4
- * an address another person has, or they have one name and share a phone, an address, a chat or a company's domain.
4
+ * an address another person has, they have one name and share a phone, an address, a chat or a company's domain, or
5
+ * an account the owner connected carries another name than the owner's (`account`).
5
6
  */
6
- export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email", "name"];
7
+ export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email", "name", "account"];
@@ -8,6 +8,9 @@ export declare const baseStagesOf: (database: CacheDatabase, pipeline: number) =
8
8
  /**
9
9
  * Suggests a base stage for every unconfirmed live stage of `pipelines` (every pipeline of the kind but the set's when absent): won and lost by outcome; an open one by its relative place among its pipeline's open stages, and when that
10
10
  * falls between two base stages, the one of the same name, else the nearer. Does nothing before the set exists.
11
+ * `onlyEmpty` leaves a stage that already has a suggestion: a sync must not replace one a model or an agent made.
11
12
  */
12
- export declare const suggestBaseStages: (database: CacheDatabase, kind: DealKind, pipelines?: readonly number[]) => void;
13
+ export declare const suggestBaseStages: (database: CacheDatabase, kind: DealKind, pipelines?: readonly number[], { onlyEmpty }?: {
14
+ onlyEmpty?: boolean;
15
+ }) => void;
13
16
  export {};
@@ -19,8 +19,9 @@ export const baseStagesOf = (database, pipeline) => database.prepare("SELECT * F
19
19
  /**
20
20
  * Suggests a base stage for every unconfirmed live stage of `pipelines` (every pipeline of the kind but the set's when absent): won and lost by outcome; an open one by its relative place among its pipeline's open stages, and when that
21
21
  * falls between two base stages, the one of the same name, else the nearer. Does nothing before the set exists.
22
+ * `onlyEmpty` leaves a stage that already has a suggestion: a sync must not replace one a model or an agent made.
22
23
  */
23
- export const suggestBaseStages = (database, kind, pipelines) => {
24
+ export const suggestBaseStages = (database, kind, pipelines, { onlyEmpty = false } = {}) => {
24
25
  const base = basePipelineOf(database, kind);
25
26
  if (base === undefined)
26
27
  return;
@@ -33,7 +34,8 @@ export const suggestBaseStages = (database, kind, pipelines) => {
33
34
  .prepare("SELECT id FROM pipelines WHERE kind = ? AND id <> ? AND deleted_at IS NULL")
34
35
  .all(kind, base)
35
36
  .map((row) => Number(row.id));
36
- const update = database.prepare("UPDATE pipeline_stages SET base_stage_id = ? WHERE id = ? AND base_confirmed = 0 AND base_stage_id IS NOT ?");
37
+ const update = database.prepare("UPDATE pipeline_stages SET base_stage_id = ? WHERE id = ? AND base_confirmed = 0 AND base_stage_id IS NOT ? " +
38
+ "AND (? = 0 OR base_stage_id IS NULL)");
37
39
  for (const pipeline of ids) {
38
40
  if (pipeline === base)
39
41
  continue;
@@ -56,7 +58,7 @@ export const suggestBaseStages = (database, kind, pipelines) => {
56
58
  else if (stage.outcome !== "open")
57
59
  chosen = ends[stage.outcome];
58
60
  const target = chosen === undefined ? null : Number(chosen.id);
59
- update.run(target, Number(stage.id), target);
61
+ update.run(target, Number(stage.id), target, onlyEmpty ? 1 : 0);
60
62
  }
61
63
  }
62
64
  };
@@ -32,7 +32,7 @@ export const crmCopiesOver = (context, people) => {
32
32
  const accountId = account(key);
33
33
  const at = now();
34
34
  const saved = pipelines.map((pipeline) => savePipeline(accountId, kind, pipeline, at));
35
- suggestBaseStages(database, kind, saved);
35
+ suggestBaseStages(database, kind, saved, { onlyEmpty: true });
36
36
  if (pipelines.length === 0)
37
37
  return { saved: 0, skipped: [] };
38
38
  const listed = new Set(pipelines.map(({ externalId }) => externalId));
@@ -115,12 +115,15 @@ export const crmCopiesOver = (context, people) => {
115
115
  "WHERE i.email = ?")
116
116
  .get(email)?.n);
117
117
  };
118
- /** A person a CRM contact or user made has no name when it joined the mail contact of its address first. */
118
+ /**
119
+ * A person a CRM contact or user made has no name when it joined the mail contact of its address first. The owner's
120
+ * name is never a CRM's: a contact on the owner's person by mistake must not rename them.
121
+ */
119
122
  const nameUnnamed = (key, externalId, type, name) => {
120
123
  const person = personIdOf(key, externalId, type);
121
124
  if (person !== null && name)
122
125
  database
123
- .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND name IS NULL")
126
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND name IS NULL AND owner = 0")
124
127
  .run(name, now(), person);
125
128
  return person;
126
129
  };
@@ -395,7 +395,9 @@ export const mailFindingsStoreOver = (context) => {
395
395
  }
396
396
  case "new_contact": {
397
397
  const person = Number(identityOfAddress(finding.address)?.person_id);
398
- database.prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ?").run(finding.name, now(), person);
398
+ database
399
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND owner = 0")
400
+ .run(finding.name, now(), person);
399
401
  return `person:${person}`;
400
402
  }
401
403
  }
@@ -127,6 +127,7 @@ export const MANIFEST = [
127
127
  { name: "20261109170741_version-61-people-ties", version: 61, minCompatible: 56 },
128
128
  { name: "20261110005159_version-62-person-kinds", version: 62, minCompatible: 56 },
129
129
  { name: "20261110005200_version-62-person-kinds-triggers", version: 62, minCompatible: 56 },
130
+ { name: "20261110020704_version-63-people-ties-messages-crm", version: 63, minCompatible: 56 },
130
131
  ];
131
132
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
132
133
  const migrations = [];
@@ -1291,5 +1291,20 @@ export const GENERATED = [
1291
1291
  "CREATE TRIGGER person_kind_message_ad AFTER DELETE ON messages BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.sender_identity_id);\nEND;",
1292
1292
  "CREATE TRIGGER person_kind_message_au AFTER UPDATE OF sender_identity_id, sent_at, deleted_at ON messages\nWHEN OLD.sender_identity_id IS NOT NEW.sender_identity_id OR OLD.sent_at IS NOT NEW.sent_at OR OLD.deleted_at IS NOT NEW.deleted_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.sender_identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.sender_identity_id);\nEND;"
1293
1293
  ]
1294
+ },
1295
+ {
1296
+ "name": "20261110020704_version-63-people-ties-messages-crm",
1297
+ "statements": [
1298
+ "CREATE TRIGGER person_kind_chat_senders_au AFTER UPDATE OF kind, participants_count ON chats\nWHEN OLD.kind IS NOT NEW.kind OR (OLD.participants_count <= 10) IS NOT (NEW.participants_count <= 10) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM messages s JOIN identity_links l ON l.identity_id = s.sender_identity_id WHERE s.chat_id = NEW.id);\nEND;",
1299
+ "CREATE TRIGGER person_kind_member_count_senders_ai AFTER INSERT ON member_counts\nWHEN (SELECT participants_count FROM chats WHERE id = NEW.chat_id) IS NULL BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM messages s JOIN identity_links l ON l.identity_id = s.sender_identity_id WHERE s.chat_id = NEW.chat_id);\nEND;",
1300
+ "CREATE TRIGGER person_kind_member_count_senders_ad AFTER DELETE ON member_counts\nWHEN (SELECT participants_count FROM chats WHERE id = OLD.chat_id) IS NULL BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM messages s JOIN identity_links l ON l.identity_id = s.sender_identity_id WHERE s.chat_id = OLD.chat_id);\nEND;",
1301
+ "CREATE TRIGGER person_kind_member_count_senders_au AFTER UPDATE OF listed_count, chat_id, date ON member_counts\nWHEN (OLD.listed_count IS NOT NEW.listed_count OR OLD.chat_id IS NOT NEW.chat_id OR OLD.date IS NOT NEW.date)\n AND (SELECT participants_count FROM chats WHERE id = NEW.chat_id) IS NULL BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM messages s JOIN identity_links l ON l.identity_id = s.sender_identity_id WHERE s.chat_id = NEW.chat_id);\nEND;",
1302
+ "CREATE TRIGGER person_kind_deal_link_ai AFTER INSERT ON links\nWHEN NEW.from_type IN ('deal', 'lead') AND NEW.kind = 'related-to' AND NEW.to_type = 'person' BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = NEW.from_type AND d.from_id = NEW.from_id AND d.kind = 'related-to' AND d.to_type = 'person' UNION SELECT NEW.to_id);\nEND;",
1303
+ "CREATE TRIGGER person_kind_deal_link_ad AFTER DELETE ON links\nWHEN OLD.from_type IN ('deal', 'lead') AND OLD.kind = 'related-to' AND OLD.to_type = 'person' BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = OLD.from_type AND d.from_id = OLD.from_id AND d.kind = 'related-to' AND d.to_type = 'person' UNION SELECT OLD.to_id);\nEND;",
1304
+ "CREATE TRIGGER person_kind_deal_link_au AFTER UPDATE OF from_type, from_id, to_type, to_id, kind, role, deleted_at ON links\nWHEN (OLD.from_type IN ('deal', 'lead') AND OLD.kind = 'related-to' AND OLD.to_type = 'person' OR NEW.from_type IN ('deal', 'lead') AND NEW.kind = 'related-to' AND NEW.to_type = 'person')\n AND (OLD.to_id IS NOT NEW.to_id OR OLD.role IS NOT NEW.role OR OLD.deleted_at IS NOT NEW.deleted_at\n OR OLD.from_id IS NOT NEW.from_id OR OLD.from_type IS NOT NEW.from_type OR OLD.kind IS NOT NEW.kind OR OLD.to_type IS NOT NEW.to_type) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = OLD.from_type AND d.from_id = OLD.from_id AND d.kind = 'related-to' AND d.to_type = 'person' UNION SELECT OLD.to_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = NEW.from_type AND d.from_id = NEW.from_id AND d.kind = 'related-to' AND d.to_type = 'person' UNION SELECT NEW.to_id);\nEND;",
1305
+ "CREATE TRIGGER person_kind_deal_owner_moved_au AFTER UPDATE OF person_id ON identity_links\nWHEN OLD.person_id IS NOT NEW.person_id AND EXISTS (SELECT 1 FROM links o WHERE o.to_type = 'person' AND (o.to_id IN (OLD.person_id, NEW.person_id) OR o.to_id IN (SELECT e.from_person_id FROM identity_link_events e WHERE e.identity_id = NEW.identity_id)) AND o.role = 'owner' AND o.from_type IN ('deal', 'lead')) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND d.to_type = 'person' WHERE o.to_type = 'person' AND (o.to_id IN (OLD.person_id, NEW.person_id) OR o.to_id IN (SELECT e.from_person_id FROM identity_link_events e WHERE e.identity_id = NEW.identity_id)) AND o.role = 'owner' AND o.from_type IN ('deal', 'lead'));\nEND;",
1306
+ "CREATE TRIGGER person_kind_deal_owner_person_au AFTER UPDATE OF owner ON persons\nWHEN OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND d.to_type = 'person' WHERE o.to_type = 'person' AND o.role = 'owner' AND o.from_type IN ('deal', 'lead') AND (o.to_id = NEW.id OR o.to_id IN (SELECT e.from_person_id FROM identity_link_events e JOIN identity_links l ON l.identity_id = e.identity_id WHERE l.person_id = NEW.id)));\nEND;",
1307
+ "CREATE TRIGGER person_kind_message_outgoing_au AFTER UPDATE OF outgoing ON messages\nWHEN OLD.outgoing IS NOT NEW.outgoing 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.sender_identity_id);\nEND;"
1308
+ ]
1294
1309
  }
1295
1310
  ];
@@ -1,5 +1,8 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
- /** People, owner aside, by the name they share once case, quotes and word order are set aside. */
2
+ /**
3
+ * People, owner aside, by the name they share once case, quotes, word order, script and spelling are set aside:
4
+ * `Светлана Кузнецова` and `Svetlana Kuznetsova` are one name here (BUG-678).
5
+ */
3
6
  export declare const peopleByNameKey: (database: CacheDatabase) => Map<string, {
4
7
  people: number[];
5
8
  name: string;
@@ -10,8 +13,10 @@ export interface SharedTrace {
10
13
  identity: number;
11
14
  with: number;
12
15
  kind: "chat" | "email" | "email-domain" | "phone";
16
+ /** The phone or address, for the kinds that have one. */
17
+ value?: string;
13
18
  evidence: string[];
14
19
  reason: string;
15
20
  }
16
- /** The first trace two people share, strongest first: a phone, an address, a chat, a company's domain. */
17
- export declare const sharedTrace: (database: CacheDatabase, a: number, b: number, name: string) => SharedTrace | undefined;
21
+ /** The traces two people share, strongest first: each phone, each address, a chat, a company's domain. */
22
+ export declare function sharedTraces(database: CacheDatabase, a: number, b: number, name: string): Generator<SharedTrace>;
@@ -1,9 +1,13 @@
1
1
  import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
2
- import { displayName, nameKey } from "../../domain/display-names.js";
2
+ import { displayName } from "../../domain/display-names.js";
3
+ import { variantKey } from "../../domain/name-variants.js";
3
4
  import { storedPhone } from "../../domain/phones.js";
4
5
  import { FREE_MAIL } from "../../mail/score.js";
5
6
  import { referenceOfThing } from "./things.js";
6
- /** People, owner aside, by the name they share once case, quotes and word order are set aside. */
7
+ /**
8
+ * People, owner aside, by the name they share once case, quotes, word order, script and spelling are set aside:
9
+ * `Светлана Кузнецова` and `Svetlana Kuznetsova` are one name here (BUG-678).
10
+ */
7
11
  export const peopleByNameKey = (database) => {
8
12
  const found = new Map();
9
13
  for (const row of database
@@ -11,7 +15,7 @@ export const peopleByNameKey = (database) => {
11
15
  "AND EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) ORDER BY p.id")
12
16
  .all()) {
13
17
  const name = String(row.name);
14
- const key = nameKey(name);
18
+ const key = variantKey(name);
15
19
  if (key === null)
16
20
  continue;
17
21
  const held = found.get(key) ?? { people: [], name: displayName(name) ?? name };
@@ -52,14 +56,16 @@ const tracesOf = (database, person) => {
52
56
  }
53
57
  return traces;
54
58
  };
55
- const common = (a, b) => {
59
+ function* common(a, b) {
60
+ const seen = new Set();
56
61
  for (const one of a) {
57
62
  const other = b.find(({ value }) => value === one.value);
58
- if (other !== undefined)
59
- return [one, other];
63
+ if (other === undefined || seen.has(one.value))
64
+ continue;
65
+ seen.add(one.value);
66
+ yield [one, other];
60
67
  }
61
- return undefined;
62
- };
68
+ }
63
69
  const commonChat = (database, a, b) => database
64
70
  .prepare("SELECT m1.chat_id, m1.identity_id AS one, m2.identity_id AS other FROM identity_links l1 " +
65
71
  "JOIN chat_members m1 ON m1.identity_id = l1.identity_id " +
@@ -67,31 +73,31 @@ const commonChat = (database, a, b) => database
67
73
  "JOIN identity_links l2 ON l2.identity_id = m2.identity_id " +
68
74
  "WHERE l1.person_id = ? AND l2.person_id = ? ORDER BY m1.chat_id LIMIT 1")
69
75
  .get(a, b);
70
- /** The first trace two people share, strongest first: a phone, an address, a chat, a company's domain. */
71
- export const sharedTrace = (database, a, b, name) => {
76
+ /** The traces two people share, strongest first: each phone, each address, a chat, a company's domain. */
77
+ export function* sharedTraces(database, a, b, name) {
72
78
  const [one, other] = [tracesOf(database, a), tracesOf(database, b)];
73
- const phone = common(one.phones, other.phones);
74
- if (phone)
75
- return {
79
+ for (const phone of common(one.phones, other.phones))
80
+ yield {
76
81
  identity: phone[0].identity,
77
82
  with: phone[1].identity,
78
83
  kind: "phone",
84
+ value: phone[0].value,
79
85
  evidence: [],
80
86
  reason: `same name «${name}» and the same phone`,
81
87
  };
82
- const email = common(one.emails, other.emails);
83
- if (email)
84
- return {
88
+ for (const email of common(one.emails, other.emails))
89
+ yield {
85
90
  identity: email[0].identity,
86
91
  with: email[1].identity,
87
92
  kind: "email",
93
+ value: email[0].value,
88
94
  evidence: [],
89
95
  reason: `same name «${name}» and the same address ${email[0].value}`,
90
96
  };
91
97
  const chat = commonChat(database, a, b);
92
98
  if (chat) {
93
99
  const ref = referenceOfThing(database, { type: "chat", id: Number(chat.chat_id) });
94
- return {
100
+ yield {
95
101
  identity: Number(chat.one),
96
102
  with: Number(chat.other),
97
103
  kind: "chat",
@@ -99,14 +105,13 @@ export const sharedTrace = (database, a, b, name) => {
99
105
  reason: `same name «${name}» and a chat they are both in`,
100
106
  };
101
107
  }
102
- const domain = common(one.domains, other.domains);
108
+ const domain = common(one.domains, other.domains).next().value;
103
109
  if (domain)
104
- return {
110
+ yield {
105
111
  identity: domain[0].identity,
106
112
  with: domain[1].identity,
107
113
  kind: "email-domain",
108
114
  evidence: [],
109
115
  reason: `same name «${name}» and mail at the same company, ${domain[0].value}`,
110
116
  };
111
- return undefined;
112
- };
117
+ }
@@ -11,6 +11,7 @@ import { indexRow } from "./index-state.js";
11
11
  import { noteIndexText } from "./index-text.js";
12
12
  import { speech } from "./lucene-fields.js";
13
13
  import { savedStemmers } from "./stems.js";
14
+ import { PLACEHOLDER_TITLE_SQL } from "./task-titles.js";
14
15
  import { write } from "./transaction.js";
15
16
  import { dropUnusedVectors } from "./vector-index.js";
16
17
  /** What an event `e` is searched by besides its title: the cleaned description, the place and the attendees' names. */
@@ -79,7 +80,7 @@ export const CORPORA = {
79
80
  index: "task_index",
80
81
  table: "tasks",
81
82
  // A rule names its task `<kind> — <source>`: words every rule task shares, so they say nothing about this one.
82
- read: "SELECT CASE WHEN title = type || ' — ' || coalesce(source_locator, '') THEN NULL ELSE title END AS title, " +
83
+ read: `SELECT CASE WHEN ${PLACEHOLDER_TITLE_SQL} THEN NULL ELSE title END AS title, ` +
83
84
  "coalesce(description, '') AS body, deleted_at IS NULL AS live, 'personal' AS scope FROM tasks WHERE id = ?",
84
85
  pieces: false,
85
86
  terms: (text, stemmer) => ({ words: taskWordsOf(text), stems: [...taskStemsOf(text, stemmer)].join(" ") }),
@@ -1,9 +1,11 @@
1
1
  import type { IdentityRef, PersonRecord } from "../types.js";
2
2
  import type { StoreContext } from "./open.js";
3
3
  /**
4
- * An account's own identity (same provider and id as the account) is the owner. Messengers save it like anyone
5
- * else's, as a person of its own, so the owner's name counted as a contact's. Links it, and whoever was linked
6
- * with it, to the owner, unless the owner separated that person from themselves; nothing to do once done.
4
+ * An account's own identity (same provider and id as the account) is usually the owner. Messengers save it like anyone
5
+ * 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
6
+ * account identity on it carries the owner's name, unless the owner separated that person from themselves. Under
7
+ * another name, such as a partner's mailbox or a spouse's messenger the owner reads, it only proposes: nothing joins
8
+ * anyone to the owner without the owner. A bot is never the owner. Nothing to do once done.
7
9
  */
8
10
  export declare const linkOwnIdentities: (context: StoreContext) => number;
9
11
  /** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
@@ -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. */
@@ -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. */
@@ -1,6 +1,7 @@
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";
5
6
  import { isQueryOnly } from "../driver.js";
6
7
  import { fold } from "../normalize.js";
@@ -17,10 +18,14 @@ const matching = (query) => {
17
18
  const text = query.trim();
18
19
  if (text.length < MIN_QUERY)
19
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}`)}%`;
20
23
  return {
21
24
  sql: " AND (p.id IN (SELECT l.person_id FROM identity_links l WHERE l.identity_id IN " +
22
- "(SELECT rowid FROM identities_fts WHERE identities_fts MATCH ?)) OR p.name LIKE ? ESCAPE '\\')",
23
- 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)],
24
29
  };
25
30
  };
26
31
  const TASK_COUNTS = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)) " +
@@ -63,6 +68,7 @@ const factsOf = (database, scope) => {
63
68
  const person = Number(row.person);
64
69
  const one = facts.get(person) ?? {
65
70
  username: null,
71
+ usernameSource: null,
66
72
  phone: null,
67
73
  email: null,
68
74
  emails: [],
@@ -71,7 +77,10 @@ const factsOf = (database, scope) => {
71
77
  organization: false,
72
78
  };
73
79
  const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
74
- 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
+ }
75
84
  one.phone ??= text(row.phone) ?? (row.provider === "phone" ? text(row.external_id) : null);
76
85
  one.email ??= email;
77
86
  if (email !== null)
@@ -149,6 +158,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
149
158
  tasks: tasks.get(id) ?? 0,
150
159
  contact: contact.phone ?? contact.email ?? (contact.username === null ? null : `@${contact.username.replace(/^@/, "")}`),
151
160
  ...contact,
161
+ usernameSource: own?.usernameSource ?? null,
152
162
  messagesFrom: (messages.get(id) ?? 0) + (mail.get(id)?.n ?? 0),
153
163
  ties,
154
164
  };
@@ -169,7 +179,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
169
179
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
170
180
  * every stored one is worked out again on the next list.
171
181
  */
172
- const KIND_RULES = "1";
182
+ const KIND_RULES = "2";
173
183
  const RULES_KEY = "people.kind_rules";
174
184
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
175
185
  const WHOLE_PASS = 20_000;
@@ -340,9 +350,12 @@ const listInMemory = (database, options) => {
340
350
  };
341
351
  };
342
352
  const words = (key) => (key === null ? [] : key.split(" "));
343
- /** 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
+ */
344
357
  const startsEach = (typed, name) => {
345
- const own = words(nameKey(name));
358
+ const own = words(variantKey(name));
346
359
  return typed.every((word) => own.some((one) => one.startsWith(word)));
347
360
  };
348
361
  /**
@@ -350,9 +363,9 @@ const startsEach = (typed, name) => {
350
363
  * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
351
364
  */
352
365
  export const similarPeople = (database, typed, limit) => {
353
- const key = nameKey(typed);
366
+ const key = variantKey(typed);
354
367
  const wanted = words(key);
355
- 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), "");
356
369
  if (longest === "")
357
370
  return [];
358
371
  const named = new Map();
@@ -370,7 +383,7 @@ export const similarPeople = (database, typed, limit) => {
370
383
  ? database
371
384
  .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities_fts f JOIN identities i ON i.id = f.rowid " +
372
385
  "JOIN identity_links l ON l.identity_id = i.id WHERE identities_fts MATCH ?")
373
- .all(ftsPhrase(longest))
386
+ .all(spellings(longest).map(ftsPhrase).join(" OR "))
374
387
  : database
375
388
  .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities i " +
376
389
  "JOIN identity_links l ON l.identity_id = i.id WHERE i.name_folded LIKE ? ESCAPE '\\'")
@@ -384,7 +397,7 @@ export const similarPeople = (database, typed, limit) => {
384
397
  .map(([person, names]) => ({
385
398
  person,
386
399
  name: names[0] ?? "",
387
- same: names.some((name) => nameKey(name) === key),
400
+ same: names.some((name) => variantKey(name) === key),
388
401
  }));
389
402
  if (found.length === 0)
390
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. */