@wirecat/cli-core 0.623.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 (42) hide show
  1. package/CHANGELOG.md +65 -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/entities/index.d.ts +2 -1
  26. package/dist/entities/list-results.d.ts +2 -0
  27. package/dist/entities/list-results.js +2 -0
  28. package/dist/entities/template.d.ts +1 -1
  29. package/dist/entities/template.js +1 -1
  30. package/dist/mcp/surface.js +23 -2
  31. package/dist/meetings/mcp/index.d.ts +15 -15
  32. package/dist/services/index.d.ts +1 -1
  33. package/dist/services/index.js +1 -1
  34. package/dist/services/search-harder.d.ts +6 -1
  35. package/dist/services/search-harder.js +9 -2
  36. package/dist/store/index.d.ts +2 -1
  37. package/dist/store/index.js +2 -0
  38. package/dist/store/people.d.ts +3 -3
  39. package/dist/store/sqlite/people-list.d.ts +23 -8
  40. package/dist/store/sqlite/people-list.js +189 -65
  41. package/package.json +2 -2
  42. package/parity.json +29 -0
@@ -47,6 +47,8 @@ export const HARDER_REASON_IDS = [
47
47
  "harder.bad-reply",
48
48
  "harder.error",
49
49
  ];
50
+ /** The result as the answer's `meta.ranking`: the same facts, with the reason as its code alone. */
51
+ export const harderRanking = ({ reason: _reason, ...rest }) => rest;
50
52
  // The search lab's prompt, word for word, except that the records travel as the gateway's untrusted data.
51
53
  const PROMPT = "Today is {as_of}. A person searches their own archive of messages, mails, notes, calendar entries and phone " +
52
54
  "records with the question below. Here are {n} candidate records, numbered, in the data.\n\n" +
@@ -185,7 +187,7 @@ const ask = async (access, options, request) => {
185
187
  model: access.model,
186
188
  ...(access.custom ? { base_url: access.endpoint } : {}),
187
189
  });
188
- return { text: answer.text, cost };
190
+ return { text: answer.text, cost, ...(answer.usage ? { usage: answer.usage } : {}) };
189
191
  }
190
192
  catch (error) {
191
193
  return { reason_id: reasonOf(error, limit.signal.aborted) };
@@ -241,7 +243,11 @@ export const reorderHarder = async (question, hits, { laterPage, access: given,
241
243
  picked = v.parse(Reply, jsonOf(answer.text)).records;
242
244
  }
243
245
  catch {
244
- return plain("harder.bad-reply", { ...sent, cost_usd: answer.cost });
246
+ return plain("harder.bad-reply", {
247
+ ...sent,
248
+ cost_usd: answer.cost,
249
+ ...(answer.usage ? { usage: answer.usage } : {}),
250
+ });
245
251
  }
246
252
  const first = [...new Set(picked.filter((i) => i >= 0 && i < candidates.length))];
247
253
  const chosen = new Set(first);
@@ -258,6 +264,7 @@ export const reorderHarder = async (question, hits, { laterPage, access: given,
258
264
  endpoint: access.endpoint,
259
265
  ...sent,
260
266
  cost_usd: answer.cost,
267
+ ...(answer.usage ? { usage: answer.usage } : {}),
261
268
  ms: Date.now() - started,
262
269
  },
263
270
  };
@@ -1,6 +1,7 @@
1
1
  export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
2
2
  export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
3
3
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
4
+ export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js";
4
5
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
5
6
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
6
7
  export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
@@ -77,7 +78,7 @@ export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder,
77
78
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
78
79
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
79
80
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
80
- export type { ListedPerson, PeopleList, PeopleListOptions, SimilarPerson } from "./sqlite/people-list.js";
81
+ export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
81
82
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
82
83
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
83
84
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -1,5 +1,6 @@
1
1
  export { BUSINESS_KINDS } from "../domain/business.js";
2
2
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
3
+ export { PERSON_KINDS } from "../domain/person-kinds.js";
3
4
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
4
5
  export { note } from "../entities/note.js";
5
6
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
@@ -38,6 +39,7 @@ export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
38
39
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
39
40
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
40
41
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
42
+ export { PEOPLE_SORTS, } from "./sqlite/people-list.js";
41
43
  export { mergeId, parseMergeId } from "./sqlite/person-merges.js";
42
44
  export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
43
45
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
@@ -104,9 +104,9 @@ export interface PeopleStore extends AccountPeople {
104
104
  name: string;
105
105
  }): Promise<PersonRecord>;
106
106
  /**
107
- * People with their shown name, contact and ties to the owner, a page at a time. By default only those with a tie
108
- * (a one-to-one chat, a small group, mail the owner wrote, a meeting, a CRM, the address book), the owner, people
109
- * added by hand and people assigned a task; `all` adds the rest.
107
+ * People of one kind with their shown name, contact, interactions and ties, a page at a time. `person` (the default)
108
+ * is the owner, people added by hand, task assignees, and named people with a tie (a one-to-one chat, a small group,
109
+ * mail the owner wrote, a meeting, a CRM, the address book); `automated`, `organization` and `unsorted` hold the rest.
110
110
  */
111
111
  list(options: PeopleListOptions): Promise<PeopleList>;
112
112
  /** People whose names start like the typed one, the same name first: for a form that adds a person. */
@@ -1,12 +1,18 @@
1
+ import { type KindSignal, type PersonKind } from "../../domain/person-kinds.js";
1
2
  import type { CacheDatabase } from "../driver.js";
2
3
  import { type ShownBecause } from "./person-ties.js";
4
+ export declare const PEOPLE_SORTS: readonly ["interactions", "recent", "name", "tasks"];
5
+ export type PeopleSort = (typeof PEOPLE_SORTS)[number];
3
6
  export interface PeopleListOptions {
4
7
  /** Part of a name or username, at least 3 characters. */
5
8
  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";
9
+ /** One kind, `person` by default, or `all`. */
10
+ kind?: PersonKind | "all";
11
+ /**
12
+ * The owner first, then `interactions`: most messages and mail from them; `recent`: newest contact; `name`; `tasks`:
13
+ * how many tasks name them. Equal rows by name.
14
+ */
15
+ sort?: PeopleSort;
10
16
  limit: number;
11
17
  offset?: number;
12
18
  }
@@ -15,27 +21,36 @@ export interface ListedPerson {
15
21
  /** As stored; `displayName` is what to show. */
16
22
  name: string | null;
17
23
  displayName: string | null;
24
+ kind: PersonKind;
25
+ /** What decided the kind: the ties for a `person`, else the signal. */
26
+ kindSignals: (ShownBecause | KindSignal)[];
18
27
  owner: boolean;
19
28
  tasks: number;
29
+ /** The one to show beside the name: the phone, else the email, else `@username`. */
30
+ contact: string | null;
20
31
  username: string | null;
21
32
  phone: string | null;
22
33
  email: string | null;
34
+ /** Messages and mail this person sent, every account together. */
35
+ messagesFrom: number;
36
+ /** The newest of their messages, their mail and their one-to-one chat's last message, as ISO time. */
37
+ lastContact: string | null;
23
38
  /** Why they are shown; empty for someone hidden by default. */
24
39
  ties: ShownBecause[];
25
40
  }
26
41
  export interface PeopleList {
27
42
  items: ListedPerson[];
28
43
  hasMore: boolean;
29
- /** Everyone the list holds over every page. */
44
+ /** The people of the kind asked over every page. */
30
45
  total: number;
31
- /** The people matching that have no tie to the owner, shown only with `all`. */
32
- hidden: number;
46
+ /** How many of each kind match the query. */
47
+ counts: Record<PersonKind, number>;
33
48
  }
34
49
  export interface SimilarPerson extends ListedPerson {
35
50
  /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
36
51
  sameName: boolean;
37
52
  }
38
- /** People by name or by task count, the owner first; by default only those with a tie to the owner. */
53
+ /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
39
54
  export declare const listPeople: (database: CacheDatabase, options: PeopleListOptions) => PeopleList;
40
55
  /**
41
56
  * People whose name, or a name of one of their identities, has a word starting with each typed word, for a form
@@ -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: "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
+ };
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.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",
@@ -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": {