@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
@@ -10,6 +10,8 @@ export declare const person: v.StrictObjectSchema<{
10
10
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
11
11
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
12
12
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
13
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
14
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
13
15
  readonly person: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>, undefined>;
14
16
  }, undefined>, undefined>, undefined>;
15
17
  }, undefined>;
@@ -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"];
@@ -1,4 +1,5 @@
1
1
  import type { Contact, Id, Page, PersonAlias, Provider } from "../domain/models.js";
2
+ import type { PersonKind } from "../domain/person-kinds.js";
2
3
  import type { PeopleLookup } from "../resolve.js";
3
4
  import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
4
5
  import type { ContactFilter } from "./sqlite/identities.js";
@@ -110,6 +111,8 @@ export interface PeopleStore extends AccountPeople {
110
111
  * name, no tie) and `unsorted` (nothing to show as a name) hold the rest.
111
112
  */
112
113
  list(options: PeopleListOptions): Promise<PeopleList>;
114
+ /** How many people of each kind match a name or username, or the whole store: `list`'s `counts` without a page. */
115
+ counts(query?: string): Promise<Record<PersonKind, number>>;
113
116
  /** People whose names start like the typed one, the same name first: for a form that adds a person. */
114
117
  similar(name: string, options?: {
115
118
  limit?: number;
@@ -4,7 +4,7 @@ import { ownerPerson } from "./sqlite/actors.js";
4
4
  import * as identities from "./sqlite/identities.js";
5
5
  import * as identityProposals from "./sqlite/identity-proposals.js";
6
6
  import { linkToOwner } from "./sqlite/own-identities.js";
7
- import { listPeople, similarPeople, } from "./sqlite/people-list.js";
7
+ import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
8
8
  import * as personLinks from "./sqlite/person-links.js";
9
9
  import { RULE, scanMatches } from "./sqlite/person-match-scan.js";
10
10
  import * as personMerges from "./sqlite/person-merges.js";
@@ -125,6 +125,7 @@ export const peopleStoreOver = (context, keyed) => {
125
125
  linkProposals: async (filter) => identityProposals.identityLinkRows(context, filter),
126
126
  linkToOwner: async (identity) => linkToOwner(context, identity),
127
127
  list: async (options) => listPeople(database, options),
128
+ counts: async (query) => countPeople(database, query),
128
129
  similar: async (name, { limit = 8 } = {}) => similarPeople(database, name, limit),
129
130
  ties: async (people) => {
130
131
  const reasons = shownReasons(database);
@@ -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
  };
@@ -41,6 +41,8 @@ export declare const upsertChat: (context: StoreContext, accountKey: number, cha
41
41
  export declare const raiseLastMessageAt: ({ orm }: StoreContext, chatKey: number, at: number) => void;
42
42
  /** Replaces who is in the chat, whole. */
43
43
  export declare const writeMembers: (context: StoreContext, key: AccountKey, accountKey: number, chatId: Id, memberIds: Id[]) => void;
44
+ /** Leaves the rows of members still there alone: a rewritten row clears their stored kind (store version 62). */
45
+ export declare const replaceMembers: ({ database }: StoreContext, chatKey: number, members: readonly number[], at: number) => void;
44
46
  export declare const members: ({ orm }: StoreContext, chatKey: number) => Member[];
45
47
  /** Takes the left mark off the chats `present` names; any other state is kept. Answers how many. */
46
48
  export declare const rejoin: ({ orm }: StoreContext, accountKey: number, present: Id[]) => number;
@@ -223,17 +223,17 @@ const metadataObject = (stored) => {
223
223
  /** Replaces who is in the chat, whole. */
224
224
  export const writeMembers = (context, key, accountKey, chatId, memberIds) => {
225
225
  const chatKey = chatPkFor(context, accountKey, chatId);
226
- context.orm.delete(chatMembers).where(eq(chatMembers.chatId, chatKey)).run();
227
- for (const id of new Set(memberIds)) {
228
- context.orm
229
- .insert(chatMembers)
230
- .values({
231
- chatId: chatKey,
232
- identityId: identityPk(context, accountKey, key.provider, id, null),
233
- createdAt: context.now(),
234
- })
235
- .run();
236
- }
226
+ const members = [...new Set(memberIds)].map((id) => identityPk(context, accountKey, key.provider, id, null));
227
+ replaceMembers(context, chatKey, members, context.now());
228
+ };
229
+ /** Leaves the rows of members still there alone: a rewritten row clears their stored kind (store version 62). */
230
+ export const replaceMembers = ({ database }, chatKey, members, at) => {
231
+ database
232
+ .prepare("DELETE FROM chat_members WHERE chat_id = ? AND identity_id NOT IN (SELECT value FROM json_each(?))")
233
+ .run(chatKey, JSON.stringify(members));
234
+ const add = database.prepare("INSERT OR IGNORE INTO chat_members (chat_id, identity_id, created_at) VALUES (?, ?, ?)");
235
+ for (const member of new Set(members))
236
+ add.run(chatKey, member, at);
237
237
  };
238
238
  export const members = ({ orm }, chatKey) => orm
239
239
  .select({ id: identities.externalId, name: identities.name, username: identities.username })
@@ -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
  };
@@ -11,8 +11,11 @@ export interface LinkRow {
11
11
  export declare const pairOf: (a: number | string, b: number | string) => string;
12
12
  /** The people a proposal's identities are on now; merges since may have moved either side. */
13
13
  export declare const currentPairOf: (database: CacheDatabase, payload: IdentityLinkPayload) => [number, number] | undefined;
14
- /** The proposals that still say something: waiting for the owner, or turned down by them. */
15
- export declare const linkRows: (database: CacheDatabase, statuses?: readonly string[]) => LinkRow[];
14
+ /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
15
+ export declare const linkRows: (database: CacheDatabase, statuses?: readonly string[], page?: {
16
+ limit: number;
17
+ offset: number;
18
+ }) => LinkRow[];
16
19
  /**
17
20
  * What a proposal rests on: its signal and the two identities it names, in either order. The owner's rejection
18
21
  * holds against this evidence only (NEED-2444); a new signal or identity for the same people proposes them again.
@@ -22,11 +22,11 @@ export const currentPairOf = (database, payload) => {
22
22
  : personOf(database, pkOf(database, payload.with));
23
23
  return from === undefined || to === undefined ? undefined : [from, to];
24
24
  };
25
- /** The proposals that still say something: waiting for the owner, or turned down by them. */
26
- export const linkRows = (database, statuses = ["proposed", "rejected"]) => database
25
+ /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
26
+ export const linkRows = (database, statuses = ["proposed", "rejected"], page) => database
27
27
  .prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? " +
28
- "AND status IN (SELECT value FROM json_each(?)) ORDER BY id")
29
- .all(IDENTITY_LINK_KIND, JSON.stringify(statuses))
28
+ `AND status IN (SELECT value FROM json_each(?)) ORDER BY id${page === undefined ? "" : " DESC LIMIT ? OFFSET ?"}`)
29
+ .all(IDENTITY_LINK_KIND, JSON.stringify(statuses), ...(page === undefined ? [] : [page.limit, page.offset]))
30
30
  .map((row) => {
31
31
  const payload = JSON.parse(String(row.payload));
32
32
  return { id: String(row.id), status: String(row.status), payload, pair: currentPairOf(database, payload) };
@@ -206,11 +206,15 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
206
206
  throw new CliError("validation_error", "a list of link proposals takes 1–500 items");
207
207
  const asked = person === undefined ? undefined : currentPerson(context.database, Number(person));
208
208
  const operations = proposalOperationsOver(context);
209
- const rows = linkRows(context.database, ["proposed", "rejected", "approved", "executed", "failed"])
210
- .filter((row) => status === "all" || SHOWN[row.status] === status)
211
- .filter((row) => asked === undefined || (row.pair?.includes(asked) ?? false))
212
- .reverse();
213
- const items = rows.slice(offset, offset + limit).map((row) => {
209
+ const statuses = Object.keys(SHOWN).filter((one) => status === "all" || SHOWN[one] === status);
210
+ // Whose a proposal is now depends on merges since, so only a list for one person reads every proposal.
211
+ const rows = asked === undefined
212
+ ? linkRows(context.database, statuses, { limit: limit + 1, offset })
213
+ : linkRows(context.database, statuses)
214
+ .filter((row) => row.pair?.includes(asked) ?? false)
215
+ .reverse()
216
+ .slice(offset, offset + limit + 1);
217
+ const items = rows.slice(0, limit).map((row) => {
214
218
  const action = operations.get(row.id);
215
219
  const payload = row.payload;
216
220
  const [from, to] = row.pair ?? payload.persons.map(Number);
@@ -230,5 +234,5 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
230
234
  createdAt: action.createdAt,
231
235
  };
232
236
  });
233
- return { items, hasMore: rows.length > offset + limit };
237
+ return { items, hasMore: rows.length > limit };
234
238
  };
@@ -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
  }
@@ -125,6 +125,9 @@ export const MANIFEST = [
125
125
  { name: "20261108165309_version-59-templates", version: 59, minCompatible: 56 },
126
126
  { name: "20261108190101_version-60-base-stages", version: 60, minCompatible: 56 },
127
127
  { name: "20261109170741_version-61-people-ties", version: 61, minCompatible: 56 },
128
+ { name: "20261110005159_version-62-person-kinds", version: 62, minCompatible: 56 },
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 },
128
131
  ];
129
132
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
130
133
  const migrations = [];
@@ -1231,5 +1231,80 @@ export const GENERATED = [
1231
1231
  "ALTER TABLE `account_identities` ADD `address_book` integer;",
1232
1232
  "CREATE INDEX `account_identities_in_address_book` ON `account_identities` (`identity_id`) WHERE address_book = 1;"
1233
1233
  ]
1234
+ },
1235
+ {
1236
+ "name": "20261110005159_version-62-person-kinds",
1237
+ "statements": [
1238
+ "ALTER TABLE `persons` ADD `kind` text;",
1239
+ "ALTER TABLE `persons` ADD `name_order` text;",
1240
+ "ALTER TABLE `persons` ADD `messages_from` integer;",
1241
+ "ALTER TABLE `persons` ADD `task_count` integer;",
1242
+ "ALTER TABLE `persons` ADD `last_contact` integer;",
1243
+ "CREATE INDEX `persons_by_kind` ON `persons` (`kind`);",
1244
+ "CREATE INDEX `persons_kind_to_work_out` ON `persons` (`id`) WHERE kind IS NULL;"
1245
+ ]
1246
+ },
1247
+ {
1248
+ "name": "20261110005200_version-62-person-kinds-triggers",
1249
+ "statements": [
1250
+ "CREATE TRIGGER person_kind_person_au AFTER UPDATE OF name, owner ON persons\nWHEN OLD.name IS NOT NEW.name OR OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id = NEW.id;\nEND;",
1251
+ "CREATE TRIGGER person_kind_link_ai AFTER INSERT ON identity_links BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (NEW.person_id);\nEND;",
1252
+ "CREATE TRIGGER person_kind_link_ad AFTER DELETE ON identity_links BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (OLD.person_id);\nEND;",
1253
+ "CREATE TRIGGER person_kind_link_au AFTER UPDATE OF person_id, identity_id ON identity_links\nWHEN OLD.person_id IS NOT NEW.person_id OR OLD.identity_id IS NOT NEW.identity_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (OLD.person_id, NEW.person_id);\nEND;",
1254
+ "CREATE TRIGGER person_kind_identity_au AFTER UPDATE OF provider, external_id, username, phone, email, bot ON identities\nWHEN OLD.provider IS NOT NEW.provider OR OLD.external_id IS NOT NEW.external_id OR OLD.username IS NOT NEW.username OR OLD.phone IS NOT NEW.phone OR OLD.email IS NOT NEW.email OR OLD.bot IS NOT NEW.bot 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.id);\nEND;",
1255
+ "CREATE TRIGGER person_kind_member_ai AFTER INSERT ON chat_members BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1256
+ "CREATE TRIGGER person_kind_member_ad AFTER DELETE ON chat_members 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.identity_id);\nEND;",
1257
+ "CREATE TRIGGER person_kind_member_au AFTER UPDATE OF chat_id, identity_id ON chat_members\nWHEN OLD.chat_id IS NOT NEW.chat_id OR OLD.identity_id IS NOT NEW.identity_id 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.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.identity_id);\nEND;",
1258
+ "CREATE TRIGGER person_kind_chat_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 chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = NEW.id);\nEND;",
1259
+ "CREATE TRIGGER person_kind_member_count_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 chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = NEW.chat_id);\nEND;",
1260
+ "CREATE TRIGGER person_kind_member_count_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 chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = OLD.chat_id);\nEND;",
1261
+ "CREATE TRIGGER person_kind_member_count_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 chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = NEW.chat_id);\nEND;",
1262
+ "CREATE TRIGGER person_kind_email_ai AFTER INSERT ON emails 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.from_identity_id);\nEND;",
1263
+ "CREATE TRIGGER person_kind_email_ad AFTER DELETE ON emails 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.from_identity_id);\nEND;",
1264
+ "CREATE TRIGGER person_kind_email_au AFTER UPDATE OF from_identity_id, outgoing, deleted_at, draft, sent_at, received_at ON emails\nWHEN OLD.from_identity_id IS NOT NEW.from_identity_id OR OLD.outgoing IS NOT NEW.outgoing OR OLD.deleted_at IS NOT NEW.deleted_at OR OLD.draft IS NOT NEW.draft OR OLD.sent_at IS NOT NEW.sent_at OR OLD.received_at IS NOT NEW.received_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.from_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.from_identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM email_recipients r JOIN identity_links l ON l.identity_id = r.identity_id WHERE r.email_id = NEW.id);\nEND;",
1265
+ "CREATE TRIGGER person_kind_recipient_ai AFTER INSERT ON email_recipients\nWHEN (SELECT outgoing FROM emails WHERE id = NEW.email_id) = 1 BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1266
+ "CREATE TRIGGER person_kind_recipient_ad AFTER DELETE ON email_recipients\nWHEN (SELECT outgoing FROM emails WHERE id = OLD.email_id) = 1 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.identity_id);\nEND;",
1267
+ "CREATE TRIGGER person_kind_recipient_au AFTER UPDATE OF email_id, identity_id ON email_recipients\nWHEN (OLD.email_id IS NOT NEW.email_id OR OLD.identity_id IS NOT NEW.identity_id) AND 1 IN (SELECT outgoing FROM emails WHERE id IN (OLD.email_id, NEW.email_id)) 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.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.identity_id);\nEND;",
1268
+ "CREATE TRIGGER person_kind_email_mailbox_ai AFTER INSERT ON email_mailboxes BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id WHERE e.id = NEW.email_id);\nEND;",
1269
+ "CREATE TRIGGER person_kind_email_mailbox_ad AFTER DELETE ON email_mailboxes BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id WHERE e.id = OLD.email_id);\nEND;",
1270
+ "CREATE TRIGGER person_kind_mailbox_au AFTER UPDATE OF kind ON mailboxes\nWHEN OLD.kind IS NOT NEW.kind BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM email_mailboxes m JOIN emails e ON e.id = m.email_id JOIN identity_links l ON l.identity_id = e.from_identity_id WHERE m.mailbox_id = NEW.id);\nEND;",
1271
+ "CREATE TRIGGER person_kind_meeting_participant_ai AFTER INSERT ON meeting_participants BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1272
+ "CREATE TRIGGER person_kind_meeting_participant_ad AFTER DELETE ON meeting_participants 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.identity_id);\nEND;",
1273
+ "CREATE TRIGGER person_kind_meeting_participant_au AFTER UPDATE OF identity_id ON meeting_participants\nWHEN OLD.identity_id IS NOT NEW.identity_id 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.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.identity_id);\nEND;",
1274
+ "CREATE TRIGGER person_kind_calendar_participant_ai AFTER INSERT ON calendar_entry_participants BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1275
+ "CREATE TRIGGER person_kind_calendar_participant_ad AFTER DELETE ON calendar_entry_participants 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.identity_id);\nEND;",
1276
+ "CREATE TRIGGER person_kind_calendar_participant_au AFTER UPDATE OF identity_id, resource ON calendar_entry_participants\nWHEN OLD.identity_id IS NOT NEW.identity_id OR OLD.resource IS NOT NEW.resource 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.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.identity_id);\nEND;",
1277
+ "CREATE TRIGGER person_kind_account_identity_ai AFTER INSERT ON account_identities BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1278
+ "CREATE TRIGGER person_kind_account_identity_ad AFTER DELETE ON account_identities 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.identity_id);\nEND;",
1279
+ "CREATE TRIGGER person_kind_account_identity_au AFTER UPDATE OF identity_id, address_book, mail_signals, last_messaged_at ON account_identities\nWHEN OLD.identity_id IS NOT NEW.identity_id OR OLD.address_book IS NOT NEW.address_book OR OLD.mail_signals IS NOT NEW.mail_signals OR OLD.last_messaged_at IS NOT NEW.last_messaged_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.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.identity_id);\nEND;",
1280
+ "CREATE TRIGGER person_kind_organization_identity_ai AFTER INSERT ON organization_identities BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1281
+ "CREATE TRIGGER person_kind_organization_identity_ad AFTER DELETE ON organization_identities 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.identity_id);\nEND;",
1282
+ "CREATE TRIGGER person_kind_organization_identity_au AFTER UPDATE OF identity_id ON organization_identities\nWHEN OLD.identity_id IS NOT NEW.identity_id 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.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.identity_id);\nEND;",
1283
+ "CREATE TRIGGER person_kind_record_ai AFTER INSERT ON records BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.entity_id WHERE NEW.entity_type = 'person');\nEND;",
1284
+ "CREATE TRIGGER person_kind_record_ad AFTER DELETE ON records BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.entity_id WHERE OLD.entity_type = 'person');\nEND;",
1285
+ "CREATE TRIGGER person_kind_record_au AFTER UPDATE OF entity_type, entity_id, deleted_at ON records\nWHEN OLD.entity_type IS NOT NEW.entity_type OR OLD.entity_id IS NOT NEW.entity_id 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 OLD.entity_id WHERE OLD.entity_type = 'person');\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.entity_id WHERE NEW.entity_type = 'person');\nEND;",
1286
+ "CREATE TRIGGER person_kind_assignment_ai AFTER INSERT ON task_assignments BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.assignee_id WHERE NEW.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE NEW.assignee_type = 'person' AND from_person_id = NEW.assignee_id);\nEND;",
1287
+ "CREATE TRIGGER person_kind_assignment_ad AFTER DELETE ON task_assignments BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.assignee_id WHERE OLD.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE OLD.assignee_type = 'person' AND from_person_id = OLD.assignee_id);\nEND;",
1288
+ "CREATE TRIGGER person_kind_assignment_au AFTER UPDATE OF task_id, assignee_type, assignee_id ON task_assignments\nWHEN OLD.task_id IS NOT NEW.task_id OR OLD.assignee_type IS NOT NEW.assignee_type OR OLD.assignee_id IS NOT NEW.assignee_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.assignee_id WHERE OLD.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE OLD.assignee_type = 'person' AND from_person_id = OLD.assignee_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.assignee_id WHERE NEW.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE NEW.assignee_type = 'person' AND from_person_id = NEW.assignee_id);\nEND;",
1289
+ "CREATE TRIGGER person_kind_task_au AFTER UPDATE OF deleted_at ON tasks\nWHEN OLD.deleted_at IS NOT NEW.deleted_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT a.assignee_id FROM task_assignments a WHERE a.task_id = NEW.id AND a.assignee_type = 'person' UNION SELECT e.to_person_id FROM task_assignments a JOIN identity_link_events e ON e.from_person_id = a.assignee_id WHERE a.task_id = NEW.id AND a.assignee_type = 'person');\nEND;",
1290
+ "CREATE TRIGGER person_kind_message_ai AFTER INSERT 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 = NEW.sender_identity_id);\nEND;",
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
+ "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
+ ]
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
+ ]
1234
1309
  }
1235
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. */