@wirecat/cli-core 0.622.0 → 0.624.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 (69) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/dist/background/backfill.d.ts +1 -1
  3. package/dist/background/backfill.js +1 -1
  4. package/dist/background/budget.d.ts +2 -0
  5. package/dist/background/report/stored-templates.d.ts +21 -3
  6. package/dist/background/report/stored-templates.js +34 -6
  7. package/dist/background/schedules.d.ts +10 -27
  8. package/dist/background/schedules.js +8 -167
  9. package/dist/background/timers.d.ts +19 -0
  10. package/dist/background/timers.js +175 -0
  11. package/dist/background/when.d.ts +49 -0
  12. package/dist/background/when.js +84 -0
  13. package/dist/calendar/mcp/index.d.ts +12 -12
  14. package/dist/calendar/prepare.d.ts +14 -0
  15. package/dist/cli/app-doctor-command.js +2 -1
  16. package/dist/cli/envelope.d.ts +28 -0
  17. package/dist/cli/index.d.ts +3 -2
  18. package/dist/cli/index.js +3 -2
  19. package/dist/cli/messenger/messages-search-command.js +4 -0
  20. package/dist/cli/program.js +6 -3
  21. package/dist/cli/schedule/schedule-command.d.ts +100 -3
  22. package/dist/cli/schedule/schedule-command.js +277 -113
  23. package/dist/cli/templates-command.js +45 -20
  24. package/dist/domain/display-names.d.ts +19 -0
  25. package/dist/domain/display-names.js +59 -0
  26. package/dist/domain/person-kinds.d.ts +9 -0
  27. package/dist/domain/person-kinds.js +67 -0
  28. package/dist/entities/index.d.ts +2 -1
  29. package/dist/entities/list-results.d.ts +2 -0
  30. package/dist/entities/list-results.js +2 -0
  31. package/dist/entities/template.d.ts +1 -1
  32. package/dist/entities/template.js +1 -1
  33. package/dist/errors/reasons.js +1 -0
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/mcp/surface.js +23 -2
  37. package/dist/search/lucene/resolved.d.ts +1 -0
  38. package/dist/search/lucene/types.d.ts +8 -0
  39. package/dist/search/lucene/types.js +7 -0
  40. package/dist/services/index.d.ts +1 -1
  41. package/dist/services/index.js +1 -1
  42. package/dist/services/messages-combined.js +3 -2
  43. package/dist/services/messages-discovery.js +3 -2
  44. package/dist/services/messages-search.js +1 -0
  45. package/dist/services/messages.d.ts +2 -0
  46. package/dist/services/people.js +1 -1
  47. package/dist/services/search-harder.d.ts +6 -1
  48. package/dist/services/search-harder.js +9 -2
  49. package/dist/store/identity-links.d.ts +3 -3
  50. package/dist/store/identity-links.js +3 -3
  51. package/dist/store/index.d.ts +3 -0
  52. package/dist/store/index.js +3 -0
  53. package/dist/store/people.d.ts +21 -2
  54. package/dist/store/people.js +35 -15
  55. package/dist/store/sqlite/lucene.js +12 -11
  56. package/dist/store/sqlite/manifest.js +1 -0
  57. package/dist/store/sqlite/migrations.generated.js +7 -0
  58. package/dist/store/sqlite/name-traces.d.ts +17 -0
  59. package/dist/store/sqlite/name-traces.js +112 -0
  60. package/dist/store/sqlite/notes.js +6 -3
  61. package/dist/store/sqlite/people-list.d.ts +59 -0
  62. package/dist/store/sqlite/people-list.js +275 -0
  63. package/dist/store/sqlite/person-match-scan.js +33 -0
  64. package/dist/store/sqlite/person-ties.d.ts +14 -0
  65. package/dist/store/sqlite/person-ties.js +66 -0
  66. package/dist/store/sqlite/schema.d.ts +16 -0
  67. package/dist/store/sqlite/schema.js +3 -0
  68. package/package.json +3 -3
  69. package/parity.json +29 -0
@@ -0,0 +1,275 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
3
+ import { displayName, isReadable, nameKey } from "../../domain/display-names.js";
4
+ import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
5
+ import { fold } from "../normalize.js";
6
+ import { mergedAwaySql } from "./merged-persons.js";
7
+ import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
8
+ import { mergedAssignees } from "./task-board.js";
9
+ export const PEOPLE_SORTS = ["interactions", "recent", "name", "tasks"];
10
+ const MIN_QUERY = 3;
11
+ const ftsPhrase = (text) => `"${text.replaceAll('"', '""')}"`;
12
+ const matching = (query) => {
13
+ if (query === undefined)
14
+ return { sql: "", params: [] };
15
+ const text = query.trim();
16
+ if (text.length < MIN_QUERY)
17
+ throw new CliError("validation_error", `a people search takes at least ${MIN_QUERY} characters, got "${query}"`);
18
+ return {
19
+ sql: " AND (p.id IN (SELECT l.person_id FROM identity_links l WHERE l.identity_id IN " +
20
+ "(SELECT rowid FROM identities_fts WHERE identities_fts MATCH ?)) OR p.name LIKE ? ESCAPE '\\')",
21
+ params: [ftsPhrase(text), `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`],
22
+ };
23
+ };
24
+ const TASK_COUNTS = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)) " +
25
+ "SELECT coalesce(m.now, a.assignee_id) AS person, count(DISTINCT t.id) AS n FROM task_assignments a " +
26
+ "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 " +
27
+ "WHERE a.assignee_type = 'person' GROUP BY 1";
28
+ const IN_SCOPE = (scope, column) => scope === "all" ? "1" : `${column} IN (SELECT value FROM json_each(?))`;
29
+ const scopeParams = (scope) => (scope === "all" ? [] : [JSON.stringify(scope)]);
30
+ const SCOPED_IDENTITIES = (scope) => `SELECT identity_id FROM identity_links WHERE ${IN_SCOPE(scope, "person_id")}`;
31
+ /** Counted over `messages_by_sender_identity_id` alone: no message row is read. */
32
+ const MESSAGE_COUNTS = (scope) => "SELECT l.person_id AS person, sum(x.n) AS n FROM (SELECT sender_identity_id AS identity, count(*) AS n FROM " +
33
+ `messages WHERE sender_identity_id ${scope === "all" ? "IS NOT NULL" : `IN (${SCOPED_IDENTITIES(scope)})`} ` +
34
+ "GROUP BY 1) x JOIN identity_links l ON l.identity_id = x.identity GROUP BY 1";
35
+ const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum(EXISTS (SELECT 1 FROM email_mailboxes m " +
36
+ "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
37
+ "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
38
+ `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`;
39
+ const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.username, i.phone, i.email, i.bot " +
40
+ `FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE ${IN_SCOPE(scope, "l.person_id")} ORDER BY i.id`;
41
+ /** Few identities have these; one pass each beats a lookup per identity. */
42
+ const NEVER_REPLIED = "SELECT identity_id FROM account_identities WHERE mail_signals LIKE '%bulk_never_replied%'";
43
+ const OWNED = "SELECT identity_id FROM organization_identities";
44
+ const LAST_CONTACTS = (identities) => `SELECT l.person_id AS person, max(t) AS at FROM (` +
45
+ `SELECT sender_identity_id AS identity, max(sent_at) AS t FROM messages WHERE sender_identity_id IN (${identities}) ` +
46
+ "AND deleted_at IS NULL GROUP BY 1 UNION ALL " +
47
+ `SELECT from_identity_id, max(coalesce(sent_at, received_at)) FROM emails WHERE from_identity_id IN (${identities}) ` +
48
+ "AND deleted_at IS NULL GROUP BY 1 UNION ALL " +
49
+ `SELECT identity_id, max(last_messaged_at) FROM account_identities WHERE identity_id IN (${identities}) GROUP BY 1` +
50
+ ") x JOIN identity_links l ON l.identity_id = x.identity GROUP BY 1";
51
+ const factsOf = (database, scope) => {
52
+ const facts = new Map();
53
+ const text = (value) => (value == null || value === "" ? null : String(value));
54
+ const ids = (sql) => new Set(database
55
+ .prepare(sql)
56
+ .all()
57
+ .map((row) => Number(row.identity_id)));
58
+ const neverReplied = ids(NEVER_REPLIED);
59
+ const owned = ids(OWNED);
60
+ for (const row of database.prepare(IDENTITIES(scope)).all(...scopeParams(scope))) {
61
+ const person = Number(row.person);
62
+ const one = facts.get(person) ?? {
63
+ username: null,
64
+ phone: null,
65
+ email: null,
66
+ emails: [],
67
+ bot: false,
68
+ neverReplied: false,
69
+ organization: false,
70
+ };
71
+ const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
72
+ one.username ??= text(row.username);
73
+ one.phone ??= text(row.phone) ?? (row.provider === "phone" ? text(row.external_id) : null);
74
+ one.email ??= email;
75
+ if (email !== null)
76
+ one.emails.push(email);
77
+ one.bot ||= Number(row.bot) === 1;
78
+ one.neverReplied ||= neverReplied.has(Number(row.id));
79
+ one.organization ||= owned.has(Number(row.id));
80
+ facts.set(person, one);
81
+ }
82
+ return facts;
83
+ };
84
+ const countsOf = (database, sql, ...params) => new Map(database
85
+ .prepare(sql)
86
+ .all(...params)
87
+ .map((row) => [Number(row.person), Number(row.n)]));
88
+ const lastContacts = (database, scope) => new Map(database
89
+ .prepare(LAST_CONTACTS(SCOPED_IDENTITIES(scope)))
90
+ .all(...scopeParams(scope), ...scopeParams(scope), ...scopeParams(scope))
91
+ .filter((row) => row.at != null)
92
+ .map((row) => [Number(row.person), Number(row.at)]));
93
+ /** One misfiled letter is no newsletter. */
94
+ const BULK_MIN = 3;
95
+ /** The first rule that holds; the list's contract in the people-clients-digests plan names the same order. */
96
+ const kindOf = (shown, facts, ties, mail) => {
97
+ const always = ties.filter((tie) => ALWAYS_SHOWN.includes(tie));
98
+ if (always.length > 0)
99
+ return { kind: "person", signals: ties };
100
+ const emails = facts?.emails ?? [];
101
+ const automated = [
102
+ ...(facts?.bot ? ["bot"] : []),
103
+ ...(emails.some(isNoReplyAddress) ? ["no-reply"] : []),
104
+ ...(mail !== undefined && mail.n >= BULK_MIN && mail.bulk * 2 > mail.n ? ["bulk-mail"] : []),
105
+ ...(facts?.neverReplied ? ["bulk-never-replied"] : []),
106
+ ...(isAutomatedName(shown) ? ["automated-name"] : []),
107
+ ];
108
+ if (automated.length > 0)
109
+ return { kind: "automated", signals: automated };
110
+ const organization = [
111
+ ...(facts?.organization ? ["organization"] : []),
112
+ ...(emails.length > 0 && emails.every(isRoleAddress) ? ["role-address"] : []),
113
+ ...(isCompanyName(shown) ? ["company-name"] : []),
114
+ ];
115
+ if (organization.length > 0)
116
+ return { kind: "organization", signals: organization };
117
+ if (!isReadable(shown))
118
+ return { kind: "unsorted", signals: ["no-name"] };
119
+ if (ties.length === 0)
120
+ return { kind: "unsorted", signals: ["no-tie"] };
121
+ return { kind: "person", signals: ties };
122
+ };
123
+ /** Each person with their kind, contact and counts; the last contact is added for the page alone. */
124
+ const classified = (database, people, scope, reasons = shownReasons(database)) => {
125
+ const facts = factsOf(database, scope);
126
+ const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
127
+ const messages = countsOf(database, MESSAGE_COUNTS(scope), ...scopeParams(scope));
128
+ const mail = new Map(database
129
+ .prepare(MAIL_COUNTS(scope))
130
+ .all(...scopeParams(scope))
131
+ .map((row) => [Number(row.person), { n: Number(row.n), bulk: Number(row.bulk) }]));
132
+ return people.map(({ id, name, owner }) => {
133
+ const own = facts.get(id);
134
+ const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
135
+ const shown = displayName(name, contact);
136
+ const ties = reasons.get(id) ?? [];
137
+ const { kind, signals } = kindOf(shown, own, ties, mail.get(id));
138
+ return {
139
+ id,
140
+ nameOrder: nameOrderOf(shown),
141
+ person: `person:${id}`,
142
+ name,
143
+ displayName: shown,
144
+ kind,
145
+ kindSignals: signals,
146
+ owner,
147
+ tasks: tasks.get(id) ?? 0,
148
+ contact: contact.phone ?? contact.email ?? (contact.username === null ? null : `@${contact.username.replace(/^@/, "")}`),
149
+ ...contact,
150
+ messagesFrom: (messages.get(id) ?? 0) + (mail.get(id)?.n ?? 0),
151
+ ties,
152
+ };
153
+ });
154
+ };
155
+ const withLastContact = (database, people, known) => {
156
+ const at = known ??
157
+ lastContacts(database, people.map(({ id }) => id));
158
+ return people.map(({ id, nameOrder: _, ...person }) => {
159
+ const time = at.get(id);
160
+ return { ...person, lastContact: time === undefined ? null : new Date(time).toISOString() };
161
+ });
162
+ };
163
+ /** Sorted as read, case and accents aside; a name with nothing to read goes last. */
164
+ const nameOrderOf = (shown) => `${isReadable(shown) ? 0 : 1}${fold(shown ?? "")}`;
165
+ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOrder ? 1 : a.id - b.id;
166
+ /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
167
+ export const listPeople = (database, options) => {
168
+ const { kind = "person", sort = "interactions", limit, offset = 0 } = options;
169
+ if (kind !== "all" && !PERSON_KINDS.includes(kind))
170
+ throw new CliError("validation_error", `a person's kind is one of ${PERSON_KINDS.join(", ")} or all, got "${kind}"`);
171
+ if (!PEOPLE_SORTS.includes(sort))
172
+ throw new CliError("validation_error", `people sort by ${PEOPLE_SORTS.join(", ")}, got "${sort}"`);
173
+ const filter = matching(options.query);
174
+ const candidates = database
175
+ .prepare(`SELECT p.id, p.name, p.owner FROM persons p WHERE NOT ${mergedAwaySql("p")}${filter.sql}`)
176
+ .all(...filter.params)
177
+ .map((row) => ({
178
+ id: Number(row.id),
179
+ name: row.name == null ? null : String(row.name),
180
+ owner: Number(row.owner) === 1,
181
+ }));
182
+ // A search reads only the people it found; a whole list reads everyone once rather than per person.
183
+ const everyone = classified(database, candidates, options.query === undefined ? "all" : candidates.map(({ id }) => id));
184
+ const counts = Object.fromEntries(PERSON_KINDS.map((one) => [one, 0]));
185
+ for (const person of everyone)
186
+ counts[person.kind] += 1;
187
+ const chosen = kind === "all" ? everyone : everyone.filter((person) => person.kind === kind);
188
+ // The newest contact of every person reads every message; only this order needs it.
189
+ const recent = sort === "recent" ? lastContacts(database, "all") : undefined;
190
+ const order = sort === "name"
191
+ ? byName
192
+ : sort === "tasks"
193
+ ? (a, b) => b.tasks - a.tasks || byName(a, b)
194
+ : sort === "recent"
195
+ ? (a, b) => (recent?.get(b.id) ?? 0) - (recent?.get(a.id) ?? 0) || byName(a, b)
196
+ : (a, b) => b.messagesFrom - a.messagesFrom || byName(a, b);
197
+ const sorted = chosen.sort((a, b) => Number(b.owner) - Number(a.owner) || order(a, b));
198
+ return {
199
+ items: withLastContact(database, sorted.slice(offset, offset + limit), recent),
200
+ hasMore: sorted.length > offset + limit,
201
+ total: sorted.length,
202
+ counts,
203
+ };
204
+ };
205
+ const words = (key) => (key === null ? [] : key.split(" "));
206
+ /** Every typed word starts a word of the name, in any order: «iv pet» finds Petrov Ivan. */
207
+ const startsEach = (typed, name) => {
208
+ const own = words(nameKey(name));
209
+ return typed.every((word) => own.some((one) => one.startsWith(word)));
210
+ };
211
+ /**
212
+ * People whose name, or a name of one of their identities, has a word starting with each typed word, for a form
213
+ * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
214
+ */
215
+ export const similarPeople = (database, typed, limit) => {
216
+ const key = nameKey(typed);
217
+ const wanted = words(key);
218
+ const longest = wanted.reduce((a, b) => (b.length > a.length ? b : a), "");
219
+ if (longest === "")
220
+ return [];
221
+ const named = new Map();
222
+ const note = (person, name) => {
223
+ if (typeof name === "string")
224
+ named.set(person, [...(named.get(person) ?? []), name]);
225
+ };
226
+ // A person added by hand has no identity to search; there are few, and SQLite folds only ASCII case.
227
+ for (const row of database
228
+ .prepare("SELECT p.id, p.name FROM persons p WHERE p.name IS NOT NULL " +
229
+ `AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) AND NOT ${mergedAwaySql("p")}`)
230
+ .all())
231
+ note(Number(row.id), row.name);
232
+ const identityRows = longest.length >= MIN_QUERY
233
+ ? database
234
+ .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities_fts f JOIN identities i ON i.id = f.rowid " +
235
+ "JOIN identity_links l ON l.identity_id = i.id WHERE identities_fts MATCH ?")
236
+ .all(ftsPhrase(longest))
237
+ : database
238
+ .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities i " +
239
+ "JOIN identity_links l ON l.identity_id = i.id WHERE i.name_folded LIKE ? ESCAPE '\\'")
240
+ .all(`%${fold(longest).replace(/[\\%_]/g, (c) => `\\${c}`)}%`);
241
+ for (const row of identityRows) {
242
+ note(Number(row.person), row.name);
243
+ note(Number(row.person), row.username);
244
+ }
245
+ const found = [...named]
246
+ .filter(([, names]) => names.some((name) => startsEach(wanted, name)))
247
+ .map(([person, names]) => ({
248
+ person,
249
+ name: names[0] ?? "",
250
+ same: names.some((name) => nameKey(name) === key),
251
+ }));
252
+ if (found.length === 0)
253
+ return [];
254
+ const ties = shownReasons(database);
255
+ const chosen = found
256
+ .sort((a, b) => Number(b.same) - Number(a.same) ||
257
+ Number(ties.has(b.person)) - Number(ties.has(a.person)) ||
258
+ a.name.localeCompare(b.name) ||
259
+ a.person - b.person)
260
+ .slice(0, limit);
261
+ const sameName = new Map(chosen.map(({ person, same }) => [person, same]));
262
+ const people = database
263
+ .prepare("SELECT id, name, owner FROM persons WHERE id IN (SELECT value FROM json_each(?))")
264
+ .all(JSON.stringify([...sameName.keys()]))
265
+ .map((row) => ({
266
+ id: Number(row.id),
267
+ name: row.name == null ? null : String(row.name),
268
+ owner: Number(row.owner) === 1,
269
+ }));
270
+ const byId = new Map(people.map((person) => [person.id, person]));
271
+ const ordered = [...sameName.keys()].flatMap((id) => byId.get(id) ?? []);
272
+ const rows = classified(database, ordered, [...sameName.keys()], ties);
273
+ const same = rows.map(({ id }) => sameName.get(id) === true);
274
+ return withLastContact(database, rows).map((person, at) => ({ ...person, sameName: same[at] === true }));
275
+ };
@@ -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.624.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
  },
@@ -278,7 +278,7 @@
278
278
  "@types/node": "^22.20.5",
279
279
  "@types/pngjs": "6.0.5",
280
280
  "@vitest/coverage-v8": "^5.0.5",
281
- "@wirecat/cli-base": "0.93.0",
281
+ "@wirecat/cli-base": "0.94.0",
282
282
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
283
283
  "ajv": "8.17.1",
284
284
  "commander": "15.0.0",
package/parity.json CHANGED
@@ -687,6 +687,9 @@
687
687
  "--no-mentions-me": {
688
688
  "meaning": "do not require a mention of you or a reply to you"
689
689
  },
690
+ "--no-notify": {
691
+ "meaning": "keep the result here: send it along none of its routes"
692
+ },
690
693
  "--no-preview": {
691
694
  "meaning": "no preview card for a link in the text"
692
695
  },
@@ -4111,16 +4114,42 @@
4111
4114
  "wa": "wa backlog: mount the shared schedule command"
4112
4115
  }
4113
4116
  },
4117
+ "schedule pause": {
4118
+ "in": ["max", "tg"],
4119
+ "planned": {
4120
+ "wa": "wa backlog: mount the shared schedule command"
4121
+ }
4122
+ },
4114
4123
  "schedule remove": {
4115
4124
  "in": ["max", "tg"],
4116
4125
  "planned": {
4117
4126
  "wa": "wa backlog: mount the shared schedule command"
4118
4127
  }
4119
4128
  },
4129
+ "schedule resume": {
4130
+ "in": ["max", "tg"],
4131
+ "planned": {
4132
+ "wa": "wa backlog: mount the shared schedule command"
4133
+ }
4134
+ },
4120
4135
  "schedule run": {
4121
4136
  "in": ["max", "tg"],
4122
4137
  "planned": {
4123
4138
  "wa": "wa backlog: mount the shared schedule command"
4139
+ },
4140
+ "options": {
4141
+ "--deliver-to": {
4142
+ "in": ["max", "tg"],
4143
+ "planned": {
4144
+ "wa": "wa backlog: mount the shared schedule command"
4145
+ }
4146
+ },
4147
+ "--no-notify": {
4148
+ "in": ["max", "tg"],
4149
+ "planned": {
4150
+ "wa": "wa backlog: mount the shared schedule command"
4151
+ }
4152
+ }
4124
4153
  }
4125
4154
  },
4126
4155
  "search": {