@wirecat/cli-core 0.622.0 → 0.623.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 (45) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/background/budget.d.ts +2 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/background/schedules.d.ts +2 -9
  5. package/dist/background/schedules.js +10 -15
  6. package/dist/background/when.d.ts +28 -0
  7. package/dist/background/when.js +40 -0
  8. package/dist/calendar/mcp/index.d.ts +12 -12
  9. package/dist/cli/messenger/messages-search-command.js +4 -0
  10. package/dist/cli/program.js +6 -3
  11. package/dist/cli/schedule/schedule-command.js +14 -8
  12. package/dist/domain/display-names.d.ts +16 -0
  13. package/dist/domain/display-names.js +50 -0
  14. package/dist/errors/reasons.js +1 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +1 -0
  17. package/dist/meetings/mcp/index.d.ts +15 -15
  18. package/dist/search/lucene/resolved.d.ts +1 -0
  19. package/dist/search/lucene/types.d.ts +8 -0
  20. package/dist/search/lucene/types.js +7 -0
  21. package/dist/services/messages-combined.js +3 -2
  22. package/dist/services/messages-discovery.js +3 -2
  23. package/dist/services/messages-search.js +1 -0
  24. package/dist/services/messages.d.ts +2 -0
  25. package/dist/services/people.js +1 -1
  26. package/dist/store/identity-links.d.ts +3 -3
  27. package/dist/store/identity-links.js +3 -3
  28. package/dist/store/index.d.ts +2 -0
  29. package/dist/store/index.js +1 -0
  30. package/dist/store/people.d.ts +21 -2
  31. package/dist/store/people.js +35 -15
  32. package/dist/store/sqlite/lucene.js +12 -11
  33. package/dist/store/sqlite/manifest.js +1 -0
  34. package/dist/store/sqlite/migrations.generated.js +7 -0
  35. package/dist/store/sqlite/name-traces.d.ts +17 -0
  36. package/dist/store/sqlite/name-traces.js +112 -0
  37. package/dist/store/sqlite/notes.js +6 -3
  38. package/dist/store/sqlite/people-list.d.ts +44 -0
  39. package/dist/store/sqlite/people-list.js +151 -0
  40. package/dist/store/sqlite/person-match-scan.js +33 -0
  41. package/dist/store/sqlite/person-ties.d.ts +14 -0
  42. package/dist/store/sqlite/person-ties.js +66 -0
  43. package/dist/store/sqlite/schema.d.ts +16 -0
  44. package/dist/store/sqlite/schema.js +3 -0
  45. package/package.json +2 -2
@@ -0,0 +1,112 @@
1
+ import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { displayName, nameKey } from "../../domain/display-names.js";
3
+ import { storedPhone } from "../../domain/phones.js";
4
+ import { FREE_MAIL } from "../../mail/score.js";
5
+ import { referenceOfThing } from "./things.js";
6
+ /** People, owner aside, by the name they share once case, quotes and word order are set aside. */
7
+ export const peopleByNameKey = (database) => {
8
+ const found = new Map();
9
+ for (const row of database
10
+ .prepare("SELECT p.id, p.name FROM persons p WHERE p.owner = 0 AND p.name IS NOT NULL " +
11
+ "AND EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) ORDER BY p.id")
12
+ .all()) {
13
+ const name = String(row.name);
14
+ const key = nameKey(name);
15
+ if (key === null)
16
+ continue;
17
+ const held = found.get(key) ?? { people: [], name: displayName(name) ?? name };
18
+ held.people.push(Number(row.id));
19
+ found.set(key, held);
20
+ }
21
+ return found;
22
+ };
23
+ const addressOf = (value) => {
24
+ const address = typeof value === "string" ? value.trim().toLowerCase() : "";
25
+ return isEmailAddress(address) && !isNoReplyAddress(address) ? address : undefined;
26
+ };
27
+ /** A company's domain: not a free mailbox such as gmail.com, and not from a role address such as `info@`. */
28
+ const companyDomain = (address) => {
29
+ const domain = address.split("@")[1];
30
+ return domain === undefined || FREE_MAIL.has(domain) || isRoleAddress(address) ? undefined : domain;
31
+ };
32
+ const tracesOf = (database, person) => {
33
+ const traces = { phones: [], emails: [], domains: [] };
34
+ for (const row of database
35
+ .prepare("SELECT i.id, i.provider, i.external_id, i.phone, i.email FROM identity_links l " +
36
+ "JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ? AND i.provider <> 'org-email' ORDER BY i.id")
37
+ .all(person)) {
38
+ const identity = Number(row.id);
39
+ const provider = String(row.provider);
40
+ const phone = provider === "phone" ? row.external_id : row.phone;
41
+ const stored = typeof phone === "string" ? storedPhone(phone, provider) : undefined;
42
+ if (stored !== undefined)
43
+ traces.phones.push({ identity, value: stored });
44
+ for (const address of [addressOf(row.email), provider === "email" ? addressOf(row.external_id) : undefined]) {
45
+ if (address === undefined)
46
+ continue;
47
+ traces.emails.push({ identity, value: address });
48
+ const domain = companyDomain(address);
49
+ if (domain !== undefined)
50
+ traces.domains.push({ identity, value: domain });
51
+ }
52
+ }
53
+ return traces;
54
+ };
55
+ const common = (a, b) => {
56
+ for (const one of a) {
57
+ const other = b.find(({ value }) => value === one.value);
58
+ if (other !== undefined)
59
+ return [one, other];
60
+ }
61
+ return undefined;
62
+ };
63
+ const commonChat = (database, a, b) => database
64
+ .prepare("SELECT m1.chat_id, m1.identity_id AS one, m2.identity_id AS other FROM identity_links l1 " +
65
+ "JOIN chat_members m1 ON m1.identity_id = l1.identity_id " +
66
+ "JOIN chat_members m2 ON m2.chat_id = m1.chat_id " +
67
+ "JOIN identity_links l2 ON l2.identity_id = m2.identity_id " +
68
+ "WHERE l1.person_id = ? AND l2.person_id = ? ORDER BY m1.chat_id LIMIT 1")
69
+ .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) => {
72
+ const [one, other] = [tracesOf(database, a), tracesOf(database, b)];
73
+ const phone = common(one.phones, other.phones);
74
+ if (phone)
75
+ return {
76
+ identity: phone[0].identity,
77
+ with: phone[1].identity,
78
+ kind: "phone",
79
+ evidence: [],
80
+ reason: `same name «${name}» and the same phone`,
81
+ };
82
+ const email = common(one.emails, other.emails);
83
+ if (email)
84
+ return {
85
+ identity: email[0].identity,
86
+ with: email[1].identity,
87
+ kind: "email",
88
+ evidence: [],
89
+ reason: `same name «${name}» and the same address ${email[0].value}`,
90
+ };
91
+ const chat = commonChat(database, a, b);
92
+ if (chat) {
93
+ const ref = referenceOfThing(database, { type: "chat", id: Number(chat.chat_id) });
94
+ return {
95
+ identity: Number(chat.one),
96
+ with: Number(chat.other),
97
+ kind: "chat",
98
+ evidence: ref === undefined ? [] : [ref],
99
+ reason: `same name «${name}» and a chat they are both in`,
100
+ };
101
+ }
102
+ const domain = common(one.domains, other.domains);
103
+ if (domain)
104
+ return {
105
+ identity: domain[0].identity,
106
+ with: domain[1].identity,
107
+ kind: "email-domain",
108
+ evidence: [],
109
+ reason: `same name «${name}» and mail at the same company, ${domain[0].value}`,
110
+ };
111
+ return undefined;
112
+ };
@@ -650,11 +650,14 @@ export const notesStoreOver = (context) => {
650
650
  const id = Number(documentRow(documentId).id);
651
651
  database.prepare("DELETE FROM links WHERE from_type = 'document' AND from_id = ? AND source = 'file'").run(id);
652
652
  const written = links.map((link) => insertLink(context, { ...link, from: `document:${id}`, origin: "file" }));
653
- // What a file's source says, such as a Drive owner, is reported by its account, not waiting for review.
653
+ // What a file's source says, such as a Drive owner (`google-drive:files.get`), is reported by its account,
654
+ // not waiting for review. A program's guess (`scan`) or an agent's (`agent:…`) still waits.
654
655
  database
655
656
  .prepare("UPDATE links SET account_id = (SELECT account_id FROM documents WHERE id = ?) WHERE from_type = 'document' " +
656
- `AND from_id = ? AND source = 'file' AND confirmed = 0 AND account_id IS NULL AND kind IN (${RELATIONSHIPS})`)
657
- .run(id, id);
657
+ `AND from_id = ? AND source = 'file' AND confirmed = 0 AND account_id IS NULL AND kind IN (${RELATIONSHIPS}) ` +
658
+ "AND (SELECT substr(json_extract(links.metadata, '$.provenance'), 1, length(a.provider) + 1) = " +
659
+ "a.provider || ':' FROM documents d JOIN accounts a ON a.id = d.account_id WHERE d.id = ?)")
660
+ .run(id, id, id);
658
661
  const reread = database.prepare("SELECT * FROM links WHERE id = ?");
659
662
  return written.map((link) => linkOf(database, reread.get(Number(link.id))));
660
663
  }),
@@ -0,0 +1,44 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import { type ShownBecause } from "./person-ties.js";
3
+ export interface PeopleListOptions {
4
+ /** Part of a name or username, at least 3 characters. */
5
+ query?: string;
6
+ /** Also the people with no tie to the owner. */
7
+ all?: boolean;
8
+ /** `tasks`: the owner, then by how many tasks name them, then by name. */
9
+ sort?: "tasks" | "name";
10
+ limit: number;
11
+ offset?: number;
12
+ }
13
+ export interface ListedPerson {
14
+ person: string;
15
+ /** As stored; `displayName` is what to show. */
16
+ name: string | null;
17
+ displayName: string | null;
18
+ owner: boolean;
19
+ tasks: number;
20
+ username: string | null;
21
+ phone: string | null;
22
+ email: string | null;
23
+ /** Why they are shown; empty for someone hidden by default. */
24
+ ties: ShownBecause[];
25
+ }
26
+ export interface PeopleList {
27
+ items: ListedPerson[];
28
+ hasMore: boolean;
29
+ /** Everyone the list holds over every page. */
30
+ total: number;
31
+ /** The people matching that have no tie to the owner, shown only with `all`. */
32
+ hidden: number;
33
+ }
34
+ export interface SimilarPerson extends ListedPerson {
35
+ /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
36
+ sameName: boolean;
37
+ }
38
+ /** People by name or by task count, the owner first; by default only those with a tie to the owner. */
39
+ export declare const listPeople: (database: CacheDatabase, options: PeopleListOptions) => PeopleList;
40
+ /**
41
+ * People whose name, or a name of one of their identities, has a word starting with each typed word, for a form
42
+ * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
43
+ */
44
+ export declare const similarPeople: (database: CacheDatabase, typed: string, limit: number) => SimilarPerson[];
@@ -0,0 +1,151 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { displayName, nameKey } from "../../domain/display-names.js";
3
+ import { fold } from "../normalize.js";
4
+ import { mergedAwaySql } from "./merged-persons.js";
5
+ import { shownReasons } from "./person-ties.js";
6
+ import { mergedAssignees } from "./task-board.js";
7
+ const MIN_QUERY = 3;
8
+ const ftsPhrase = (text) => `"${text.replaceAll('"', '""')}"`;
9
+ const matching = (query) => {
10
+ if (query === undefined)
11
+ return { sql: "", params: [] };
12
+ const text = query.trim();
13
+ if (text.length < MIN_QUERY)
14
+ throw new CliError("validation_error", `a people search takes at least ${MIN_QUERY} characters, got "${query}"`);
15
+ return {
16
+ sql: " AND (p.id IN (SELECT l.person_id FROM identity_links l WHERE l.identity_id IN " +
17
+ "(SELECT rowid FROM identities_fts WHERE identities_fts MATCH ?)) OR p.name LIKE ? ESCAPE '\\')",
18
+ params: [ftsPhrase(text), `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`],
19
+ };
20
+ };
21
+ const firstOf = (column, provider) => `(SELECT coalesce(i.${column}, CASE WHEN i.provider = '${provider}' THEN i.external_id END) FROM identity_links l ` +
22
+ `JOIN identities i ON i.id = l.identity_id WHERE l.person_id = p.id ` +
23
+ `AND (i.${column} IS NOT NULL OR i.provider = '${provider}') ORDER BY i.id LIMIT 1)`;
24
+ const ROW = "p.id, p.name, p.owner, " +
25
+ "(SELECT i.username FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
26
+ "WHERE l.person_id = p.id AND i.username IS NOT NULL ORDER BY i.id LIMIT 1) AS username, " +
27
+ `${firstOf("phone", "phone")} AS phone, ${firstOf("email", "email")} AS email`;
28
+ const TASK_COUNTS = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)), " +
29
+ "counts AS (SELECT coalesce(m.now, a.assignee_id) AS person, count(DISTINCT t.id) AS n FROM task_assignments a " +
30
+ "JOIN tasks t ON t.id = a.task_id AND t.deleted_at IS NULL LEFT JOIN merged m ON m.id = a.assignee_id " +
31
+ "WHERE a.assignee_type = 'person' GROUP BY 1)";
32
+ /** Sorted as read: wrapping quotes and spaces do not decide a name's place. */
33
+ const BY_NAME = "p.name IS NULL, ltrim(p.name, ' \"''«“„‘`') COLLATE NOCASE, p.id";
34
+ const listedOf = (row, ties) => {
35
+ const text = (value) => (value == null ? null : String(value));
36
+ const id = Number(row.id);
37
+ const name = text(row.name);
38
+ const contact = { username: text(row.username), phone: text(row.phone), email: text(row.email) };
39
+ return {
40
+ person: `person:${id}`,
41
+ name,
42
+ displayName: displayName(name, contact),
43
+ owner: Number(row.owner) === 1,
44
+ tasks: Number(row.n ?? 0),
45
+ ...contact,
46
+ ties: ties.get(id) ?? [],
47
+ };
48
+ };
49
+ /** Each person's row with their contact and task count, in the order given. */
50
+ const rowsOf = (database, people) => {
51
+ if (people.length === 0)
52
+ return [];
53
+ const byId = new Map(database
54
+ .prepare(`${TASK_COUNTS} SELECT ${ROW}, coalesce(c.n, 0) AS n FROM persons p LEFT JOIN counts c ON c.person = p.id ` +
55
+ "WHERE p.id IN (SELECT value FROM json_each(?))")
56
+ .all(mergedAssignees(database), JSON.stringify(people))
57
+ .map((row) => [Number(row.id), row]));
58
+ return people.flatMap((person) => {
59
+ const row = byId.get(person);
60
+ return row === undefined ? [] : [row];
61
+ });
62
+ };
63
+ /** People by name or by task count, the owner first; by default only those with a tie to the owner. */
64
+ export const listPeople = (database, options) => {
65
+ const { all = false, sort = "tasks", limit, offset = 0 } = options;
66
+ const filter = matching(options.query);
67
+ const reasons = shownReasons(database);
68
+ const shown = JSON.stringify([...reasons.keys()]);
69
+ const live = `NOT ${mergedAwaySql("p")}${filter.sql}`;
70
+ const counted = database
71
+ .prepare("SELECT count(*) AS total, coalesce(sum(p.id NOT IN (SELECT value FROM json_each(?))), 0) AS hidden " +
72
+ `FROM persons p WHERE ${live}`)
73
+ .get(shown, ...filter.params);
74
+ const order = sort === "name" ? `p.owner DESC, ${BY_NAME}` : `p.owner DESC, n DESC, ${BY_NAME}`;
75
+ // Ids first: the contact columns are worked out for the page only, not for every row the sort reads.
76
+ const ids = database
77
+ .prepare(`${TASK_COUNTS} SELECT p.id, coalesce(c.n, 0) AS n FROM persons p LEFT JOIN counts c ON c.person = p.id ` +
78
+ `WHERE ${live}${all ? "" : " AND p.id IN (SELECT value FROM json_each(?))"} ORDER BY ${order} LIMIT ? OFFSET ?`)
79
+ .all(mergedAssignees(database), ...filter.params, ...(all ? [] : [shown]), limit + 1, offset)
80
+ .map((row) => Number(row.id));
81
+ const page = ids.slice(0, limit);
82
+ const hidden = Number(counted?.hidden ?? 0);
83
+ return {
84
+ items: rowsOf(database, page).map((row) => listedOf(row, reasons)),
85
+ hasMore: ids.length > limit,
86
+ total: Number(counted?.total ?? 0) - (all ? 0 : hidden),
87
+ hidden,
88
+ };
89
+ };
90
+ const words = (key) => (key === null ? [] : key.split(" "));
91
+ /** Every typed word starts a word of the name, in any order: «iv pet» finds Petrov Ivan. */
92
+ const startsEach = (typed, name) => {
93
+ const own = words(nameKey(name));
94
+ return typed.every((word) => own.some((one) => one.startsWith(word)));
95
+ };
96
+ /**
97
+ * People whose name, or a name of one of their identities, has a word starting with each typed word, for a form
98
+ * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
99
+ */
100
+ export const similarPeople = (database, typed, limit) => {
101
+ const key = nameKey(typed);
102
+ const wanted = words(key);
103
+ const longest = wanted.reduce((a, b) => (b.length > a.length ? b : a), "");
104
+ if (longest === "")
105
+ return [];
106
+ const named = new Map();
107
+ const note = (person, name) => {
108
+ if (typeof name === "string")
109
+ named.set(person, [...(named.get(person) ?? []), name]);
110
+ };
111
+ // A person added by hand has no identity to search; there are few, and SQLite folds only ASCII case.
112
+ for (const row of database
113
+ .prepare("SELECT p.id, p.name FROM persons p WHERE p.name IS NOT NULL " +
114
+ `AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) AND NOT ${mergedAwaySql("p")}`)
115
+ .all())
116
+ note(Number(row.id), row.name);
117
+ const identityRows = longest.length >= MIN_QUERY
118
+ ? database
119
+ .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities_fts f JOIN identities i ON i.id = f.rowid " +
120
+ "JOIN identity_links l ON l.identity_id = i.id WHERE identities_fts MATCH ?")
121
+ .all(ftsPhrase(longest))
122
+ : database
123
+ .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities i " +
124
+ "JOIN identity_links l ON l.identity_id = i.id WHERE i.name_folded LIKE ? ESCAPE '\\'")
125
+ .all(`%${fold(longest).replace(/[\\%_]/g, (c) => `\\${c}`)}%`);
126
+ for (const row of identityRows) {
127
+ note(Number(row.person), row.name);
128
+ note(Number(row.person), row.username);
129
+ }
130
+ const found = [...named]
131
+ .filter(([, names]) => names.some((name) => startsEach(wanted, name)))
132
+ .map(([person, names]) => ({
133
+ person,
134
+ name: names[0] ?? "",
135
+ same: names.some((name) => nameKey(name) === key),
136
+ }));
137
+ if (found.length === 0)
138
+ return [];
139
+ const ties = shownReasons(database);
140
+ const chosen = found
141
+ .sort((a, b) => Number(b.same) - Number(a.same) ||
142
+ Number(ties.has(b.person)) - Number(ties.has(a.person)) ||
143
+ a.name.localeCompare(b.name) ||
144
+ a.person - b.person)
145
+ .slice(0, limit);
146
+ const sameName = new Map(chosen.map(({ person, same }) => [person, same]));
147
+ return rowsOf(database, [...sameName.keys()]).map((row) => ({
148
+ ...listedOf(row, ties),
149
+ sameName: sameName.get(Number(row.id)) === true,
150
+ }));
151
+ };
@@ -2,6 +2,7 @@ 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";
5
6
  import { mergePerson } from "./person-links.js";
6
7
  import { personsByIdentifiers } from "./person-matcher.js";
7
8
  import { resolvePersonLinks } from "./person-resolution.js";
@@ -184,6 +185,34 @@ const sameEmail = (pass, address, holders) => {
184
185
  if (from !== into)
185
186
  into = join(pass, { from, into, identity: people.get(from), with: intoIdentity }, "email");
186
187
  };
188
+ const peopleOfIdentities = (context, identities) => new Set([...identities].flatMap((identity) => personOf(context, identity) ?? []));
189
+ /**
190
+ * One name and a shared trace (a phone, an address, a chat, a company's domain) only proposes: a name is common, so
191
+ * the owner decides every merge. More than `MOST_SHARING` people on one name is too common to propose from.
192
+ */
193
+ const sameName = (pass, people, name) => {
194
+ if (people.length > MOST_SHARING) {
195
+ pass.result.skipped.push({ persons: people.map(String), signal: "name", reason: "identity.common-name" });
196
+ return;
197
+ }
198
+ const sorted = [...people].sort((a, b) => a - b);
199
+ for (const [at, from] of sorted.entries())
200
+ for (const to of sorted.slice(at + 1)) {
201
+ const trace = sharedTrace(pass.context.database, from, to, name);
202
+ if (trace === undefined)
203
+ continue;
204
+ propose(pass, {
205
+ identity: trace.identity,
206
+ with: trace.with,
207
+ from,
208
+ to,
209
+ joins: "person",
210
+ signal: "name",
211
+ evidence: trace.evidence,
212
+ reason: trace.reason,
213
+ });
214
+ }
215
+ };
187
216
  /** What a meeting guest typed is their word only: it is proposed, and only when it names exactly one person. */
188
217
  const guestEmail = (pass, row) => {
189
218
  const { context } = pass;
@@ -244,6 +273,10 @@ export const scanMatches = (context, { full = false } = {}) => {
244
273
  for (const row of guestRows(database))
245
274
  if ((changed === undefined || changed.has(row.identity)) && !pass.index.names(row.ref))
246
275
  write(database, () => guestEmail(pass, row));
276
+ const changedPeople = changed === undefined ? undefined : peopleOfIdentities(context, changed);
277
+ for (const { people, name } of peopleByNameKey(database).values())
278
+ if (people.length > 1 && (changedPeople === undefined || people.some((one) => changedPeople.has(one))))
279
+ write(database, () => sameName(pass, people, name));
247
280
  write(database, () => database
248
281
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
249
282
  .run(CURSOR, JSON.stringify(started), context.now()));
@@ -0,0 +1,14 @@
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. */
3
+ export declare const SMALL_GROUP_MEMBERS = 10;
4
+ /** What ties a person to the owner, from what the store holds about them. */
5
+ export declare const PERSON_TIES: readonly ["chat", "small-group", "mail", "meeting", "crm", "phone-book"];
6
+ export type PersonTie = (typeof PERSON_TIES)[number];
7
+ /** Why a person with no tie is still shown: the owner, someone added by hand, someone assigned a task. */
8
+ export declare const ALWAYS_SHOWN: readonly ["owner", "added", "task"];
9
+ export type ShownBecause = (typeof ALWAYS_SHOWN)[number] | PersonTie;
10
+ /**
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`).
13
+ */
14
+ export declare const shownReasons: (database: CacheDatabase) => Map<number, ShownBecause[]>;
@@ -0,0 +1,66 @@
1
+ import { kindsOfEntry, providers } from "../../domain/providers.js";
2
+ import { mergedAwaySql } from "./merged-persons.js";
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. */
5
+ export const SMALL_GROUP_MEMBERS = 10;
6
+ /** What ties a person to the owner, from what the store holds about them. */
7
+ export const PERSON_TIES = ["chat", "small-group", "mail", "meeting", "crm", "phone-book"];
8
+ /** Why a person with no tie is still shown: the owner, someone added by hand, someone assigned a task. */
9
+ export const ALWAYS_SHOWN = ["owner", "added", "task"];
10
+ const crmProviders = () => providers()
11
+ .filter((entry) => kindsOfEntry(entry).includes("crm"))
12
+ .map(({ name }) => name);
13
+ const quoted = (value) => `'${value.replaceAll("'", "''")}'`;
14
+ /** A group of unknown size counts as large: hidden, rather than shown on a guess. */
15
+ const GROUP_SIZE = "coalesce(c.participants_count, (SELECT mc.listed_count FROM member_counts mc WHERE mc.chat_id = c.id " +
16
+ "ORDER BY mc.date DESC LIMIT 1))";
17
+ /** Each tie as the identities that have it. */
18
+ const tieIdentities = () => {
19
+ const crm = crmProviders();
20
+ 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}`,
24
+ // 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",
33
+ };
34
+ };
35
+ /**
36
+ * One row per person and reason they are shown: each tie (a merged person has every tie of every identity on them),
37
+ * the owner, a person added by hand (no identity, and not merged away), and a task's assignee, a merged-away one as
38
+ * the person they are now. Takes the merged assignees (`mergedAssignees`) as its one parameter.
39
+ */
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})`),
42
+ "SELECT entity_id, 'crm' FROM records WHERE entity_type = 'person' AND deleted_at IS NULL AND entity_id IS NOT NULL",
43
+ "SELECT id, 'owner' FROM persons WHERE owner = 1",
44
+ "SELECT p.id, 'added' FROM persons p WHERE NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) " +
45
+ `AND NOT ${mergedAwaySql("p")}`,
46
+ "SELECT coalesce(json_extract(m.value, '$[1]'), a.assignee_id), 'task' FROM task_assignments a " +
47
+ "JOIN tasks t ON t.id = a.task_id AND t.deleted_at IS NULL " +
48
+ "LEFT JOIN json_each(?) m ON json_extract(m.value, '$[0]') = a.assignee_id WHERE a.assignee_type = 'person'",
49
+ ].join(" UNION ALL ");
50
+ const ORDER = [...ALWAYS_SHOWN, ...PERSON_TIES];
51
+ /**
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`).
54
+ */
55
+ export const shownReasons = (database) => {
56
+ const found = new Map();
57
+ for (const row of database
58
+ .prepare(`SELECT DISTINCT person, tie FROM (${reasonRows()})`)
59
+ .all(mergedAssignees(database))) {
60
+ const person = Number(row.person);
61
+ const reasons = found.get(person) ?? new Set();
62
+ reasons.add(row.tie);
63
+ found.set(person, reasons);
64
+ }
65
+ return new Map([...found].map(([person, reasons]) => [person, ORDER.filter((one) => reasons.has(one))]));
66
+ };
@@ -1603,6 +1603,22 @@ export declare const accountIdentities: import("drizzle-orm/sqlite-core").SQLite
1603
1603
  identity: undefined;
1604
1604
  generated: undefined;
1605
1605
  }, {}>;
1606
+ addressBook: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1607
+ name: string;
1608
+ tableName: "account_identities";
1609
+ dataType: "number int53";
1610
+ data: number;
1611
+ driverParam: number;
1612
+ notNull: false;
1613
+ hasDefault: false;
1614
+ isPrimaryKey: false;
1615
+ isAutoincrement: false;
1616
+ hasRuntimeDefault: false;
1617
+ enumValues: undefined;
1618
+ baseColumn: never;
1619
+ identity: undefined;
1620
+ generated: undefined;
1621
+ }, {}>;
1606
1622
  };
1607
1623
  dialect: 'sqlite';
1608
1624
  isAlias: false;
@@ -168,9 +168,12 @@ export const accountIdentities = sqliteTable("account_identities", {
168
168
  mailScoredAt: integer("mail_scored_at"),
169
169
  /** 1 when search ranks this sender's mail lower: signs of fraud, not one of the owner's own. */
170
170
  mailDemoted: integer("mail_demoted"),
171
+ /** 1 while in this account's address book: a tie to the owner. */
172
+ addressBook: integer("address_book"),
171
173
  }, (table) => [
172
174
  primaryKey({ columns: [table.accountId, table.identityId] }),
173
175
  index("account_identities_by_identity_id").on(table.identityId),
176
+ index("account_identities_in_address_book").on(table.identityId).where(sql `address_book = 1`),
174
177
  ]);
175
178
  export const aliases = sqliteTable("aliases", {
176
179
  id: integer("id").primaryKey(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.622.0",
3
+ "version": "0.623.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": 60,
18
+ "speaks": 61,
19
19
  "minCompatible": 56
20
20
  }
21
21
  },