@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
@@ -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. */
@@ -2,8 +2,8 @@ import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/ad
2
2
  import { BARE_INTERNATIONAL_PROVIDERS, storedPhone } from "../../domain/phones.js";
3
3
  import { linkIndex, settleLinks } from "./identity-link-rows.js";
4
4
  import { openIdentityLink } from "./identity-proposals.js";
5
- import { peopleByNameKey, sharedTrace } from "./name-traces.js";
6
- import { mergePerson } from "./person-links.js";
5
+ import { peopleByNameKey, sharedTraces } from "./name-traces.js";
6
+ import { isOwner, mergePerson } from "./person-links.js";
7
7
  import { personsByIdentifiers } from "./person-matcher.js";
8
8
  import { resolvePersonLinks } from "./person-resolution.js";
9
9
  import { separated } from "./person-separation.js";
@@ -20,11 +20,33 @@ const CURSOR = "people.scan";
20
20
  * keeps its user's own number, holds it; a CRM's or a card's number is someone's word and waits as a proposal.
21
21
  */
22
22
  const phonePairJoins = (holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider));
23
+ /** NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. */
24
+ const addressGroupJoins = (people) => people <= 2;
25
+ /** A bot or a service account shares its number or address with whoever runs it; it is nobody's person. */
26
+ const NOT_A_BOT = "i.bot IS NOT 1 AND i.provider NOT LIKE '%-bot'";
27
+ const COMPANY = "EXISTS (SELECT 1 FROM organization_identities o WHERE o.identity_id = i.id) AS company";
23
28
  /**
24
- * NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. So is
25
- * a role address such as `info@` or `hello@`, even when two people have it.
29
+ * SEC-177: a company's line or mailbox is everyone's who works there, so it never says two people are one. It is one
30
+ * when an organization holds it, or when two people of one list have it, such as two CRM contacts with one number. A
31
+ * CRM's contact and its user may be one person, so they are two lists. A messenger keeps one account per number, so
32
+ * two of its accounts on one number are a number that changed hands, not a company's line.
26
33
  */
27
- const addressGroupJoins = (address, people) => people <= 2 && !isRoleAddress(address);
34
+ const sharedLine = (context, holders) => {
35
+ if (holders.some(({ company }) => company))
36
+ return true;
37
+ const seen = new Map();
38
+ for (const { identity, provider, list } of holders) {
39
+ if (provider === "email" || provider === "phone" || BARE_INTERNATIONAL_PROVIDERS.includes(provider))
40
+ continue;
41
+ const person = personOf(context, identity);
42
+ const before = seen.get(list);
43
+ if (before !== undefined && person !== undefined && before !== person)
44
+ return true;
45
+ if (person !== undefined)
46
+ seen.set(list, person);
47
+ }
48
+ return false;
49
+ };
28
50
  const maxOf = (database, sql) => Number(database.prepare(sql).get()?.n ?? 0);
29
51
  const cursorNow = (database) => ({
30
52
  identity: maxOf(database, "SELECT max(id) AS n FROM identities"),
@@ -45,6 +67,15 @@ const changedSince = (database, since) => new Set(database
45
67
  "UNION SELECT identity_id FROM meeting_participants WHERE id > ?")
46
68
  .all(since.identity, since.at, since.event, since.revision, since.participant)
47
69
  .map(({ id }) => Number(id)));
70
+ const holderOf = (row) => {
71
+ const provider = String(row.provider);
72
+ return {
73
+ identity: Number(row.id),
74
+ provider,
75
+ list: `${provider}:${String(row.external_id).replace(/[^/]*$/u, "")}`,
76
+ company: row.company === 1,
77
+ };
78
+ };
48
79
  const add = (found, key, holder) => {
49
80
  if (key === undefined)
50
81
  return;
@@ -56,12 +87,13 @@ const add = (found, key, holder) => {
56
87
  const phoneHolders = (database) => {
57
88
  const found = new Map();
58
89
  for (const row of database
59
- .prepare("SELECT i.id, i.provider, i.external_id, i.phone FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
60
- "WHERE i.provider = 'phone' OR i.phone IS NOT NULL ORDER BY i.id")
90
+ .prepare(`SELECT i.id, i.provider, i.external_id, i.phone, ${COMPANY} FROM identities i ` +
91
+ `JOIN identity_links l ON l.identity_id = i.id WHERE (i.provider = 'phone' OR i.phone IS NOT NULL) AND ${NOT_A_BOT} ` +
92
+ "ORDER BY i.id")
61
93
  .all()) {
62
94
  const provider = String(row.provider);
63
95
  const raw = String(provider === "phone" ? row.external_id : row.phone);
64
- add(found, storedPhone(raw, provider), { identity: Number(row.id), provider });
96
+ add(found, storedPhone(raw, provider), holderOf(row));
65
97
  }
66
98
  return found;
67
99
  };
@@ -73,10 +105,11 @@ const addressOf = (value) => {
73
105
  const emailHolders = (database) => {
74
106
  const found = new Map();
75
107
  for (const row of database
76
- .prepare("SELECT i.id, i.provider, i.external_id, i.email FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
77
- "WHERE i.provider <> 'org-email' AND (i.provider = 'email' OR i.email IS NOT NULL) ORDER BY i.id")
108
+ .prepare(`SELECT i.id, i.provider, i.external_id, i.email, ${COMPANY} FROM identities i ` +
109
+ "JOIN identity_links l ON l.identity_id = i.id " +
110
+ `WHERE i.provider <> 'org-email' AND (i.provider = 'email' OR i.email IS NOT NULL) AND ${NOT_A_BOT} ORDER BY i.id`)
78
111
  .all()) {
79
- const holder = { identity: Number(row.id), provider: String(row.provider) };
112
+ const holder = holderOf(row);
80
113
  add(found, addressOf(row.email), holder);
81
114
  if (row.provider === "email")
82
115
  add(found, addressOf(row.external_id), holder);
@@ -113,6 +146,8 @@ const join = (pass, sides, signal) => {
113
146
  result.skipped.push({ persons: [String(from), String(into)], signal: method, reason: "identity.separated" });
114
147
  return into;
115
148
  }
149
+ if (touchesOwner(pass, from, into, method))
150
+ return into;
116
151
  if (index.rejected(from, into) !== undefined) {
117
152
  propose(pass, { identity: sides.identity, with: sides.with, from, to: into, joins: "person", signal });
118
153
  return into;
@@ -123,7 +158,20 @@ const join = (pass, sides, signal) => {
123
158
  result.merged.push({ into: String(kept), from: String(kept === into ? from : into), signal: method });
124
159
  return kept;
125
160
  };
126
- const propose = ({ context, index, result }, opening) => {
161
+ /**
162
+ * SEC-177: the scan never joins the owner or proposes anyone to them; a mailbox or number the owner reads may be
163
+ * someone else's, and only the owner joins anyone to themselves.
164
+ */
165
+ const touchesOwner = ({ context, result }, from, to, signal) => {
166
+ if (!isOwner(context, from) && !isOwner(context, to))
167
+ return false;
168
+ result.skipped.push({ persons: [String(from), String(to)], signal, reason: "identity.owner" });
169
+ return true;
170
+ };
171
+ const propose = (pass, opening) => {
172
+ const { context, index, result } = pass;
173
+ if (touchesOwner(pass, opening.from, opening.to, opening.signal))
174
+ return;
127
175
  const opened = openIdentityLink(context, { ...opening, by: RULE }, index);
128
176
  const persons = [String(opening.from), String(opening.to)];
129
177
  if (opened.outcome === "skipped") {
@@ -153,11 +201,17 @@ const tooMany = (pass, people, reason, signal) => {
153
201
  pass.result.skipped.push({ persons: [...people.keys()].map(String), signal, reason });
154
202
  return true;
155
203
  };
156
- /** A number two people have joins them (NEED-2445); one that more share, or that once proposed, proposes. */
204
+ const skipShared = (pass, people, signal) => pass.result.skipped.push({ persons: [...people.keys()].map(String), signal, reason: `identity.shared-${signal}` });
205
+ /**
206
+ * A number two people have joins them (NEED-2445); one that more share, or that once proposed, proposes. A company's
207
+ * line does neither.
208
+ */
157
209
  const samePhone = (pass, holders) => {
158
210
  const people = peopleOf(pass.context, holders);
159
211
  if (people.size < 2 || tooMany(pass, people, "identity.shared-phone", "phone"))
160
212
  return;
213
+ if (sharedLine(pass.context, holders))
214
+ return skipShared(pass, people, "phone");
161
215
  const [into, from] = [...people.keys()].sort((a, b) => a - b);
162
216
  if (people.size === 2 && phonePairJoins(holders) && !pass.index.known(from, into))
163
217
  join(pass, { from, into, identity: people.get(from), with: people.get(into) }, "phone");
@@ -165,8 +219,8 @@ const samePhone = (pass, holders) => {
165
219
  proposeEachPair(pass, people, "phone");
166
220
  };
167
221
  /**
168
- * One address is one person in any scope (NEED-2382), unless more than two people have it or it is a role address
169
- * (NEED-2446). A no-reply address is no one's.
222
+ * One address is one person in any scope (NEED-2382), unless more than two people have it (NEED-2446). A no-reply
223
+ * address is no one's; a role address such as `info@` and a company's mailbox say nothing about who is who (SEC-177).
170
224
  */
171
225
  const sameEmail = (pass, address, holders) => {
172
226
  if (isNoReplyAddress(address))
@@ -174,7 +228,9 @@ const sameEmail = (pass, address, holders) => {
174
228
  const people = peopleOf(pass.context, holders);
175
229
  if (people.size < 2 || tooMany(pass, people, "identity.shared-email", "email"))
176
230
  return;
177
- if (!addressGroupJoins(address, people.size))
231
+ if (isRoleAddress(address) || sharedLine(pass.context, holders))
232
+ return skipShared(pass, people, "email");
233
+ if (!addressGroupJoins(people.size))
178
234
  return proposeEachPair(pass, people, "email");
179
235
  const contact = holders.find(({ provider }) => provider === "email");
180
236
  const held = contact === undefined ? undefined : personOf(pass.context, contact.identity);
@@ -186,6 +242,25 @@ const sameEmail = (pass, address, holders) => {
186
242
  into = join(pass, { from, into, identity: people.get(from), with: intoIdentity }, "email");
187
243
  };
188
244
  const peopleOfIdentities = (context, identities) => new Set([...identities].flatMap((identity) => personOf(context, identity) ?? []));
245
+ const providersOf = ({ database }, person) => new Set(database
246
+ .prepare("SELECT DISTINCT i.provider FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ?")
247
+ .all(person)
248
+ .map(({ provider }) => String(provider)));
249
+ /**
250
+ * SEC-177: a phone or address proves only when it is these two people's alone. A chat or a company's domain is weaker,
251
+ * and is enough only between people of one source, whose names come from one place.
252
+ */
253
+ const strongEnough = (context, from, to, trace) => {
254
+ if (trace.value !== undefined) {
255
+ const held = personsByIdentifiers(context.database, {
256
+ emails: trace.kind === "email" ? [trace.value] : [],
257
+ phones: trace.kind === "phone" ? [trace.value] : [],
258
+ });
259
+ return held.every((person) => person === from || person === to);
260
+ }
261
+ const theirs = providersOf(context, to);
262
+ return [...providersOf(context, from)].some((provider) => theirs.has(provider));
263
+ };
189
264
  /**
190
265
  * One name and a shared trace (a phone, an address, a chat, a company's domain) only proposes: a name is common, so
191
266
  * the owner decides every merge. More than `MOST_SHARING` people on one name is too common to propose from.
@@ -198,7 +273,12 @@ const sameName = (pass, people, name) => {
198
273
  const sorted = [...people].sort((a, b) => a - b);
199
274
  for (const [at, from] of sorted.entries())
200
275
  for (const to of sorted.slice(at + 1)) {
201
- const trace = sharedTrace(pass.context.database, from, to, name);
276
+ let trace;
277
+ for (const one of sharedTraces(pass.context.database, from, to, name))
278
+ if (strongEnough(pass.context, from, to, one)) {
279
+ trace = one;
280
+ break;
281
+ }
202
282
  if (trace === undefined)
203
283
  continue;
204
284
  propose(pass, {
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { currentPerson, mergeSql, SEPARATIONS } from "./merged-persons.js";
3
- import { move, recordOf, required } from "./person-links.js";
3
+ import { move, recordOf, renameAfterLeaving, required } from "./person-links.js";
4
4
  import { persons } from "./schema.js";
5
5
  export const mergeId = (to, from) => `merge:${to}-${from}`;
6
6
  /** The two uids a `merge:<to>-<from>` id names. */
@@ -102,6 +102,7 @@ export const undoMerge = (context, toUid, fromUid, by) => {
102
102
  throw new CliError("not_found", `nothing of person:${fromUid} is merged into person:${toUid}`);
103
103
  for (const { pk } of here)
104
104
  move(context, pk, to, from, { method: "undo-merge", by });
105
+ renameAfterLeaving(context, to, here.map(({ pk }) => pk));
105
106
  return recordOf(context, from);
106
107
  };
107
108
  /**
@@ -132,5 +133,6 @@ export const split = (context, uid, refs, by) => {
132
133
  .get()?.pk);
133
134
  for (const { pk } of found)
134
135
  move(context, pk, person, alone, { method: "split", by });
136
+ renameAfterLeaving(context, person, found.map(({ pk }) => pk));
135
137
  return recordOf(context, alone);
136
138
  };
@@ -12,6 +12,6 @@ export declare const ALWAYS_SHOWN: readonly ["owner", "added", "task"];
12
12
  export type ShownBecause = (typeof ALWAYS_SHOWN)[number] | PersonTie;
13
13
  /**
14
14
  * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default.
15
- * `people` narrows it to those. One pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
15
+ * `people` narrows it to those. On 40,000 identities and 400,000 messages about 130 ms for everyone, 1 ms for a page.
16
16
  */
17
17
  export declare const shownReasons: (database: CacheDatabase, people?: readonly number[]) => Map<number, ShownBecause[]>;
@@ -1,5 +1,5 @@
1
1
  import { kindsOfEntry, providers } from "../../domain/providers.js";
2
- import { mergedAwaySql } from "./merged-persons.js";
2
+ import { mergedAwaySql, mergeSql } from "./merged-persons.js";
3
3
  import { mergedAssignees } from "./task-board.js";
4
4
  /**
5
5
  * A group this small is people the owner knows; in a bigger one an author alone is background. Store version 62's
@@ -17,22 +17,52 @@ const quoted = (value) => `'${value.replaceAll("'", "''")}'`;
17
17
  /** A group of unknown size counts as large: hidden, rather than shown on a guess. */
18
18
  const GROUP_SIZE = "coalesce(c.participants_count, (SELECT mc.listed_count FROM member_counts mc WHERE mc.chat_id = c.id " +
19
19
  "ORDER BY mc.date DESC LIMIT 1))";
20
- /** Each tie as the identities that have it. */
21
- const tieIdentities = () => {
20
+ /**
21
+ * Telegram and WhatsApp keep no member list, so a chat's people are also whoever wrote in it. For a few people, asked
22
+ * per identity through `messages_by_sender_identity_id`; for everyone, one pass over the messages, which is faster.
23
+ */
24
+ const chatPeople = (where, few) => {
25
+ const members = `SELECT m.identity_id FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE ${where}`;
26
+ if (few)
27
+ return (`(l.identity_id IN (${members}) OR EXISTS (SELECT 1 FROM messages s JOIN chats c ON c.id = s.chat_id ` +
28
+ `WHERE s.sender_identity_id = l.identity_id AND s.outgoing IS NOT 1 AND ${where}))`);
29
+ return (`l.identity_id IN (${members} UNION SELECT s.sender_identity_id FROM chats c JOIN messages s ON s.chat_id = c.id ` +
30
+ `WHERE ${where} AND s.sender_identity_id IS NOT NULL AND s.outgoing IS NOT 1)`);
31
+ };
32
+ const among = (identities) => `l.identity_id IN (${identities})`;
33
+ /**
34
+ * NEED-2500 A: a CRM contact ties a person only when the CRM ties them to the owner, by a deal or lead whose owner is
35
+ * the owner's person, so the owner's CRM user must be linked to the owner. The user a CRM sync signs in as is not the
36
+ * owner: a portal's webhook may belong to a colleague. A CRM's users tie as before.
37
+ */
38
+ // A deal's links name the people its CRM records had then; one merged into another person since still counts.
39
+ const OWNERS_CRM_PEOPLE = "SELECT id FROM persons WHERE owner = 1 UNION SELECT e.from_person_id FROM identity_link_events e " +
40
+ "JOIN identity_links l ON l.identity_id = e.identity_id JOIN persons p ON p.id = l.person_id AND p.owner = 1";
41
+ const crmTie = (crm) => {
42
+ if (crm.length === 0)
43
+ return "SELECT NULL WHERE 0";
44
+ const providers = crm.map(quoted).join(", ");
45
+ const contacts = "SELECT d.to_id FROM links d JOIN links o ON o.from_type = d.from_type AND o.from_id = d.from_id " +
46
+ "AND o.kind = 'related-to' AND o.role = 'owner' AND o.to_type = 'person' AND o.deleted_at IS NULL " +
47
+ "WHERE d.from_type IN ('deal', 'lead') AND d.kind = 'related-to' AND d.to_type = 'person' " +
48
+ `AND d.role IS NOT 'owner' AND d.deleted_at IS NULL AND o.to_id IN (${OWNERS_CRM_PEOPLE})`;
49
+ return (`SELECT id FROM identities WHERE provider IN (${providers}) AND external_id LIKE '%/user/%' UNION ` +
50
+ `SELECT l.identity_id FROM identity_links l WHERE l.person_id IN (${contacts}) UNION ` +
51
+ `SELECT e.identity_id FROM identity_link_events e WHERE e.from_person_id IN (${contacts}) AND ${mergeSql("e")}`);
52
+ };
53
+ /** Each tie as a condition on the identity link `l`. */
54
+ const tieIdentities = (few) => {
22
55
  const crm = crmProviders();
23
56
  return {
24
- chat: "SELECT m.identity_id FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.kind = 'dialog'",
25
- "small-group": "SELECT m.identity_id FROM chats c JOIN chat_members m ON m.chat_id = c.id " +
26
- `WHERE c.kind = 'group' AND ${GROUP_SIZE} <= ${SMALL_GROUP_MEMBERS}`,
57
+ chat: chatPeople("c.kind = 'dialog'", few),
58
+ "small-group": chatPeople(`c.kind = 'group' AND ${GROUP_SIZE} <= ${SMALL_GROUP_MEMBERS}`, few),
27
59
  // NEED-2342 A: the owner wrote to them; mail they sent, a newsletter included, is no tie.
28
- mail: "SELECT r.identity_id FROM emails e JOIN email_recipients r ON r.email_id = e.id " +
29
- "WHERE e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1 AND r.identity_id IS NOT NULL",
30
- meeting: "SELECT identity_id FROM meeting_participants UNION ALL " +
31
- "SELECT identity_id FROM calendar_entry_participants WHERE resource = 0 AND identity_id IS NOT NULL",
32
- crm: crm.length === 0
33
- ? "SELECT NULL WHERE 0"
34
- : `SELECT id FROM identities WHERE provider IN (${crm.map(quoted).join(", ")})`,
35
- "phone-book": "SELECT identity_id FROM account_identities WHERE address_book = 1",
60
+ mail: among("SELECT r.identity_id FROM emails e JOIN email_recipients r ON r.email_id = e.id " +
61
+ "WHERE e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1 AND r.identity_id IS NOT NULL"),
62
+ meeting: among("SELECT identity_id FROM meeting_participants UNION ALL " +
63
+ "SELECT identity_id FROM calendar_entry_participants WHERE resource = 0 AND identity_id IS NOT NULL"),
64
+ crm: among(crmTie(crm)),
65
+ "phone-book": among("SELECT identity_id FROM account_identities WHERE address_book = 1"),
36
66
  };
37
67
  };
38
68
  /**
@@ -40,8 +70,8 @@ const tieIdentities = () => {
40
70
  * the owner, a person added by hand (no identity, and not merged away), and a task's assignee, a merged-away one as
41
71
  * the person they are now. Takes the merged assignees (`mergedAssignees`) as its one parameter.
42
72
  */
43
- const reasonRows = () => [
44
- ...Object.entries(tieIdentities()).map(([tie, identities]) => `SELECT l.person_id AS person, '${tie}' AS tie FROM identity_links l WHERE l.identity_id IN (${identities})`),
73
+ const reasonRows = (only) => [
74
+ ...Object.entries(tieIdentities(only !== "")).map(([tie, holds]) => `SELECT l.person_id AS person, '${tie}' AS tie FROM identity_links l WHERE ${holds}${only}`),
45
75
  "SELECT entity_id, 'crm' FROM records WHERE entity_type = 'person' AND deleted_at IS NULL AND entity_id IS NOT NULL",
46
76
  "SELECT id, 'owner' FROM persons WHERE owner = 1",
47
77
  "SELECT p.id, 'added' FROM persons p WHERE NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) " +
@@ -53,14 +83,16 @@ const reasonRows = () => [
53
83
  const ORDER = [...ALWAYS_SHOWN, ...PERSON_TIES];
54
84
  /**
55
85
  * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default.
56
- * `people` narrows it to those. One pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
86
+ * `people` narrows it to those. On 40,000 identities and 400,000 messages about 130 ms for everyone, 1 ms for a page.
57
87
  */
58
88
  export const shownReasons = (database, people) => {
59
89
  const found = new Map();
60
- const only = people === undefined ? "" : " WHERE person IN (SELECT value FROM json_each(?))";
61
- for (const row of database
62
- .prepare(`SELECT DISTINCT person, tie FROM (${reasonRows()})${only}`)
63
- .all(mergedAssignees(database), ...(people === undefined ? [] : [JSON.stringify(people)]))) {
90
+ const scoped = people !== undefined;
91
+ const sql = scoped
92
+ ? "WITH only(id) AS (SELECT value FROM json_each(?)) SELECT DISTINCT person, tie FROM " +
93
+ `(${reasonRows(" AND l.person_id IN (SELECT id FROM only)")}) WHERE person IN (SELECT id FROM only)`
94
+ : `SELECT DISTINCT person, tie FROM (${reasonRows("")})`;
95
+ for (const row of database.prepare(sql).all(...(scoped ? [JSON.stringify(people)] : []), mergedAssignees(database))) {
64
96
  const person = Number(row.person);
65
97
  const reasons = found.get(person) ?? new Set();
66
98
  reasons.add(row.tie);
@@ -6,6 +6,7 @@ import { linkKind } from "./link-kinds.js";
6
6
  import { CORPORA, drainCorpus } from "./note-index.js";
7
7
  import { stemmerCache, storeStemmers } from "./stems.js";
8
8
  import { inboxKey } from "./task-keys.js";
9
+ import { placeholderTitleOf } from "./task-titles.js";
9
10
  import { taskRowOf, thingOf } from "./things.js";
10
11
  const DAY = 86_400_000;
11
12
  /** Tasks closed longer ago are done with: a new message about them is new work, or a follow-up. */
@@ -20,7 +21,6 @@ const REPLY_DEPTH = 20;
20
21
  export const LINKED_MESSAGES = 5;
21
22
  /** A message linked by any of these is about the task; `answered-by` is the owner's own answer. */
22
23
  const ABOUT_TASK = ["related-to", "evidence", "created-from"];
23
- const PLACEHOLDER = (row) => `${String(row.type)} — ${String(row.source_locator ?? "")}`;
24
24
  export const taskSimilarityOver = (context) => {
25
25
  const { database, now } = context;
26
26
  const stemmerFor = stemmerCache();
@@ -68,7 +68,7 @@ export const taskSimilarityOver = (context) => {
68
68
  return {
69
69
  row: Number(row.id),
70
70
  project: Number(row.project_id),
71
- title: String(row.title) === PLACEHOLDER(row) ? "" : String(row.title),
71
+ title: String(row.title) === placeholderTitleOf(row) ? "" : String(row.title),
72
72
  description: row.description == null ? "" : String(row.description),
73
73
  ...(row.category == null ? {} : { category: String(row.category) }),
74
74
  ...(source ? { source } : {}),
@@ -0,0 +1,12 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ type Row = Record<string, unknown>;
3
+ /** The title a rule gives a task it finds in a message: no message text is stored, so it is only a reference. */
4
+ export declare const placeholderTitleOf: (row: Row) => string;
5
+ /** Same test in SQL, against a `tasks` row. */
6
+ export declare const PLACEHOLDER_TITLE_SQL = "title = type || ' \u2014 ' || coalesce(source_locator, '')";
7
+ /**
8
+ * What to show as a task's title: the first line of its source message while the stored title is still the
9
+ * placeholder, the stored title otherwise. Read time only, so a deleted message leaves nothing behind.
10
+ */
11
+ export declare const displayTitleOf: (database: CacheDatabase, row: Row) => string;
12
+ export {};
@@ -0,0 +1,42 @@
1
+ import { isLocator } from "../../domain/locator.js";
2
+ import { thingOf } from "./things.js";
3
+ const MAX_TITLE = 120;
4
+ /** The title a rule gives a task it finds in a message: no message text is stored, so it is only a reference. */
5
+ export const placeholderTitleOf = (row) => `${String(row.type)} — ${String(row.source_locator ?? "")}`;
6
+ /** Same test in SQL, against a `tasks` row. */
7
+ export const PLACEHOLDER_TITLE_SQL = "title = type || ' — ' || coalesce(source_locator, '')";
8
+ const firstLine = (text) => {
9
+ const line = text
10
+ .split(/\r?\n/)
11
+ .find((one) => one.trim() !== "")
12
+ ?.trim();
13
+ if (line === undefined)
14
+ return undefined;
15
+ if (line.length <= MAX_TITLE)
16
+ return line;
17
+ const cut = line.slice(0, MAX_TITLE);
18
+ const space = cut.lastIndexOf(" ");
19
+ return `${(space > 0 ? cut.slice(0, space) : cut).replace(/[\s.,;:!?-]+$/, "")}…`;
20
+ };
21
+ /**
22
+ * What to show as a task's title: the first line of its source message while the stored title is still the
23
+ * placeholder, the stored title otherwise. Read time only, so a deleted message leaves nothing behind.
24
+ */
25
+ export const displayTitleOf = (database, row) => {
26
+ const stored = String(row.title);
27
+ const locator = row.source_locator;
28
+ if (stored !== placeholderTitleOf(row) || typeof locator !== "string" || !locator.startsWith("msg:"))
29
+ return stored;
30
+ if (!isLocator(locator))
31
+ return stored;
32
+ try {
33
+ const thing = thingOf(database, locator);
34
+ if (thing?.type !== "message")
35
+ return stored;
36
+ const message = database.prepare("SELECT text FROM messages WHERE id = ? AND deleted_at IS NULL").get(thing.id);
37
+ return (typeof message?.text === "string" ? firstLine(message.text) : undefined) ?? stored;
38
+ }
39
+ catch {
40
+ return stored;
41
+ }
42
+ };
@@ -12,6 +12,7 @@ import { taskCloseOver } from "./task-close-store.js";
12
12
  import { inboxKey, typedKey } from "./task-keys.js";
13
13
  import { taskPairsOver } from "./task-pairs.js";
14
14
  import { taskStatsOver } from "./task-stats.js";
15
+ import { displayTitleOf } from "./task-titles.js";
15
16
  import { taskRowOf, thingOf } from "./things.js";
16
17
  import { read, write } from "./transaction.js";
17
18
  import { recordTaskEvent, workTasksOver } from "./work-tasks.js";
@@ -116,7 +117,7 @@ export const taskStoreOver = (context) => {
116
117
  .all(project, ...(where?.params ?? []), limit, offset)
117
118
  .map((row) => ({
118
119
  task: toTask(row),
119
- title: String(row.title),
120
+ title: displayTitleOf(database, row),
120
121
  updatedAt: new Date(Number(row.updated_at)),
121
122
  closeSuggestion: closeSuggestionOf(database, row),
122
123
  }));
@@ -15,6 +15,7 @@ import { closeSuggestionOf, SUGGESTION_COLUMNS } from "./task-close.js";
15
15
  import { addComment, authorNamed, commentsOf } from "./task-comments.js";
16
16
  import { INBOX_KEY_LENGTH, inboxKey } from "./task-keys.js";
17
17
  import { taskRelationsStoreOver } from "./task-relations.js";
18
+ import { displayTitleOf } from "./task-titles.js";
18
19
  import { taskIdOf, taskRowOf, thingOf } from "./things.js";
19
20
  import { write } from "./transaction.js";
20
21
  export const TASK_ROLES = ["assignee", "reviewer", "watcher"];
@@ -128,7 +129,7 @@ export const workTaskOperationsOver = (context) => {
128
129
  project: `project:${row.project_id}`,
129
130
  ...projectNamed(Number(row.project_id)),
130
131
  createdBy: authorNamed(database, row),
131
- title: String(row.title),
132
+ title: displayTitleOf(database, row),
132
133
  description: row.description == null ? null : String(row.description),
133
134
  type: row.type,
134
135
  status: row.status,
@@ -50,6 +50,9 @@ export interface LinkOptions {
50
50
  export interface LinkedIdentity extends IdentityRef {
51
51
  name: string | null;
52
52
  username: string | null;
53
+ /** The phone and address its source gave it, when it gave one. */
54
+ phone?: string | null;
55
+ email?: string | null;
53
56
  isBot: boolean | null;
54
57
  /** The accounts in this store that have seen it. */
55
58
  accounts: Id[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.629.0",
3
+ "version": "0.630.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -15,7 +15,7 @@
15
15
  "type": "module",
16
16
  "wirecat": {
17
17
  "store": {
18
- "speaks": 62,
18
+ "speaks": 63,
19
19
  "minCompatible": 56
20
20
  }
21
21
  },