@wirecat/cli-core 0.628.0 → 0.629.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,31 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.629.0 — 10.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`people.counts(query?)` gives how many people each kind holds in one grouped query.** People's filter tabs
13
+ needed one `people.list` call for each kind, and each call took seconds. Now they take one call of about 5 ms on
14
+ 113,000 people. It gives the same numbers as `list`'s `counts`.
15
+
16
+ ### Fixed
17
+
18
+ - **`people.list` costs what the page asks for (store version 62).** Each person's kind, name order, messages and mail
19
+ sent, task count and newest contact are kept on `persons`. Triggers clear them when anything they are made from
20
+ changes, and the next list works out only the cleared people. The list then filters, counts, sorts and pages in SQL.
21
+ It works out ties, signals and contacts only for the rows it returns. On a synthetic store of 113,000 people a first
22
+ page drops from 0.7 s to about 40 ms, a kind tab from about 1 s to 45 ms, and the order by newest contact from 2.4 s
23
+ to about 50 ms. The first list after a sync of 10,000 messages from 2,000 senders takes about 0.15 s
24
+ ([cli-testing `performance/memo/people-list`](https://github.com/WireCatLabs/cli-testing/tree/main/performance/memo/people-list)).
25
+ The answers are the same as before. The first list after the upgrade works out everyone once, which takes as long as
26
+ a list did before. A read-only open with anything left to work out answers from memory, as before.
27
+ - **Saving a chat's members leaves the rows of members who stayed alone.** It deleted and wrote again every row, which
28
+ would clear the stored kind of every member on each sync.
29
+ - **`people.linkProposals` pages in SQL when it lists everyone's proposals.** It read, parsed and resolved every link
30
+ proposal of every status before it took the page: 213 to 244 ms for 500 of 25,000 proposals, now 18 ms. memo's
31
+ `people review` reads it. A list for one person still reads them all, since merges decide whose a proposal is now.
32
+
8
33
  ## 0.628.0 — 10.11.2026
9
34
 
10
35
  ### Added
@@ -1,4 +1,5 @@
1
1
  import type { Contact, Id, Page, PersonAlias, Provider } from "../domain/models.js";
2
+ import type { PersonKind } from "../domain/person-kinds.js";
2
3
  import type { PeopleLookup } from "../resolve.js";
3
4
  import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
4
5
  import type { ContactFilter } from "./sqlite/identities.js";
@@ -110,6 +111,8 @@ export interface PeopleStore extends AccountPeople {
110
111
  * name, no tie) and `unsorted` (nothing to show as a name) hold the rest.
111
112
  */
112
113
  list(options: PeopleListOptions): Promise<PeopleList>;
114
+ /** How many people of each kind match a name or username, or the whole store: `list`'s `counts` without a page. */
115
+ counts(query?: string): Promise<Record<PersonKind, number>>;
113
116
  /** People whose names start like the typed one, the same name first: for a form that adds a person. */
114
117
  similar(name: string, options?: {
115
118
  limit?: number;
@@ -4,7 +4,7 @@ import { ownerPerson } from "./sqlite/actors.js";
4
4
  import * as identities from "./sqlite/identities.js";
5
5
  import * as identityProposals from "./sqlite/identity-proposals.js";
6
6
  import { linkToOwner } from "./sqlite/own-identities.js";
7
- import { listPeople, similarPeople, } from "./sqlite/people-list.js";
7
+ import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
8
8
  import * as personLinks from "./sqlite/person-links.js";
9
9
  import { RULE, scanMatches } from "./sqlite/person-match-scan.js";
10
10
  import * as personMerges from "./sqlite/person-merges.js";
@@ -125,6 +125,7 @@ export const peopleStoreOver = (context, keyed) => {
125
125
  linkProposals: async (filter) => identityProposals.identityLinkRows(context, filter),
126
126
  linkToOwner: async (identity) => linkToOwner(context, identity),
127
127
  list: async (options) => listPeople(database, options),
128
+ counts: async (query) => countPeople(database, query),
128
129
  similar: async (name, { limit = 8 } = {}) => similarPeople(database, name, limit),
129
130
  ties: async (people) => {
130
131
  const reasons = shownReasons(database);
@@ -41,6 +41,8 @@ export declare const upsertChat: (context: StoreContext, accountKey: number, cha
41
41
  export declare const raiseLastMessageAt: ({ orm }: StoreContext, chatKey: number, at: number) => void;
42
42
  /** Replaces who is in the chat, whole. */
43
43
  export declare const writeMembers: (context: StoreContext, key: AccountKey, accountKey: number, chatId: Id, memberIds: Id[]) => void;
44
+ /** Leaves the rows of members still there alone: a rewritten row clears their stored kind (store version 62). */
45
+ export declare const replaceMembers: ({ database }: StoreContext, chatKey: number, members: readonly number[], at: number) => void;
44
46
  export declare const members: ({ orm }: StoreContext, chatKey: number) => Member[];
45
47
  /** Takes the left mark off the chats `present` names; any other state is kept. Answers how many. */
46
48
  export declare const rejoin: ({ orm }: StoreContext, accountKey: number, present: Id[]) => number;
@@ -223,17 +223,17 @@ const metadataObject = (stored) => {
223
223
  /** Replaces who is in the chat, whole. */
224
224
  export const writeMembers = (context, key, accountKey, chatId, memberIds) => {
225
225
  const chatKey = chatPkFor(context, accountKey, chatId);
226
- context.orm.delete(chatMembers).where(eq(chatMembers.chatId, chatKey)).run();
227
- for (const id of new Set(memberIds)) {
228
- context.orm
229
- .insert(chatMembers)
230
- .values({
231
- chatId: chatKey,
232
- identityId: identityPk(context, accountKey, key.provider, id, null),
233
- createdAt: context.now(),
234
- })
235
- .run();
236
- }
226
+ const members = [...new Set(memberIds)].map((id) => identityPk(context, accountKey, key.provider, id, null));
227
+ replaceMembers(context, chatKey, members, context.now());
228
+ };
229
+ /** Leaves the rows of members still there alone: a rewritten row clears their stored kind (store version 62). */
230
+ export const replaceMembers = ({ database }, chatKey, members, at) => {
231
+ database
232
+ .prepare("DELETE FROM chat_members WHERE chat_id = ? AND identity_id NOT IN (SELECT value FROM json_each(?))")
233
+ .run(chatKey, JSON.stringify(members));
234
+ const add = database.prepare("INSERT OR IGNORE INTO chat_members (chat_id, identity_id, created_at) VALUES (?, ?, ?)");
235
+ for (const member of new Set(members))
236
+ add.run(chatKey, member, at);
237
237
  };
238
238
  export const members = ({ orm }, chatKey) => orm
239
239
  .select({ id: identities.externalId, name: identities.name, username: identities.username })
@@ -11,8 +11,11 @@ export interface LinkRow {
11
11
  export declare const pairOf: (a: number | string, b: number | string) => string;
12
12
  /** The people a proposal's identities are on now; merges since may have moved either side. */
13
13
  export declare const currentPairOf: (database: CacheDatabase, payload: IdentityLinkPayload) => [number, number] | undefined;
14
- /** The proposals that still say something: waiting for the owner, or turned down by them. */
15
- export declare const linkRows: (database: CacheDatabase, statuses?: readonly string[]) => LinkRow[];
14
+ /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
15
+ export declare const linkRows: (database: CacheDatabase, statuses?: readonly string[], page?: {
16
+ limit: number;
17
+ offset: number;
18
+ }) => LinkRow[];
16
19
  /**
17
20
  * What a proposal rests on: its signal and the two identities it names, in either order. The owner's rejection
18
21
  * holds against this evidence only (NEED-2444); a new signal or identity for the same people proposes them again.
@@ -22,11 +22,11 @@ export const currentPairOf = (database, payload) => {
22
22
  : personOf(database, pkOf(database, payload.with));
23
23
  return from === undefined || to === undefined ? undefined : [from, to];
24
24
  };
25
- /** The proposals that still say something: waiting for the owner, or turned down by them. */
26
- export const linkRows = (database, statuses = ["proposed", "rejected"]) => database
25
+ /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
26
+ export const linkRows = (database, statuses = ["proposed", "rejected"], page) => database
27
27
  .prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? " +
28
- "AND status IN (SELECT value FROM json_each(?)) ORDER BY id")
29
- .all(IDENTITY_LINK_KIND, JSON.stringify(statuses))
28
+ `AND status IN (SELECT value FROM json_each(?)) ORDER BY id${page === undefined ? "" : " DESC LIMIT ? OFFSET ?"}`)
29
+ .all(IDENTITY_LINK_KIND, JSON.stringify(statuses), ...(page === undefined ? [] : [page.limit, page.offset]))
30
30
  .map((row) => {
31
31
  const payload = JSON.parse(String(row.payload));
32
32
  return { id: String(row.id), status: String(row.status), payload, pair: currentPairOf(database, payload) };
@@ -206,11 +206,15 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
206
206
  throw new CliError("validation_error", "a list of link proposals takes 1–500 items");
207
207
  const asked = person === undefined ? undefined : currentPerson(context.database, Number(person));
208
208
  const operations = proposalOperationsOver(context);
209
- const rows = linkRows(context.database, ["proposed", "rejected", "approved", "executed", "failed"])
210
- .filter((row) => status === "all" || SHOWN[row.status] === status)
211
- .filter((row) => asked === undefined || (row.pair?.includes(asked) ?? false))
212
- .reverse();
213
- const items = rows.slice(offset, offset + limit).map((row) => {
209
+ const statuses = Object.keys(SHOWN).filter((one) => status === "all" || SHOWN[one] === status);
210
+ // Whose a proposal is now depends on merges since, so only a list for one person reads every proposal.
211
+ const rows = asked === undefined
212
+ ? linkRows(context.database, statuses, { limit: limit + 1, offset })
213
+ : linkRows(context.database, statuses)
214
+ .filter((row) => row.pair?.includes(asked) ?? false)
215
+ .reverse()
216
+ .slice(offset, offset + limit + 1);
217
+ const items = rows.slice(0, limit).map((row) => {
214
218
  const action = operations.get(row.id);
215
219
  const payload = row.payload;
216
220
  const [from, to] = row.pair ?? payload.persons.map(Number);
@@ -230,5 +234,5 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
230
234
  createdAt: action.createdAt,
231
235
  };
232
236
  });
233
- return { items, hasMore: rows.length > offset + limit };
237
+ return { items, hasMore: rows.length > limit };
234
238
  };
@@ -125,6 +125,8 @@ export const MANIFEST = [
125
125
  { name: "20261108165309_version-59-templates", version: 59, minCompatible: 56 },
126
126
  { name: "20261108190101_version-60-base-stages", version: 60, minCompatible: 56 },
127
127
  { name: "20261109170741_version-61-people-ties", version: 61, minCompatible: 56 },
128
+ { name: "20261110005159_version-62-person-kinds", version: 62, minCompatible: 56 },
129
+ { name: "20261110005200_version-62-person-kinds-triggers", version: 62, minCompatible: 56 },
128
130
  ];
129
131
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
130
132
  const migrations = [];
@@ -1231,5 +1231,65 @@ export const GENERATED = [
1231
1231
  "ALTER TABLE `account_identities` ADD `address_book` integer;",
1232
1232
  "CREATE INDEX `account_identities_in_address_book` ON `account_identities` (`identity_id`) WHERE address_book = 1;"
1233
1233
  ]
1234
+ },
1235
+ {
1236
+ "name": "20261110005159_version-62-person-kinds",
1237
+ "statements": [
1238
+ "ALTER TABLE `persons` ADD `kind` text;",
1239
+ "ALTER TABLE `persons` ADD `name_order` text;",
1240
+ "ALTER TABLE `persons` ADD `messages_from` integer;",
1241
+ "ALTER TABLE `persons` ADD `task_count` integer;",
1242
+ "ALTER TABLE `persons` ADD `last_contact` integer;",
1243
+ "CREATE INDEX `persons_by_kind` ON `persons` (`kind`);",
1244
+ "CREATE INDEX `persons_kind_to_work_out` ON `persons` (`id`) WHERE kind IS NULL;"
1245
+ ]
1246
+ },
1247
+ {
1248
+ "name": "20261110005200_version-62-person-kinds-triggers",
1249
+ "statements": [
1250
+ "CREATE TRIGGER person_kind_person_au AFTER UPDATE OF name, owner ON persons\nWHEN OLD.name IS NOT NEW.name OR OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id = NEW.id;\nEND;",
1251
+ "CREATE TRIGGER person_kind_link_ai AFTER INSERT ON identity_links BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (NEW.person_id);\nEND;",
1252
+ "CREATE TRIGGER person_kind_link_ad AFTER DELETE ON identity_links BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (OLD.person_id);\nEND;",
1253
+ "CREATE TRIGGER person_kind_link_au AFTER UPDATE OF person_id, identity_id ON identity_links\nWHEN OLD.person_id IS NOT NEW.person_id OR OLD.identity_id IS NOT NEW.identity_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (OLD.person_id, NEW.person_id);\nEND;",
1254
+ "CREATE TRIGGER person_kind_identity_au AFTER UPDATE OF provider, external_id, username, phone, email, bot ON identities\nWHEN OLD.provider IS NOT NEW.provider OR OLD.external_id IS NOT NEW.external_id OR OLD.username IS NOT NEW.username OR OLD.phone IS NOT NEW.phone OR OLD.email IS NOT NEW.email OR OLD.bot IS NOT NEW.bot BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.id);\nEND;",
1255
+ "CREATE TRIGGER person_kind_member_ai AFTER INSERT ON chat_members BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1256
+ "CREATE TRIGGER person_kind_member_ad AFTER DELETE ON chat_members BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\nEND;",
1257
+ "CREATE TRIGGER person_kind_member_au AFTER UPDATE OF chat_id, identity_id ON chat_members\nWHEN OLD.chat_id IS NOT NEW.chat_id OR OLD.identity_id IS NOT NEW.identity_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1258
+ "CREATE TRIGGER person_kind_chat_au AFTER UPDATE OF kind, participants_count ON chats\nWHEN OLD.kind IS NOT NEW.kind OR (OLD.participants_count <= 10) IS NOT (NEW.participants_count <= 10) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = NEW.id);\nEND;",
1259
+ "CREATE TRIGGER person_kind_member_count_ai AFTER INSERT ON member_counts\nWHEN (SELECT participants_count FROM chats WHERE id = NEW.chat_id) IS NULL BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = NEW.chat_id);\nEND;",
1260
+ "CREATE TRIGGER person_kind_member_count_ad AFTER DELETE ON member_counts\nWHEN (SELECT participants_count FROM chats WHERE id = OLD.chat_id) IS NULL BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = OLD.chat_id);\nEND;",
1261
+ "CREATE TRIGGER person_kind_member_count_au AFTER UPDATE OF listed_count, chat_id, date ON member_counts\nWHEN (OLD.listed_count IS NOT NEW.listed_count OR OLD.chat_id IS NOT NEW.chat_id OR OLD.date IS NOT NEW.date)\n AND (SELECT participants_count FROM chats WHERE id = NEW.chat_id) IS NULL BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM chat_members m JOIN identity_links l ON l.identity_id = m.identity_id WHERE m.chat_id = NEW.chat_id);\nEND;",
1262
+ "CREATE TRIGGER person_kind_email_ai AFTER INSERT ON emails BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.from_identity_id);\nEND;",
1263
+ "CREATE TRIGGER person_kind_email_ad AFTER DELETE ON emails BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.from_identity_id);\nEND;",
1264
+ "CREATE TRIGGER person_kind_email_au AFTER UPDATE OF from_identity_id, outgoing, deleted_at, draft, sent_at, received_at ON emails\nWHEN OLD.from_identity_id IS NOT NEW.from_identity_id OR OLD.outgoing IS NOT NEW.outgoing OR OLD.deleted_at IS NOT NEW.deleted_at OR OLD.draft IS NOT NEW.draft OR OLD.sent_at IS NOT NEW.sent_at OR OLD.received_at IS NOT NEW.received_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.from_identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.from_identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM email_recipients r JOIN identity_links l ON l.identity_id = r.identity_id WHERE r.email_id = NEW.id);\nEND;",
1265
+ "CREATE TRIGGER person_kind_recipient_ai AFTER INSERT ON email_recipients\nWHEN (SELECT outgoing FROM emails WHERE id = NEW.email_id) = 1 BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1266
+ "CREATE TRIGGER person_kind_recipient_ad AFTER DELETE ON email_recipients\nWHEN (SELECT outgoing FROM emails WHERE id = OLD.email_id) = 1 BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\nEND;",
1267
+ "CREATE TRIGGER person_kind_recipient_au AFTER UPDATE OF email_id, identity_id ON email_recipients\nWHEN (OLD.email_id IS NOT NEW.email_id OR OLD.identity_id IS NOT NEW.identity_id) AND 1 IN (SELECT outgoing FROM emails WHERE id IN (OLD.email_id, NEW.email_id)) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1268
+ "CREATE TRIGGER person_kind_email_mailbox_ai AFTER INSERT ON email_mailboxes BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id WHERE e.id = NEW.email_id);\nEND;",
1269
+ "CREATE TRIGGER person_kind_email_mailbox_ad AFTER DELETE ON email_mailboxes BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id WHERE e.id = OLD.email_id);\nEND;",
1270
+ "CREATE TRIGGER person_kind_mailbox_au AFTER UPDATE OF kind ON mailboxes\nWHEN OLD.kind IS NOT NEW.kind BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT l.person_id FROM email_mailboxes m JOIN emails e ON e.id = m.email_id JOIN identity_links l ON l.identity_id = e.from_identity_id WHERE m.mailbox_id = NEW.id);\nEND;",
1271
+ "CREATE TRIGGER person_kind_meeting_participant_ai AFTER INSERT ON meeting_participants BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1272
+ "CREATE TRIGGER person_kind_meeting_participant_ad AFTER DELETE ON meeting_participants BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\nEND;",
1273
+ "CREATE TRIGGER person_kind_meeting_participant_au AFTER UPDATE OF identity_id ON meeting_participants\nWHEN OLD.identity_id IS NOT NEW.identity_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1274
+ "CREATE TRIGGER person_kind_calendar_participant_ai AFTER INSERT ON calendar_entry_participants BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1275
+ "CREATE TRIGGER person_kind_calendar_participant_ad AFTER DELETE ON calendar_entry_participants BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\nEND;",
1276
+ "CREATE TRIGGER person_kind_calendar_participant_au AFTER UPDATE OF identity_id, resource ON calendar_entry_participants\nWHEN OLD.identity_id IS NOT NEW.identity_id OR OLD.resource IS NOT NEW.resource BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1277
+ "CREATE TRIGGER person_kind_account_identity_ai AFTER INSERT ON account_identities BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1278
+ "CREATE TRIGGER person_kind_account_identity_ad AFTER DELETE ON account_identities BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\nEND;",
1279
+ "CREATE TRIGGER person_kind_account_identity_au AFTER UPDATE OF identity_id, address_book, mail_signals, last_messaged_at ON account_identities\nWHEN OLD.identity_id IS NOT NEW.identity_id OR OLD.address_book IS NOT NEW.address_book OR OLD.mail_signals IS NOT NEW.mail_signals OR OLD.last_messaged_at IS NOT NEW.last_messaged_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1280
+ "CREATE TRIGGER person_kind_organization_identity_ai AFTER INSERT ON organization_identities BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1281
+ "CREATE TRIGGER person_kind_organization_identity_ad AFTER DELETE ON organization_identities BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\nEND;",
1282
+ "CREATE TRIGGER person_kind_organization_identity_au AFTER UPDATE OF identity_id ON organization_identities\nWHEN OLD.identity_id IS NOT NEW.identity_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;",
1283
+ "CREATE TRIGGER person_kind_record_ai AFTER INSERT ON records BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.entity_id WHERE NEW.entity_type = 'person');\nEND;",
1284
+ "CREATE TRIGGER person_kind_record_ad AFTER DELETE ON records BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.entity_id WHERE OLD.entity_type = 'person');\nEND;",
1285
+ "CREATE TRIGGER person_kind_record_au AFTER UPDATE OF entity_type, entity_id, deleted_at ON records\nWHEN OLD.entity_type IS NOT NEW.entity_type OR OLD.entity_id IS NOT NEW.entity_id OR OLD.deleted_at IS NOT NEW.deleted_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.entity_id WHERE OLD.entity_type = 'person');\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.entity_id WHERE NEW.entity_type = 'person');\nEND;",
1286
+ "CREATE TRIGGER person_kind_assignment_ai AFTER INSERT ON task_assignments BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.assignee_id WHERE NEW.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE NEW.assignee_type = 'person' AND from_person_id = NEW.assignee_id);\nEND;",
1287
+ "CREATE TRIGGER person_kind_assignment_ad AFTER DELETE ON task_assignments BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.assignee_id WHERE OLD.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE OLD.assignee_type = 'person' AND from_person_id = OLD.assignee_id);\nEND;",
1288
+ "CREATE TRIGGER person_kind_assignment_au AFTER UPDATE OF task_id, assignee_type, assignee_id ON task_assignments\nWHEN OLD.task_id IS NOT NEW.task_id OR OLD.assignee_type IS NOT NEW.assignee_type OR OLD.assignee_id IS NOT NEW.assignee_id BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT OLD.assignee_id WHERE OLD.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE OLD.assignee_type = 'person' AND from_person_id = OLD.assignee_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT NEW.assignee_id WHERE NEW.assignee_type = 'person' UNION SELECT to_person_id FROM identity_link_events WHERE NEW.assignee_type = 'person' AND from_person_id = NEW.assignee_id);\nEND;",
1289
+ "CREATE TRIGGER person_kind_task_au AFTER UPDATE OF deleted_at ON tasks\nWHEN OLD.deleted_at IS NOT NEW.deleted_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT a.assignee_id FROM task_assignments a WHERE a.task_id = NEW.id AND a.assignee_type = 'person' UNION SELECT e.to_person_id FROM task_assignments a JOIN identity_link_events e ON e.from_person_id = a.assignee_id WHERE a.task_id = NEW.id AND a.assignee_type = 'person');\nEND;",
1290
+ "CREATE TRIGGER person_kind_message_ai AFTER INSERT ON messages BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.sender_identity_id);\nEND;",
1291
+ "CREATE TRIGGER person_kind_message_ad AFTER DELETE ON messages BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.sender_identity_id);\nEND;",
1292
+ "CREATE TRIGGER person_kind_message_au AFTER UPDATE OF sender_identity_id, sent_at, deleted_at ON messages\nWHEN OLD.sender_identity_id IS NOT NEW.sender_identity_id OR OLD.sent_at IS NOT NEW.sent_at OR OLD.deleted_at IS NOT NEW.deleted_at BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = OLD.sender_identity_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.sender_identity_id);\nEND;"
1293
+ ]
1234
1294
  }
1235
1295
  ];
@@ -1,5 +1,5 @@
1
1
  import { type KindSignal, type PersonKind } from "../../domain/person-kinds.js";
2
- import type { CacheDatabase } from "../driver.js";
2
+ import { type CacheDatabase } from "../driver.js";
3
3
  import { type ShownBecause } from "./person-ties.js";
4
4
  export declare const PEOPLE_SORTS: readonly ["interactions", "recent", "name", "tasks"];
5
5
  export type PeopleSort = (typeof PEOPLE_SORTS)[number];
@@ -50,6 +50,8 @@ export interface SimilarPerson extends ListedPerson {
50
50
  /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
51
51
  sameName: boolean;
52
52
  }
53
+ /** How many people of each kind match the query, every kind at once. */
54
+ export declare const countPeople: (database: CacheDatabase, query?: string) => Record<PersonKind, number>;
53
55
  /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
54
56
  export declare const listPeople: (database: CacheDatabase, options: PeopleListOptions) => PeopleList;
55
57
  /**
@@ -2,10 +2,12 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
3
3
  import { displayName, isReadable, nameKey } from "../../domain/display-names.js";
4
4
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
5
+ import { isQueryOnly } from "../driver.js";
5
6
  import { fold } from "../normalize.js";
6
7
  import { mergedAwaySql } from "./merged-persons.js";
7
8
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
8
9
  import { mergedAssignees } from "./task-board.js";
10
+ import { read, writeBatch } from "./transaction.js";
9
11
  export const PEOPLE_SORTS = ["interactions", "recent", "name", "tasks"];
10
12
  const MIN_QUERY = 3;
11
13
  const ftsPhrase = (text) => `"${text.replaceAll('"', '""')}"`;
@@ -121,7 +123,7 @@ const kindOf = (shown, facts, ties, mail) => {
121
123
  return { kind: "person", signals: ties };
122
124
  };
123
125
  /** 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)) => {
126
+ const classified = (database, people, scope, reasons = shownReasons(database, scope === "all" ? undefined : scope)) => {
125
127
  const facts = factsOf(database, scope);
126
128
  const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
127
129
  const messages = countsOf(database, MESSAGE_COUNTS(scope), ...scopeParams(scope));
@@ -163,25 +165,160 @@ const withLastContact = (database, people, known) => {
163
165
  /** Sorted as read, case and accents aside; a name with nothing to read goes last. */
164
166
  const nameOrderOf = (shown) => `${isReadable(shown) ? 0 : 1}${fold(shown ?? "")}`;
165
167
  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;
168
+ /**
169
+ * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
170
+ * every stored one is worked out again on the next list.
171
+ */
172
+ const KIND_RULES = "1";
173
+ const RULES_KEY = "people.kind_rules";
174
+ /** Past this many people to work out, one pass over everyone beats a lookup per person. */
175
+ const WHOLE_PASS = 20_000;
176
+ /** About 0.7 s of work on 113,000 people: well inside another writer's 5 s wait for the lock. */
177
+ const UNDER_LOCK = 5_000;
178
+ const TRIES = 3;
179
+ const dataVersion = (database) => Number(Object.values(database.prepare("PRAGMA data_version").get() ?? {})[0]);
180
+ const rulesOf = (database) => {
181
+ const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(RULES_KEY);
182
+ return row === undefined ? undefined : String(row.value);
183
+ };
184
+ const candidateOf = (row) => ({
185
+ id: Number(row.id),
186
+ name: row.name == null ? null : String(row.name),
187
+ owner: Number(row.owner) === 1,
188
+ });
189
+ /** Stored for a person a merge emptied, so a list leaves them out without asking each person. */
190
+ const MERGED = "merged";
191
+ /** The people whose stored kind is not current, worked out; `undefined` when there are none. */
192
+ const workOut = (database, all, most) => {
193
+ const rows = database
194
+ .prepare(`SELECT id, name, owner, ${mergedAwaySql("p")} AS merged FROM persons p` +
195
+ `${all ? "" : " WHERE kind IS NULL"}${most === undefined ? "" : ` LIMIT ${most + 1}`}`)
196
+ .all();
197
+ if (rows.length === 0 && !all)
198
+ return undefined;
199
+ if (most !== undefined && rows.length > most)
200
+ return undefined;
201
+ const merged = new Set(rows.filter((row) => Number(row.merged) === 1).map((row) => Number(row.id)));
202
+ const stale = rows.map(candidateOf);
203
+ const scope = all || stale.length > WHOLE_PASS ? "all" : stale.map(({ id }) => id);
204
+ const contacts = lastContacts(database, scope);
205
+ return classified(database, stale, scope).map((person) => ({
206
+ ...person,
207
+ kind: merged.has(person.id) ? MERGED : person.kind,
208
+ lastContact: contacts.get(person.id),
209
+ }));
210
+ };
211
+ const keep = (database, worked) => {
212
+ const row = database.prepare("UPDATE persons SET kind = ?, name_order = ?, messages_from = ?, task_count = ?, last_contact = ? WHERE id = ?");
213
+ for (const person of worked)
214
+ row.run(person.kind, person.nameOrder, person.messagesFrom, person.tasks, person.lastContact ?? null, person.id);
215
+ database
216
+ .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " +
217
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
218
+ .run(RULES_KEY, KIND_RULES, Date.now());
219
+ };
220
+ /**
221
+ * Works out and keeps the kind, name order and counts of every person whose stored ones the triggers cleared.
222
+ * A few, as a sync leaves, are worked out under the write lock. Everyone, after an upgrade, would hold the lock for
223
+ * seconds: that pass runs outside it and is kept only when no other process wrote meanwhile, else it runs again.
224
+ * Answers whether every stored one is current.
225
+ */
226
+ const storeKinds = (database) => {
227
+ if (isQueryOnly(database))
228
+ return (rulesOf(database) === KIND_RULES &&
229
+ database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
230
+ if (rulesOf(database) === KIND_RULES &&
231
+ database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined)
232
+ return true;
233
+ const few = writeBatch(database, () => {
234
+ if (rulesOf(database) !== KIND_RULES)
235
+ return false;
236
+ const worked = workOut(database, false, UNDER_LOCK);
237
+ if (worked !== undefined)
238
+ keep(database, worked);
239
+ return (worked !== undefined || database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
240
+ });
241
+ if (few)
242
+ return true;
243
+ for (let attempt = 0; attempt < TRIES; attempt++) {
244
+ const before = dataVersion(database);
245
+ const worked = read(database, () => workOut(database, rulesOf(database) !== KIND_RULES));
246
+ if (worked === undefined)
247
+ return true;
248
+ const kept = writeBatch(database, () => {
249
+ if (dataVersion(database) !== before)
250
+ return false;
251
+ keep(database, worked);
252
+ return true;
253
+ });
254
+ if (kept)
255
+ return true;
256
+ }
257
+ return false;
258
+ };
259
+ const STORED_ORDER = {
260
+ interactions: "p.messages_from DESC, ",
261
+ tasks: "p.task_count DESC, ",
262
+ recent: "coalesce(p.last_contact, 0) DESC, ",
263
+ name: "",
264
+ };
265
+ const noCounts = () => Object.fromEntries(PERSON_KINDS.map((one) => [one, 0]));
266
+ const storedCounts = (database, filter) => {
267
+ const counts = noCounts();
268
+ for (const row of database
269
+ .prepare(`SELECT p.kind, count(*) AS n FROM persons p WHERE p.kind <> '${MERGED}'${filter.sql} GROUP BY 1`)
270
+ .all(...filter.params))
271
+ if (PERSON_KINDS.includes(row.kind))
272
+ counts[row.kind] = Number(row.n);
273
+ return counts;
274
+ };
275
+ const checked = (options) => {
276
+ const { kind = "person", sort = "interactions" } = options;
169
277
  if (kind !== "all" && !PERSON_KINDS.includes(kind))
170
278
  throw new CliError("validation_error", `a person's kind is one of ${PERSON_KINDS.join(", ")} or all, got "${kind}"`);
171
279
  if (!PEOPLE_SORTS.includes(sort))
172
280
  throw new CliError("validation_error", `people sort by ${PEOPLE_SORTS.join(", ")}, got "${sort}"`);
173
- const filter = matching(options.query);
281
+ return { kind, sort, filter: matching(options.query) };
282
+ };
283
+ /** How many people of each kind match the query, every kind at once. */
284
+ export const countPeople = (database, query) => {
285
+ const filter = matching(query);
286
+ return storeKinds(database) ? storedCounts(database, filter) : listInMemory(database, { limit: 0, query }).counts;
287
+ };
288
+ /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
289
+ export const listPeople = (database, options) => {
290
+ const { kind, sort, filter } = checked(options);
291
+ if (!storeKinds(database))
292
+ return listInMemory(database, options);
293
+ const { limit, offset = 0 } = options;
294
+ return read(database, () => {
295
+ const counts = storedCounts(database, filter);
296
+ const total = kind === "all" ? Object.values(counts).reduce((a, b) => a + b, 0) : counts[kind];
297
+ const rows = database
298
+ .prepare(`SELECT p.id, p.name, p.owner, p.last_contact FROM persons p WHERE p.kind ${kind === "all" ? "<>" : "="} ?` +
299
+ `${filter.sql} ORDER BY p.owner DESC, ${STORED_ORDER[sort]}p.name_order, p.id LIMIT ? OFFSET ?`)
300
+ .all(kind === "all" ? MERGED : kind, ...filter.params, limit, offset);
301
+ const page = rows.map(candidateOf);
302
+ const contacts = new Map(rows.filter((row) => row.last_contact != null).map((row) => [Number(row.id), Number(row.last_contact)]));
303
+ return {
304
+ items: withLastContact(database, classified(database, page, page.map(({ id }) => id)), contacts),
305
+ hasMore: total > offset + limit,
306
+ total,
307
+ counts,
308
+ };
309
+ });
310
+ };
311
+ /** The list worked out for every person on the call, for a read-only store whose stored kinds are not current. */
312
+ const listInMemory = (database, options) => {
313
+ const { kind, sort, filter } = checked(options);
314
+ const { limit, offset = 0 } = options;
174
315
  const candidates = database
175
316
  .prepare(`SELECT p.id, p.name, p.owner FROM persons p WHERE NOT ${mergedAwaySql("p")}${filter.sql}`)
176
317
  .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
- }));
318
+ .map(candidateOf);
182
319
  // A search reads only the people it found; a whole list reads everyone once rather than per person.
183
320
  const everyone = classified(database, candidates, options.query === undefined ? "all" : candidates.map(({ id }) => id));
184
- const counts = Object.fromEntries(PERSON_KINDS.map((one) => [one, 0]));
321
+ const counts = noCounts();
185
322
  for (const person of everyone)
186
323
  counts[person.kind] += 1;
187
324
  const chosen = kind === "all" ? everyone : everyone.filter((person) => person.kind === kind);
@@ -1,5 +1,8 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
- /** A group this small is people the owner knows; in a bigger one an author alone is background. */
2
+ /**
3
+ * A group this small is people the owner knows; in a bigger one an author alone is background. Store version 62's
4
+ * trigger `person_kind_chat_au` holds the same number: changing it takes a migration that replaces that trigger.
5
+ */
3
6
  export declare const SMALL_GROUP_MEMBERS = 10;
4
7
  /** What ties a person to the owner, from what the store holds about them. */
5
8
  export declare const PERSON_TIES: readonly ["chat", "small-group", "mail", "meeting", "crm", "phone-book"];
@@ -8,7 +11,7 @@ export type PersonTie = (typeof PERSON_TIES)[number];
8
11
  export declare const ALWAYS_SHOWN: readonly ["owner", "added", "task"];
9
12
  export type ShownBecause = (typeof ALWAYS_SHOWN)[number] | PersonTie;
10
13
  /**
11
- * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default. One
12
- * pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
14
+ * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default.
15
+ * `people` narrows it to those. One pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
13
16
  */
14
- export declare const shownReasons: (database: CacheDatabase) => Map<number, ShownBecause[]>;
17
+ export declare const shownReasons: (database: CacheDatabase, people?: readonly number[]) => Map<number, ShownBecause[]>;
@@ -1,7 +1,10 @@
1
1
  import { kindsOfEntry, providers } from "../../domain/providers.js";
2
2
  import { mergedAwaySql } from "./merged-persons.js";
3
3
  import { mergedAssignees } from "./task-board.js";
4
- /** A group this small is people the owner knows; in a bigger one an author alone is background. */
4
+ /**
5
+ * A group this small is people the owner knows; in a bigger one an author alone is background. Store version 62's
6
+ * trigger `person_kind_chat_au` holds the same number: changing it takes a migration that replaces that trigger.
7
+ */
5
8
  export const SMALL_GROUP_MEMBERS = 10;
6
9
  /** What ties a person to the owner, from what the store holds about them. */
7
10
  export const PERSON_TIES = ["chat", "small-group", "mail", "meeting", "crm", "phone-book"];
@@ -49,14 +52,15 @@ const reasonRows = () => [
49
52
  ].join(" UNION ALL ");
50
53
  const ORDER = [...ALWAYS_SHOWN, ...PERSON_TIES];
51
54
  /**
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`).
55
+ * Why each person is shown, in a fixed order; a person missing from the map has no tie and is hidden by default.
56
+ * `people` narrows it to those. One pass over every tie: on 51,000 identities about 35 ms (cli-testing `performance/people/ties`).
54
57
  */
55
- export const shownReasons = (database) => {
58
+ export const shownReasons = (database, people) => {
56
59
  const found = new Map();
60
+ const only = people === undefined ? "" : " WHERE person IN (SELECT value FROM json_each(?))";
57
61
  for (const row of database
58
- .prepare(`SELECT DISTINCT person, tie FROM (${reasonRows()})`)
59
- .all(mergedAssignees(database))) {
62
+ .prepare(`SELECT DISTINCT person, tie FROM (${reasonRows()})${only}`)
63
+ .all(mergedAssignees(database), ...(people === undefined ? [] : [JSON.stringify(people)]))) {
60
64
  const person = Number(row.person);
61
65
  const reasons = found.get(person) ?? new Set();
62
66
  reasons.add(row.tie);
@@ -1,8 +1,9 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { replaceMembers } from "./chats.js";
2
3
  import { and, asc, eq, gte, inArray, isNotNull, isNull, or, sql } from "./drizzle/core.js";
3
4
  import { identityPk, seenIdentity } from "./identities.js";
4
5
  import { bound } from "./query-filter.js";
5
- import { chatMembers, chats, identities, identityRevisions, memberCounts, memberStays } from "./schema.js";
6
+ import { chats, identities, identityRevisions, memberCounts, memberStays } from "./schema.js";
6
7
  const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
7
8
  const marksOf = ({ isBot, flagged, deleted, hasPhoto }) => ({
8
9
  ...(isBot === undefined ? {} : { bot: isBot }),
@@ -104,9 +105,7 @@ export const saveRoster = (context, accountKey, provider, chatKey, { members, co
104
105
  orm.update(memberStays).set({ leftAt: observedAt }).where(eq(memberStays.id, pk)).run();
105
106
  change.gone.push(id);
106
107
  }
107
- orm.delete(chatMembers).where(eq(chatMembers.chatId, chatKey)).run();
108
- for (const person of present)
109
- orm.insert(chatMembers).values({ chatId: chatKey, identityId: person, createdAt: at }).run();
108
+ replaceMembers(context, chatKey, [...present], at);
110
109
  }
111
110
  const day = new Date(at).toISOString().slice(0, 10);
112
111
  const count = {
@@ -842,6 +842,86 @@ export declare const persons: import("drizzle-orm/sqlite-core").SQLiteTableWithC
842
842
  identity: undefined;
843
843
  generated: undefined;
844
844
  }, {}>;
845
+ kind: import("drizzle-orm/sqlite-core").SQLiteColumn<{
846
+ name: string;
847
+ tableName: "persons";
848
+ dataType: "string";
849
+ data: string;
850
+ driverParam: string;
851
+ notNull: false;
852
+ hasDefault: false;
853
+ isPrimaryKey: false;
854
+ isAutoincrement: false;
855
+ hasRuntimeDefault: false;
856
+ enumValues: [string, ...string[]];
857
+ baseColumn: never;
858
+ identity: undefined;
859
+ generated: undefined;
860
+ }, {}>;
861
+ nameOrder: import("drizzle-orm/sqlite-core").SQLiteColumn<{
862
+ name: string;
863
+ tableName: "persons";
864
+ dataType: "string";
865
+ data: string;
866
+ driverParam: string;
867
+ notNull: false;
868
+ hasDefault: false;
869
+ isPrimaryKey: false;
870
+ isAutoincrement: false;
871
+ hasRuntimeDefault: false;
872
+ enumValues: [string, ...string[]];
873
+ baseColumn: never;
874
+ identity: undefined;
875
+ generated: undefined;
876
+ }, {}>;
877
+ messagesFrom: import("drizzle-orm/sqlite-core").SQLiteColumn<{
878
+ name: string;
879
+ tableName: "persons";
880
+ dataType: "number int53";
881
+ data: number;
882
+ driverParam: number;
883
+ notNull: false;
884
+ hasDefault: false;
885
+ isPrimaryKey: false;
886
+ isAutoincrement: false;
887
+ hasRuntimeDefault: false;
888
+ enumValues: undefined;
889
+ baseColumn: never;
890
+ identity: undefined;
891
+ generated: undefined;
892
+ }, {}>;
893
+ taskCount: import("drizzle-orm/sqlite-core").SQLiteColumn<{
894
+ name: string;
895
+ tableName: "persons";
896
+ dataType: "number int53";
897
+ data: number;
898
+ driverParam: number;
899
+ notNull: false;
900
+ hasDefault: false;
901
+ isPrimaryKey: false;
902
+ isAutoincrement: false;
903
+ hasRuntimeDefault: false;
904
+ enumValues: undefined;
905
+ baseColumn: never;
906
+ identity: undefined;
907
+ generated: undefined;
908
+ }, {}>;
909
+ lastContact: import("drizzle-orm/sqlite-core").SQLiteColumn<{
910
+ name: string;
911
+ tableName: "persons";
912
+ dataType: "number int53";
913
+ data: number;
914
+ driverParam: number;
915
+ notNull: false;
916
+ hasDefault: false;
917
+ isPrimaryKey: false;
918
+ isAutoincrement: false;
919
+ hasRuntimeDefault: false;
920
+ enumValues: undefined;
921
+ baseColumn: never;
922
+ identity: undefined;
923
+ generated: undefined;
924
+ }, {}>;
845
925
  };
846
926
  dialect: 'sqlite';
847
927
  isAlias: false;
@@ -86,7 +86,15 @@ export const persons = sqliteTable("persons", {
86
86
  owner: integer("owner").notNull().default(0),
87
87
  createdAt: integer("created_at").notNull(),
88
88
  updatedAt: integer("updated_at").notNull(),
89
- });
89
+ kind: text("kind"),
90
+ nameOrder: text("name_order"),
91
+ messagesFrom: integer("messages_from"),
92
+ taskCount: integer("task_count"),
93
+ lastContact: integer("last_contact"),
94
+ }, (table) => [
95
+ index("persons_by_kind").on(table.kind),
96
+ index("persons_kind_to_work_out").on(table.id).where(sql `kind IS NULL`),
97
+ ]);
90
98
  export const identities = sqliteTable("identities", {
91
99
  id: integer("id").primaryKey(),
92
100
  provider: text("provider").notNull(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.628.0",
3
+ "version": "0.629.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -15,7 +15,7 @@
15
15
  "type": "module",
16
16
  "wirecat": {
17
17
  "store": {
18
- "speaks": 61,
18
+ "speaks": 62,
19
19
  "minCompatible": 56
20
20
  }
21
21
  },