@wirecat/cli-core 0.631.0 → 0.633.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 (58) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/calendar/mcp/index.d.ts +12 -12
  3. package/dist/cli/messenger/archive-commands.js +4 -1
  4. package/dist/cli/messenger/context.d.ts +2 -0
  5. package/dist/cli/messenger/reply-stats-command.js +1 -1
  6. package/dist/cli/messenger/serve-relay.d.ts +1 -0
  7. package/dist/cli/messenger/stats-answers.d.ts +5 -2
  8. package/dist/cli/messenger/stats-answers.js +8 -2
  9. package/dist/cli/messenger/store-import-command.d.ts +4 -0
  10. package/dist/cli/messenger/store-import-command.js +166 -0
  11. package/dist/cli/messenger/stored.d.ts +7 -1
  12. package/dist/cli/messenger/stored.js +1 -1
  13. package/dist/cli/messenger/tasks-command.js +5 -3
  14. package/dist/domain/test-data.d.ts +15 -0
  15. package/dist/domain/test-data.js +18 -0
  16. package/dist/entities/chat-stats.d.ts +2 -0
  17. package/dist/entities/chat-stats.js +2 -0
  18. package/dist/entities/index.d.ts +18 -2
  19. package/dist/entities/index.js +3 -2
  20. package/dist/entities/store-maintenance.d.ts +16 -0
  21. package/dist/entities/store-maintenance.js +10 -0
  22. package/dist/errors/reasons.js +9 -0
  23. package/dist/kit/seed.js +6 -7
  24. package/dist/search/lucene/registry.js +11 -0
  25. package/dist/sends/permissions.js +1 -0
  26. package/dist/services/proposals/kinds/identity-split.d.ts +4 -0
  27. package/dist/services/proposals/kinds/identity-split.js +65 -0
  28. package/dist/services/proposals/registry.js +2 -0
  29. package/dist/services/reply-stats.js +11 -3
  30. package/dist/services/task-stats.d.ts +7 -2
  31. package/dist/services/task-stats.js +53 -20
  32. package/dist/services/tasks.d.ts +1 -0
  33. package/dist/services/tasks.js +16 -4
  34. package/dist/store/decisions.js +3 -1
  35. package/dist/store/drivers/bun-sqlite.js +2 -0
  36. package/dist/store/drivers/node-sqlite.js +2 -0
  37. package/dist/store/identity-splits.d.ts +60 -0
  38. package/dist/store/identity-splits.js +5 -0
  39. package/dist/store/index.d.ts +2 -0
  40. package/dist/store/index.js +2 -0
  41. package/dist/store/path.d.ts +3 -0
  42. package/dist/store/path.js +25 -6
  43. package/dist/store/people.d.ts +23 -0
  44. package/dist/store/people.js +6 -0
  45. package/dist/store/sqlite/accounts.js +4 -0
  46. package/dist/store/sqlite/crm-contacts.js +5 -1
  47. package/dist/store/sqlite/identity-link-rows.d.ts +5 -0
  48. package/dist/store/sqlite/identity-link-rows.js +5 -3
  49. package/dist/store/sqlite/identity-split-proposals.d.ts +29 -0
  50. package/dist/store/sqlite/identity-split-proposals.js +195 -0
  51. package/dist/store/sqlite/lucene-fields.js +3 -0
  52. package/dist/store/sqlite/person-doubts.d.ts +36 -0
  53. package/dist/store/sqlite/person-doubts.js +229 -0
  54. package/dist/store/sqlite/proposed-actions.js +6 -0
  55. package/dist/store/sqlite/reply-times.d.ts +3 -1
  56. package/dist/store/sqlite/reply-times.js +11 -6
  57. package/package.json +1 -1
  58. package/parity.json +3 -0
@@ -0,0 +1,229 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { displayName } from "../../domain/display-names.js";
3
+ import { nameSkeletons } from "../../domain/name-variants.js";
4
+ import { RESERVED_ADDRESS_GLOBS, SEED_ID_GLOBS, SEED_PEOPLE } from "../../domain/test-data.js";
5
+ import { keptTogether } from "./identity-split-proposals.js";
6
+ import { merges } from "./person-merges.js";
7
+ /** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
8
+ export const DOUBT_REASONS = ["owner-other-name", "test-data", "shared-address", "mixed-names"];
9
+ const COLUMNS = "l.person_id AS person, p.owner, p.name AS person_name, i.id AS pk, i.provider, i.external_id, i.name, i.phone, " +
10
+ "i.email, l.method, l.author, l.created_at, EXISTS (SELECT 1 FROM accounts a WHERE a.provider = i.provider " +
11
+ "AND a.external_id = i.external_id) AS account FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
12
+ "JOIN persons p ON p.id = l.person_id";
13
+ const text = (value) => (typeof value === "string" && value.trim() !== "" ? value : null);
14
+ const heldOf = (row) => ({
15
+ pk: Number(row.pk),
16
+ person: Number(row.person),
17
+ owner: Number(row.owner) === 1,
18
+ personName: text(row.person_name),
19
+ ref: `${String(row.provider)}:${String(row.external_id)}`,
20
+ name: text(row.name),
21
+ phone: text(row.phone)?.replace(/\D/gu, "") || null,
22
+ email: text(row.email)?.toLowerCase() ?? null,
23
+ account: Number(row.account) === 1,
24
+ method: String(row.method),
25
+ by: String(row.author),
26
+ at: Number(row.created_at),
27
+ });
28
+ /** Only these people can carry two names or someone else's identity; the store has a few thousand of them. */
29
+ const sharedPeople = (database) => database
30
+ .prepare(`SELECT ${COLUMNS} WHERE l.person_id IN (SELECT person_id FROM identity_links GROUP BY person_id HAVING count(*) > 1) ` +
31
+ "ORDER BY l.person_id, i.id")
32
+ .all()
33
+ .map(heldOf);
34
+ /**
35
+ * Identities a test run left: the seed's word ids, an address at a reserved domain, or a seed name with its username
36
+ * or beside another seed name in one provider, since one name alone may be a real person's.
37
+ */
38
+ const testData = (database) => {
39
+ const names = JSON.stringify(SEED_PEOPLE.map(({ name }) => name));
40
+ const usernames = JSON.stringify(SEED_PEOPLE.flatMap(({ username }) => (username === null ? [] : [username])));
41
+ const globs = (column, patterns) => patterns.map((pattern) => `${column} GLOB '${pattern}'`).join(" OR ");
42
+ return database
43
+ .prepare(`SELECT ${COLUMNS} WHERE ${globs("i.external_id", SEED_ID_GLOBS)} OR ${globs("lower(i.email)", RESERVED_ADDRESS_GLOBS)} ` +
44
+ "OR (i.name IN (SELECT value FROM json_each(?)) AND (i.username IN (SELECT value FROM json_each(?)) " +
45
+ "OR (SELECT count(DISTINCT j.name) FROM identities j WHERE j.provider = i.provider " +
46
+ "AND j.name IN (SELECT value FROM json_each(?))) >= 2)) ORDER BY l.person_id, i.id")
47
+ .all(names, usernames, names)
48
+ .map(heldOf);
49
+ };
50
+ /** A name's words, script and spelling aside; none for an address or a placeholder, which say nothing of a name. */
51
+ const wordsOf = (name) => {
52
+ const shown = displayName(name);
53
+ if (shown === null || shown.includes("@"))
54
+ return new Set();
55
+ return new Set(nameSkeletons(shown).filter((word) => word.length >= 2 && !/^\d+$/u.test(word)));
56
+ };
57
+ const sharesWord = (one, other) => [...one].some((word) => other.has(word));
58
+ /**
59
+ * The identities grouped by names that share a word, the person's own first: the most identities, counting double what
60
+ * the owner linked by hand, an account the owner connected and the person's own name.
61
+ */
62
+ const nameGroups = (held) => {
63
+ const named = held.map((one) => ({ one, words: wordsOf(one.name) })).filter(({ words }) => words.size > 0);
64
+ const group = named.map((_, index) => index);
65
+ const root = (at) => {
66
+ let top = at;
67
+ while (group[top] !== top)
68
+ top = group[top];
69
+ let step = at;
70
+ while (group[step] !== top) {
71
+ const next = group[step];
72
+ group[step] = top;
73
+ step = next;
74
+ }
75
+ return top;
76
+ };
77
+ const firstWith = new Map();
78
+ for (const [index, { words }] of named.entries())
79
+ for (const word of words) {
80
+ const first = firstWith.get(word);
81
+ if (first === undefined)
82
+ firstWith.set(word, index);
83
+ else
84
+ group[root(index)] = root(first);
85
+ }
86
+ const groups = new Map();
87
+ for (const [index, { one }] of named.entries()) {
88
+ const same = groups.get(root(index));
89
+ if (same)
90
+ same.push(one);
91
+ else
92
+ groups.set(root(index), [one]);
93
+ }
94
+ const own = wordsOf(held[0]?.personName ?? null);
95
+ const weight = (members) => members.reduce((sum, one) => sum + 1 + (one.by === "owner" ? 2 : 0) + (one.account ? 2 : 0), 0) +
96
+ (members.some(({ name }) => sharesWord(wordsOf(name), own)) ? 2 : 0);
97
+ return [...groups.values()].sort((a, b) => weight(b) - weight(a) || a[0].pk - b[0].pk);
98
+ };
99
+ const quoted = (held) => [...new Set(held.map(({ name, ref }) => name ?? ref))].map((name) => `«${name}»`).join(", ");
100
+ const whyOf = (found) => {
101
+ const names = quoted(found.held);
102
+ if (found.reason === "owner-other-name")
103
+ return `your own person holds ${names}, under another name than yours: an account or mailbox you read may be someone else's`;
104
+ if (found.reason === "test-data")
105
+ return `${names} looks like test data, not a real contact: a name from the test seed, or an address at a reserved test domain`;
106
+ if (found.reason === "shared-address")
107
+ return `${names} joined this person by the address ${found.address}, which people with other names share: a shared or company mailbox may hold two people`;
108
+ return `this person carries different names (${names}) with no phone or address in common`;
109
+ };
110
+ const doubtsOf = (held, kept, test) => {
111
+ const [first] = held;
112
+ if (first === undefined)
113
+ return [];
114
+ const groups = nameGroups(held.filter(({ pk }) => !test.has(pk)));
115
+ if (groups.length < 2)
116
+ return [];
117
+ const main = groups[0];
118
+ const outside = groups
119
+ .slice(1)
120
+ .flat()
121
+ .filter(({ by, ref }) => by !== "owner" && !kept.has(ref));
122
+ const base = { person: first.person, owner: first.owner, name: first.personName };
123
+ if (first.owner)
124
+ return outside.length ? [{ ...base, reason: "owner-other-name", held: outside }] : [];
125
+ const found = [];
126
+ const mixed = [];
127
+ for (const one of outside) {
128
+ if (one.phone !== null && main.some(({ phone }) => phone === one.phone))
129
+ continue;
130
+ const address = one.email === null ? undefined : main.find(({ email }) => email === one.email)?.email;
131
+ if (typeof address === "string")
132
+ found.push({ ...base, reason: "shared-address", held: [one], address });
133
+ else
134
+ mixed.push(one);
135
+ }
136
+ if (mixed.length)
137
+ found.push({ ...base, reason: "mixed-names", held: [...main, ...mixed] });
138
+ return found;
139
+ };
140
+ const byPerson = (held) => {
141
+ const found = new Map();
142
+ for (const one of held) {
143
+ const same = found.get(one.person);
144
+ if (same)
145
+ same.push(one);
146
+ else
147
+ found.set(one.person, [one]);
148
+ }
149
+ return found;
150
+ };
151
+ const ORDER = new Map(DOUBT_REASONS.map((reason, index) => [reason, index]));
152
+ /** Everything in doubt, the owner first, then by reason and person. A few thousand people are read, never every row. */
153
+ const everyDoubt = (database) => {
154
+ const test = testData(database);
155
+ const testPks = new Set(test.map(({ pk }) => pk));
156
+ const kept = keptTogether(database);
157
+ const found = [];
158
+ for (const [person, held] of byPerson(sharedPeople(database)))
159
+ for (const one of doubtsOf(held, kept.get(person) ?? new Set(), testPks))
160
+ found.push(one);
161
+ for (const held of byPerson(test).values()) {
162
+ const [first] = held;
163
+ found.push({ person: first.person, owner: first.owner, name: first.personName, reason: "test-data", held });
164
+ }
165
+ return found.sort((a, b) => Number(b.owner) - Number(a.owner) ||
166
+ (ORDER.get(a.reason) ?? 0) - (ORDER.get(b.reason) ?? 0) ||
167
+ a.person - b.person);
168
+ };
169
+ /**
170
+ * The owner's moves that take the doubted identities off: undoing a merge that brought only doubted ones, and one
171
+ * unlink per name group of the rest, so two strangers on one person do not land on one new person together.
172
+ */
173
+ const fixOf = (context, found) => {
174
+ if (found.reason === "test-data" || found.reason === "mixed-names")
175
+ return [];
176
+ const doubted = new Set(found.held.map(({ ref }) => ref));
177
+ const commands = [];
178
+ const unmerged = new Set();
179
+ for (const merge of merges(context, String(found.person))) {
180
+ const refs = merge.identities.map(({ provider, id }) => `${provider}:${id}`);
181
+ if (refs.length === 0 || !refs.every((ref) => doubted.has(ref)))
182
+ continue;
183
+ commands.push(`people unmerge ${merge.id}`);
184
+ for (const ref of refs)
185
+ unmerged.add(ref);
186
+ }
187
+ const rest = found.held.filter(({ ref }) => !unmerged.has(ref));
188
+ for (const group of nameGroups(rest))
189
+ commands.push(`people unlink ${group.map(({ ref }) => shellWord(ref)).join(" ")}`);
190
+ return commands;
191
+ };
192
+ /** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
193
+ const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
194
+ const shown = (context, found) => {
195
+ const fix = fixOf(context, found);
196
+ return {
197
+ person: `person:${found.person}`,
198
+ name: found.name,
199
+ owner: found.owner,
200
+ reason: found.reason,
201
+ why: whyOf(found),
202
+ identities: found.held.map(({ ref, name, method, by, at }) => ({
203
+ identity: ref,
204
+ name,
205
+ method,
206
+ by,
207
+ at: new Date(at).toISOString(),
208
+ })),
209
+ evidence: [
210
+ ...found.held.map(({ ref }) => ref),
211
+ ...(found.address === undefined ? [] : [`email:${found.address}`]),
212
+ ...fix.flatMap((command) => command.match(/merge:\d+-\d+/u) ?? []),
213
+ ],
214
+ fix,
215
+ };
216
+ };
217
+ /** People that may be wrong, a page at a time, each with why and the owner's moves that would set it right. */
218
+ export const personDoubts = (context, { limit, offset }) => {
219
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
220
+ throw new CliError("validation_error", "a list of doubts takes 1–500 items");
221
+ if (!Number.isSafeInteger(offset) || offset < 0)
222
+ throw new CliError("validation_error", "a list of doubts takes a nonnegative offset");
223
+ const found = everyDoubt(context.database);
224
+ return {
225
+ items: found.slice(offset, offset + limit).map((one) => shown(context, one)),
226
+ total: found.length,
227
+ hasMore: found.length > offset + limit,
228
+ };
229
+ };
@@ -3,6 +3,7 @@ import { MEETING_FINDINGS_KIND } from "../../meetings/index.js";
3
3
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
4
4
  import { EVIDENCE_FINDINGS_KIND } from "../evidence-findings.js";
5
5
  import { IDENTITY_LINK_KIND } from "../identity-links.js";
6
+ import { IDENTITY_SPLIT_KIND } from "../identity-splits.js";
6
7
  import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
7
8
  import { SOURCE_REVIEW_KIND } from "../source-review.js";
8
9
  import { proposedBySql } from "./actors.js";
@@ -191,6 +192,11 @@ const DEDICATED_REVIEW = {
191
192
  reason: "identity-link.dedicated-review",
192
193
  through: "the people review, which checks that neither person changed",
193
194
  },
195
+ [IDENTITY_SPLIT_KIND]: {
196
+ what: "a proposed split of a person",
197
+ reason: "identity-split.dedicated-review",
198
+ through: "the people review, which checks that the person did not change",
199
+ },
194
200
  };
195
201
  /** Refuses a dedicated kind on a generic action path: approving one as an action would skip its own checks. */
196
202
  export const assertGenericAction = (kind) => {
@@ -9,6 +9,8 @@ export interface ChatScope {
9
9
  chatId: string;
10
10
  }[];
11
11
  kinds: string[];
12
+ /** Only chats muted (true) or not muted (false) now; absent reads both. */
13
+ muted?: boolean;
12
14
  /** Inclusive bounds in ms; absent is open. */
13
15
  since?: number;
14
16
  until?: number;
@@ -33,7 +35,7 @@ export interface NewestMessage {
33
35
  * One row per reply in one-to-one chats. Each chat is read from the start of the run before the first message in the
34
36
  * period, so a reply early in the period is timed from the first message it answers, however old.
35
37
  */
36
- export declare const replyDelaysQuery: (scope: ChatScope, who: "me" | "others") => {
38
+ export declare const replyDelaysQuery: (scope: ChatScope, who: "me" | "others", now: number) => {
37
39
  sql: string;
38
40
  params: SqlValue[];
39
41
  };
@@ -1,7 +1,8 @@
1
1
  import { PEER_KIND } from "./lucene-fields.js";
2
2
  import { read } from "./transaction.js";
3
3
  const FAR = Number.MAX_SAFE_INTEGER;
4
- const chatsIn = (scope, kinds) => {
4
+ const MUTED_NOW = "(coalesce(c.muted,0)=1 AND (c.muted_until IS NULL OR c.muted_until>?))";
5
+ const chatsIn = (scope, kinds, now) => {
5
6
  const params = [...scope.accounts.flatMap(({ provider, account }) => [provider, account]), ...kinds];
6
7
  const parts = [
7
8
  `(${scope.accounts.map(() => "(ac.provider=? AND ac.external_id=?)").join(" OR ") || "0"})`,
@@ -15,6 +16,10 @@ const chatsIn = (scope, kinds) => {
15
16
  parts.push(`${PEER_KIND}=?`);
16
17
  params.push(kind);
17
18
  }
19
+ if (scope.muted !== undefined) {
20
+ parts.push(scope.muted ? MUTED_NOW : `NOT ${MUTED_NOW}`);
21
+ params.push(now);
22
+ }
18
23
  // As in search: a chat named is read even when it is not searchable.
19
24
  if (scope.chats.length === 0)
20
25
  parts.push("c.searchable=1");
@@ -24,10 +29,10 @@ const chatsIn = (scope, kinds) => {
24
29
  * One row per reply in one-to-one chats. Each chat is read from the start of the run before the first message in the
25
30
  * period, so a reply early in the period is timed from the first message it answers, however old.
26
31
  */
27
- export const replyDelaysQuery = (scope, who) => {
32
+ export const replyDelaysQuery = (scope, who, now) => {
28
33
  const since = scope.since ?? -FAR;
29
34
  const until = scope.until ?? FAR;
30
- const chats = chatsIn(scope, ["private"]);
35
+ const chats = chatsIn(scope, ["private"], now);
31
36
  return {
32
37
  sql: `WITH scoped AS MATERIALIZED (
33
38
  SELECT c.id AS chat_id, coalesce((
@@ -51,7 +56,7 @@ WHERE asked_at IS NOT NULL AND mine=? AND sent_at>=? AND sent_at<=?`,
51
56
  };
52
57
  };
53
58
  export const replyDelays = (context, scope, who) => {
54
- const { sql, params } = replyDelaysQuery(scope, who);
59
+ const { sql, params } = replyDelaysQuery(scope, who, context.now());
55
60
  return read(context.database, () => context.database
56
61
  .prepare(sql)
57
62
  .all(...params)
@@ -59,7 +64,7 @@ export const replyDelays = (context, scope, who) => {
59
64
  };
60
65
  /** Each one-to-one chat's and group's newest message, found by index per chat, its time within the scope's bounds. */
61
66
  export const newestMessagesQuery = (scope, now) => {
62
- const chats = chatsIn(scope, ["private", "group"]);
67
+ const chats = chatsIn(scope, ["private", "group"], now);
63
68
  return {
64
69
  sql: `SELECT c.id AS chat_id, ${PEER_KIND} AS kind, m.sent_at, coalesce(m.outgoing,0) AS mine, m.text,
65
70
  (EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(m.mentions) THEN m.mentions ELSE '[]' END) WHERE value=ac.external_id)
@@ -67,7 +72,7 @@ export const newestMessagesQuery = (scope, now) => {
67
72
  OR EXISTS (SELECT 1 FROM messages q WHERE q.chat_id=c.id AND q.external_id=m.reply_to_external_id AND q.outgoing=1)
68
73
  ) AS addressed,
69
74
  (SELECT i.username FROM identities i WHERE i.provider=ac.provider AND i.external_id=ac.external_id) AS owner_username,
70
- ((coalesce(c.muted,0)=1 AND (c.muted_until IS NULL OR c.muted_until>?)) OR coalesce(c.archived,0)=1)
75
+ (${MUTED_NOW} OR coalesce(c.archived,0)=1)
71
76
  AND coalesce(c.marked_unread,0)=0 AS quiet
72
77
  FROM chats c JOIN accounts ac ON ac.id=c.account_id
73
78
  JOIN messages m ON m.id=(SELECT n.id FROM messages n WHERE n.chat_id=c.id AND n.deleted_at IS NULL ORDER BY n.sent_at DESC LIMIT 1)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.631.0",
3
+ "version": "0.633.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",
package/parity.json CHANGED
@@ -4878,6 +4878,9 @@
4878
4878
  "store gaps show": {
4879
4879
  "in": "all"
4880
4880
  },
4881
+ "store import": {
4882
+ "in": "all"
4883
+ },
4881
4884
  "store info": {
4882
4885
  "in": "all"
4883
4886
  },