@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
@@ -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
  };
@@ -1,5 +1,8 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
- /** A group this small is people the owner knows; in a bigger one an author alone is background. */
2
+ /**
3
+ * A group this small is people the owner knows; in a bigger one an author alone is background. Store version 62's
4
+ * trigger `person_kind_chat_au` holds the same number: changing it takes a migration that replaces that trigger.
5
+ */
3
6
  export declare const SMALL_GROUP_MEMBERS = 10;
4
7
  /** What ties a person to the owner, from what the store holds about them. */
5
8
  export declare const PERSON_TIES: readonly ["chat", "small-group", "mail", "meeting", "crm", "phone-book"];
@@ -8,7 +11,7 @@ export type PersonTie = (typeof PERSON_TIES)[number];
8
11
  export declare const ALWAYS_SHOWN: readonly ["owner", "added", "task"];
9
12
  export type ShownBecause = (typeof ALWAYS_SHOWN)[number] | PersonTie;
10
13
  /**
11
- * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default. One
12
- * pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
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. On 40,000 identities and 400,000 messages about 130 ms for everyone, 1 ms for a page.
13
16
  */
14
- export declare const shownReasons: (database: CacheDatabase) => Map<number, ShownBecause[]>;
17
+ export declare const shownReasons: (database: CacheDatabase, people?: readonly number[]) => Map<number, ShownBecause[]>;
@@ -1,7 +1,10 @@
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
- /** A group this small is people the owner knows; in a bigger one an author alone is background. */
4
+ /**
5
+ * A group this small is people the owner knows; in a bigger one an author alone is background. Store version 62's
6
+ * trigger `person_kind_chat_au` holds the same number: changing it takes a migration that replaces that trigger.
7
+ */
5
8
  export const SMALL_GROUP_MEMBERS = 10;
6
9
  /** What ties a person to the owner, from what the store holds about them. */
7
10
  export const PERSON_TIES = ["chat", "small-group", "mail", "meeting", "crm", "phone-book"];
@@ -14,22 +17,52 @@ const quoted = (value) => `'${value.replaceAll("'", "''")}'`;
14
17
  /** A group of unknown size counts as large: hidden, rather than shown on a guess. */
15
18
  const GROUP_SIZE = "coalesce(c.participants_count, (SELECT mc.listed_count FROM member_counts mc WHERE mc.chat_id = c.id " +
16
19
  "ORDER BY mc.date DESC LIMIT 1))";
17
- /** Each tie as the identities that have it. */
18
- 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) => {
19
55
  const crm = crmProviders();
20
56
  return {
21
- chat: "SELECT m.identity_id FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.kind = 'dialog'",
22
- "small-group": "SELECT m.identity_id FROM chats c JOIN chat_members m ON m.chat_id = c.id " +
23
- `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),
24
59
  // NEED-2342 A: the owner wrote to them; mail they sent, a newsletter included, is no tie.
25
- mail: "SELECT r.identity_id FROM emails e JOIN email_recipients r ON r.email_id = e.id " +
26
- "WHERE e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1 AND r.identity_id IS NOT NULL",
27
- meeting: "SELECT identity_id FROM meeting_participants UNION ALL " +
28
- "SELECT identity_id FROM calendar_entry_participants WHERE resource = 0 AND identity_id IS NOT NULL",
29
- crm: crm.length === 0
30
- ? "SELECT NULL WHERE 0"
31
- : `SELECT id FROM identities WHERE provider IN (${crm.map(quoted).join(", ")})`,
32
- "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"),
33
66
  };
34
67
  };
35
68
  /**
@@ -37,8 +70,8 @@ const tieIdentities = () => {
37
70
  * the owner, a person added by hand (no identity, and not merged away), and a task's assignee, a merged-away one as
38
71
  * the person they are now. Takes the merged assignees (`mergedAssignees`) as its one parameter.
39
72
  */
40
- const reasonRows = () => [
41
- ...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}`),
42
75
  "SELECT entity_id, 'crm' FROM records WHERE entity_type = 'person' AND deleted_at IS NULL AND entity_id IS NOT NULL",
43
76
  "SELECT id, 'owner' FROM persons WHERE owner = 1",
44
77
  "SELECT p.id, 'added' FROM persons p WHERE NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) " +
@@ -49,14 +82,17 @@ const reasonRows = () => [
49
82
  ].join(" UNION ALL ");
50
83
  const ORDER = [...ALWAYS_SHOWN, ...PERSON_TIES];
51
84
  /**
52
- * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default. One
53
- * pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
85
+ * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default.
86
+ * `people` narrows it to those. On 40,000 identities and 400,000 messages about 130 ms for everyone, 1 ms for a page.
54
87
  */
55
- export const shownReasons = (database) => {
88
+ export const shownReasons = (database, people) => {
56
89
  const found = new Map();
57
- for (const row of database
58
- .prepare(`SELECT DISTINCT person, tie FROM (${reasonRows()})`)
59
- .all(mergedAssignees(database))) {
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))) {
60
96
  const person = Number(row.person);
61
97
  const reasons = found.get(person) ?? new Set();
62
98
  reasons.add(row.tie);
@@ -1,8 +1,9 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { replaceMembers } from "./chats.js";
2
3
  import { and, asc, eq, gte, inArray, isNotNull, isNull, or, sql } from "./drizzle/core.js";
3
4
  import { identityPk, seenIdentity } from "./identities.js";
4
5
  import { bound } from "./query-filter.js";
5
- import { chatMembers, chats, identities, identityRevisions, memberCounts, memberStays } from "./schema.js";
6
+ import { chats, identities, identityRevisions, memberCounts, memberStays } from "./schema.js";
6
7
  const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
7
8
  const marksOf = ({ isBot, flagged, deleted, hasPhoto }) => ({
8
9
  ...(isBot === undefined ? {} : { bot: isBot }),
@@ -104,9 +105,7 @@ export const saveRoster = (context, accountKey, provider, chatKey, { members, co
104
105
  orm.update(memberStays).set({ leftAt: observedAt }).where(eq(memberStays.id, pk)).run();
105
106
  change.gone.push(id);
106
107
  }
107
- orm.delete(chatMembers).where(eq(chatMembers.chatId, chatKey)).run();
108
- for (const person of present)
109
- orm.insert(chatMembers).values({ chatId: chatKey, identityId: person, createdAt: at }).run();
108
+ replaceMembers(context, chatKey, [...present], at);
110
109
  }
111
110
  const day = new Date(at).toISOString().slice(0, 10);
112
111
  const count = {
@@ -842,6 +842,86 @@ export declare const persons: import("drizzle-orm/sqlite-core").SQLiteTableWithC
842
842
  identity: undefined;
843
843
  generated: undefined;
844
844
  }, {}>;
845
+ kind: import("drizzle-orm/sqlite-core").SQLiteColumn<{
846
+ name: string;
847
+ tableName: "persons";
848
+ dataType: "string";
849
+ data: string;
850
+ driverParam: string;
851
+ notNull: false;
852
+ hasDefault: false;
853
+ isPrimaryKey: false;
854
+ isAutoincrement: false;
855
+ hasRuntimeDefault: false;
856
+ enumValues: [string, ...string[]];
857
+ baseColumn: never;
858
+ identity: undefined;
859
+ generated: undefined;
860
+ }, {}>;
861
+ nameOrder: import("drizzle-orm/sqlite-core").SQLiteColumn<{
862
+ name: string;
863
+ tableName: "persons";
864
+ dataType: "string";
865
+ data: string;
866
+ driverParam: string;
867
+ notNull: false;
868
+ hasDefault: false;
869
+ isPrimaryKey: false;
870
+ isAutoincrement: false;
871
+ hasRuntimeDefault: false;
872
+ enumValues: [string, ...string[]];
873
+ baseColumn: never;
874
+ identity: undefined;
875
+ generated: undefined;
876
+ }, {}>;
877
+ messagesFrom: import("drizzle-orm/sqlite-core").SQLiteColumn<{
878
+ name: string;
879
+ tableName: "persons";
880
+ dataType: "number int53";
881
+ data: number;
882
+ driverParam: number;
883
+ notNull: false;
884
+ hasDefault: false;
885
+ isPrimaryKey: false;
886
+ isAutoincrement: false;
887
+ hasRuntimeDefault: false;
888
+ enumValues: undefined;
889
+ baseColumn: never;
890
+ identity: undefined;
891
+ generated: undefined;
892
+ }, {}>;
893
+ taskCount: import("drizzle-orm/sqlite-core").SQLiteColumn<{
894
+ name: string;
895
+ tableName: "persons";
896
+ dataType: "number int53";
897
+ data: number;
898
+ driverParam: number;
899
+ notNull: false;
900
+ hasDefault: false;
901
+ isPrimaryKey: false;
902
+ isAutoincrement: false;
903
+ hasRuntimeDefault: false;
904
+ enumValues: undefined;
905
+ baseColumn: never;
906
+ identity: undefined;
907
+ generated: undefined;
908
+ }, {}>;
909
+ lastContact: import("drizzle-orm/sqlite-core").SQLiteColumn<{
910
+ name: string;
911
+ tableName: "persons";
912
+ dataType: "number int53";
913
+ data: number;
914
+ driverParam: number;
915
+ notNull: false;
916
+ hasDefault: false;
917
+ isPrimaryKey: false;
918
+ isAutoincrement: false;
919
+ hasRuntimeDefault: false;
920
+ enumValues: undefined;
921
+ baseColumn: never;
922
+ identity: undefined;
923
+ generated: undefined;
924
+ }, {}>;
845
925
  };
846
926
  dialect: 'sqlite';
847
927
  isAlias: false;
@@ -86,7 +86,15 @@ export const persons = sqliteTable("persons", {
86
86
  owner: integer("owner").notNull().default(0),
87
87
  createdAt: integer("created_at").notNull(),
88
88
  updatedAt: integer("updated_at").notNull(),
89
- });
89
+ kind: text("kind"),
90
+ nameOrder: text("name_order"),
91
+ messagesFrom: integer("messages_from"),
92
+ taskCount: integer("task_count"),
93
+ lastContact: integer("last_contact"),
94
+ }, (table) => [
95
+ index("persons_by_kind").on(table.kind),
96
+ index("persons_kind_to_work_out").on(table.id).where(sql `kind IS NULL`),
97
+ ]);
90
98
  export const identities = sqliteTable("identities", {
91
99
  id: integer("id").primaryKey(),
92
100
  provider: text("provider").notNull(),
@@ -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.628.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": 61,
18
+ "speaks": 63,
19
19
  "minCompatible": 56
20
20
  }
21
21
  },