@wirecat/cli-core 0.623.0 → 0.625.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 (47) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/dist/background/backfill.d.ts +1 -1
  3. package/dist/background/backfill.js +1 -1
  4. package/dist/background/daily-archive-timer.d.ts +1 -1
  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 -20
  8. package/dist/background/schedules.js +8 -162
  9. package/dist/background/timers.d.ts +19 -0
  10. package/dist/background/timers.js +175 -0
  11. package/dist/background/when.d.ts +28 -7
  12. package/dist/background/when.js +55 -11
  13. package/dist/calendar/prepare.d.ts +14 -0
  14. package/dist/cli/app-doctor-command.js +2 -1
  15. package/dist/cli/envelope.d.ts +28 -0
  16. package/dist/cli/index.d.ts +3 -2
  17. package/dist/cli/index.js +3 -2
  18. package/dist/cli/schedule/schedule-command.d.ts +100 -3
  19. package/dist/cli/schedule/schedule-command.js +276 -118
  20. package/dist/cli/templates-command.js +45 -20
  21. package/dist/domain/display-names.d.ts +5 -2
  22. package/dist/domain/display-names.js +13 -4
  23. package/dist/domain/person-kinds.d.ts +9 -0
  24. package/dist/domain/person-kinds.js +67 -0
  25. package/dist/domain/records-table.d.ts +61 -0
  26. package/dist/domain/records-table.js +382 -0
  27. package/dist/entities/index.d.ts +2 -1
  28. package/dist/entities/list-results.d.ts +2 -0
  29. package/dist/entities/list-results.js +2 -0
  30. package/dist/entities/template.d.ts +1 -1
  31. package/dist/entities/template.js +1 -1
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.js +1 -0
  34. package/dist/mcp/surface.js +23 -2
  35. package/dist/meetings/mcp/index.d.ts +15 -15
  36. package/dist/services/index.d.ts +1 -1
  37. package/dist/services/index.js +1 -1
  38. package/dist/services/metadata.d.ts +1 -1
  39. package/dist/services/search-harder.d.ts +6 -1
  40. package/dist/services/search-harder.js +9 -2
  41. package/dist/store/index.d.ts +2 -1
  42. package/dist/store/index.js +2 -0
  43. package/dist/store/people.d.ts +4 -3
  44. package/dist/store/sqlite/people-list.d.ts +23 -8
  45. package/dist/store/sqlite/people-list.js +189 -65
  46. package/package.json +2 -2
  47. package/parity.json +29 -0
@@ -1,9 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { displayName, nameKey } from "../../domain/display-names.js";
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";
3
5
  import { fold } from "../normalize.js";
4
6
  import { mergedAwaySql } from "./merged-persons.js";
5
- import { shownReasons } from "./person-ties.js";
7
+ import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
6
8
  import { mergedAssignees } from "./task-board.js";
9
+ export const PEOPLE_SORTS = ["interactions", "recent", "name", "tasks"];
7
10
  const MIN_QUERY = 3;
8
11
  const ftsPhrase = (text) => `"${text.replaceAll('"', '""')}"`;
9
12
  const matching = (query) => {
@@ -18,73 +21,185 @@ const matching = (query) => {
18
21
  params: [ftsPhrase(text), `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`],
19
22
  };
20
23
  };
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 " +
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 " +
30
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 " +
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
- };
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;
48
83
  };
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];
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: "stranger", 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
+ };
61
153
  });
62
154
  };
63
- /** People by name or by task count, the owner first; by default only those with a tie to the owner. */
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. */
64
167
  export const listPeople = (database, options) => {
65
- const { all = false, sort = "tasks", limit, offset = 0 } = 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}"`);
66
173
  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);
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));
83
198
  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,
199
+ items: withLastContact(database, sorted.slice(offset, offset + limit), recent),
200
+ hasMore: sorted.length > offset + limit,
201
+ total: sorted.length,
202
+ counts,
88
203
  };
89
204
  };
90
205
  const words = (key) => (key === null ? [] : key.split(" "));
@@ -144,8 +259,17 @@ export const similarPeople = (database, typed, limit) => {
144
259
  a.person - b.person)
145
260
  .slice(0, limit);
146
261
  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,
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,
150
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 }));
151
275
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.623.0",
3
+ "version": "0.625.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",
@@ -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": {