@wirecat/cli-core 0.630.0 → 0.632.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 (60) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/mcp/index.d.ts +12 -12
  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/tasks-command.js +5 -3
  10. package/dist/crm/cli/index.js +22 -2
  11. package/dist/crm/sync.d.ts +3 -1
  12. package/dist/crm/sync.js +5 -0
  13. package/dist/domain/crm.d.ts +2 -1
  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 +1 -0
  19. package/dist/errors/reasons.js +9 -0
  20. package/dist/kit/seed.js +6 -7
  21. package/dist/search/lucene/registry.js +11 -0
  22. package/dist/services/metadata.d.ts +1 -1
  23. package/dist/services/proposals/kinds/identity-split.d.ts +4 -0
  24. package/dist/services/proposals/kinds/identity-split.js +65 -0
  25. package/dist/services/proposals/registry.js +2 -0
  26. package/dist/services/reply-stats.js +11 -3
  27. package/dist/services/task-stats.d.ts +7 -2
  28. package/dist/services/task-stats.js +53 -20
  29. package/dist/services/tasks.d.ts +1 -0
  30. package/dist/services/tasks.js +16 -4
  31. package/dist/store/decisions.js +3 -1
  32. package/dist/store/drivers/bun-sqlite.js +2 -0
  33. package/dist/store/drivers/node-sqlite.js +2 -0
  34. package/dist/store/identity-splits.d.ts +60 -0
  35. package/dist/store/identity-splits.js +5 -0
  36. package/dist/store/index.d.ts +3 -1
  37. package/dist/store/index.js +3 -1
  38. package/dist/store/people.d.ts +23 -0
  39. package/dist/store/people.js +6 -0
  40. package/dist/store/sqlite/accounts.d.ts +7 -0
  41. package/dist/store/sqlite/accounts.js +17 -5
  42. package/dist/store/sqlite/crm-contacts.d.ts +26 -0
  43. package/dist/store/sqlite/crm-contacts.js +138 -0
  44. package/dist/store/sqlite/crm-settings.d.ts +2 -0
  45. package/dist/store/sqlite/crm-settings.js +5 -0
  46. package/dist/store/sqlite/crm.d.ts +12 -0
  47. package/dist/store/sqlite/crm.js +7 -2
  48. package/dist/store/sqlite/identity-link-rows.d.ts +5 -0
  49. package/dist/store/sqlite/identity-link-rows.js +5 -3
  50. package/dist/store/sqlite/identity-split-proposals.d.ts +29 -0
  51. package/dist/store/sqlite/identity-split-proposals.js +195 -0
  52. package/dist/store/sqlite/lucene-fields.js +3 -0
  53. package/dist/store/sqlite/manifest.js +1 -0
  54. package/dist/store/sqlite/migrations.generated.js +15 -0
  55. package/dist/store/sqlite/person-doubts.d.ts +36 -0
  56. package/dist/store/sqlite/person-doubts.js +229 -0
  57. package/dist/store/sqlite/proposed-actions.js +6 -0
  58. package/dist/store/sqlite/reply-times.d.ts +3 -1
  59. package/dist/store/sqlite/reply-times.js +11 -6
  60. package/package.json +2 -2
@@ -0,0 +1,65 @@
1
+ import { IDENTITY_SPLIT_KIND, proposerOfAction } from "../../../store/index.js";
2
+ import { actionStatus, kept, pushed, storedStatus } from "./shared.js";
3
+ const summaryOf = (payload, person) => payload.split === "unmerge"
4
+ ? `undo ${payload.merge}: ${payload.identities.join(", ")} go back to their own person`
5
+ : `${payload.identities.join(", ")} may not be ${person}: they would move to a person of their own`;
6
+ /** An older build approved it as a plain action and split nothing: it shows as turned down, not as done. */
7
+ const dropped = (action) => action.status !== "proposed" &&
8
+ action.status !== "rejected" &&
9
+ typeof action.result?.person !== "string";
10
+ const rowOf = (store) => async (action) => {
11
+ const payload = action.payload;
12
+ const [first] = payload.identities;
13
+ const now = first === undefined
14
+ ? undefined
15
+ : await store.people.personOf({
16
+ provider: first.slice(0, first.indexOf(":")),
17
+ id: first.slice(first.indexOf(":") + 1),
18
+ });
19
+ const person = `person:${now?.uid ?? payload.person}`;
20
+ const summary = summaryOf(payload, person);
21
+ return {
22
+ id: action.id,
23
+ kind: IDENTITY_SPLIT_KIND,
24
+ status: dropped(action) ? "rejected" : actionStatus(action.status),
25
+ project: null,
26
+ subject: person,
27
+ object: null,
28
+ summary: dropped(action)
29
+ ? `not carried out: an older version approved it without splitting; ${summary}`
30
+ : summary,
31
+ proposedBy: proposerOfAction(action),
32
+ reason: action.reason,
33
+ evidence: payload.evidence.slice(0, 5),
34
+ score: null,
35
+ signals: null,
36
+ parts: null,
37
+ createdAt: action.createdAt,
38
+ };
39
+ };
40
+ /** Identities that may not belong to their person; only the owner takes them off. */
41
+ export const identitySplitKind = (store) => ({
42
+ kind: IDENTITY_SPLIT_KIND,
43
+ stored: [IDENTITY_SPLIT_KIND],
44
+ ownerOnly: true,
45
+ list: async (filter) => {
46
+ const status = storedStatus(filter);
47
+ const stored = await store.proposedActions.list({
48
+ kinds: [IDENTITY_SPLIT_KIND],
49
+ ...(status === undefined ? {} : { status }),
50
+ ...pushed(filter),
51
+ });
52
+ return kept(await Promise.all(stored.map(rowOf(store))), filter);
53
+ },
54
+ get: async (id) => rowOf(store)(await store.proposedActions.get(id)),
55
+ decide: async (id, { confirm, by, reason }) => {
56
+ const decided = await store.people.decideSplit(id, { confirm, by, ...(reason === undefined ? {} : { reason }) });
57
+ const person = decided.result?.person;
58
+ return {
59
+ id,
60
+ kind: IDENTITY_SPLIT_KIND,
61
+ status: confirm ? "confirmed" : "rejected",
62
+ made: person === undefined ? [] : [`person:${person}`],
63
+ };
64
+ },
65
+ });
@@ -6,6 +6,7 @@ import { factKind } from "./kinds/fact.js";
6
6
  import { invoiceKind, paymentKind } from "./kinds/finance.js";
7
7
  import { findingsKind } from "./kinds/findings.js";
8
8
  import { identityLinkKind } from "./kinds/identity-link.js";
9
+ import { identitySplitKind } from "./kinds/identity-split.js";
9
10
  import { keyDocumentKind } from "./kinds/key-document.js";
10
11
  import { mailFindingsKind } from "./kinds/mail-findings.js";
11
12
  import { meetingFindingsKind } from "./kinds/meeting-findings.js";
@@ -154,6 +155,7 @@ export const proposalRegistry = (store) => {
154
155
  taskCloseKind(store),
155
156
  sourceReviewKind(store),
156
157
  identityLinkKind(store),
158
+ identitySplitKind(store),
157
159
  ])
158
160
  registry.register(kind);
159
161
  registry.register(actionKind(store, registry.claimed));
@@ -5,15 +5,15 @@ import { calendarKey } from "../domain/calendar.js";
5
5
  import { rankingQuestion } from "../domain/rankings-options.js";
6
6
  import { MESSAGE_PARSING } from "../search/lucene/types.js";
7
7
  import { prepareLucene } from "./messages-search.js";
8
- const FIELDS = ["date", "chat", "kind"];
8
+ const FIELDS = ["date", "chat", "kind", "muted"];
9
9
  /** Per waiting chat, how far back its unanswered messages are counted. */
10
10
  export const WAITING_TAIL = 100;
11
- /** Only AND-ed `date:`, `chat:` and `kind:` terms: each becomes an index bound, so no query reads every message. */
11
+ /** Only AND-ed `date:`, `chat:`, `kind:` and `muted:` terms: each becomes an index bound, so no query reads every message. */
12
12
  const plainOnly = (text, command) => {
13
13
  if (text === undefined)
14
14
  return;
15
15
  const refuse = () => {
16
- throw new CliError("validation_error", `${command} reads date:, chat: and kind: terms, AND-ed — not words, other fields, OR or NOT`, { reason: "query.unsupported-field" });
16
+ throw new CliError("validation_error", `${command} reads date:, chat:, kind: and muted: terms, AND-ed — not words, other fields, OR or NOT`, { reason: "query.unsupported-field" });
17
17
  };
18
18
  const visit = (node) => {
19
19
  if (node.kind === "boolean")
@@ -40,6 +40,14 @@ const scopeOf = (root, accounts) => {
40
40
  scope.chats.push(chat);
41
41
  else if (node.field === "kind")
42
42
  scope.kinds.push(node.value.toLowerCase());
43
+ else if (node.field === "muted") {
44
+ const muted = node.value.toLowerCase() === "true";
45
+ if (scope.muted !== undefined && scope.muted !== muted)
46
+ throw new CliError("validation_error", "muted:true and muted:false cannot both hold", {
47
+ reason: "query.conflict",
48
+ });
49
+ scope.muted = muted;
50
+ }
43
51
  else if (date) {
44
52
  if (date.lower !== undefined) {
45
53
  const lower = date.lower + (date.lower_inclusive ? 0 : 1);
@@ -17,6 +17,8 @@ export interface TaskStatsRequest {
17
17
  export interface TaskStatsGroup {
18
18
  /** The stored chat id, `meeting:<account>/<meeting>`, or the project's store id. */
19
19
  group: string;
20
+ /** The group's account, when the answer reads several. */
21
+ account?: AccountKey;
20
22
  name: string | null;
21
23
  open: number;
22
24
  created: number;
@@ -27,6 +29,8 @@ export interface TaskStatsGroup {
27
29
  }
28
30
  export interface TaskStats {
29
31
  by: TaskStatsBy;
32
+ /** Every account read, when the answer reads several. */
33
+ accounts?: AccountKey[];
30
34
  open: number;
31
35
  created: number;
32
36
  closed: number;
@@ -36,6 +40,7 @@ export interface TaskStats {
36
40
  }
37
41
  /**
38
42
  * `stats tasks show`: `open` is open now, `created` the tasks opened in the period, `closed` those closed in it; the
39
- * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`.
43
+ * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`. Given several
44
+ * accounts it reads each one's tasks and counts them together; every row then names its account.
40
45
  */
41
- export declare const taskStatsOf: (store: MessageStore, account: AccountKey, { by, query, timezone, group, kind }: TaskStatsRequest, columns: ColumnMap, now?: number) => Promise<TaskStats>;
46
+ export declare const taskStatsOf: (store: MessageStore, accounts: AccountKey | readonly AccountKey[], { by, query, timezone, group, kind }: TaskStatsRequest, columns: ColumnMap, now?: number) => Promise<TaskStats>;
@@ -42,11 +42,16 @@ const and = (parts) => parts.length === 0
42
42
  : { sql: parts.map(({ sql }) => `(${sql})`).join(" AND "), params: parts.flatMap(({ params }) => params) };
43
43
  /**
44
44
  * `stats tasks show`: `open` is open now, `created` the tasks opened in the period, `closed` those closed in it; the
45
- * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`.
45
+ * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`. Given several
46
+ * accounts it reads each one's tasks and counts them together; every row then names its account.
46
47
  */
47
- export const taskStatsOf = async (store, account, { by = "chat", query, timezone, group, kind }, columns, now = Date.now()) => {
48
+ export const taskStatsOf = async (store, accounts, { by = "chat", query, timezone, group, kind }, columns, now = Date.now()) => {
48
49
  if (query)
49
50
  refuseNestedPeriod(query.root);
51
+ const several = Array.isArray(accounts);
52
+ const list = several
53
+ ? [...new Map(accounts.map((one) => [taskAccount(one), one])).values()]
54
+ : [accounts];
50
55
  const time = (sql) => ({ type: "time", sql });
51
56
  const read = { ...columns, [PERIOD_FIELD]: time("t.created_at"), closed: time("t.closed_at") };
52
57
  const fixed = [
@@ -56,17 +61,30 @@ export const taskStatsOf = async (store, account, { by = "chat", query, timezone
56
61
  ];
57
62
  const options = { command: "stats tasks show", now, ...(timezone === undefined ? {} : { zone: timezone }) };
58
63
  const where = (ast, more = []) => and([...fixed, ...more, ...(ast ? [queryFilter(ast, read, options)] : [])]);
59
- const scope = by === "project" ? { board: true } : { account: taskAccount(account) };
60
- const all = await store.tasks.statRows(scope, where(withoutField(query, PERIOD_FIELD)));
61
- const created = await store.tasks.statRows(scope, where(query));
62
- const closed = await store.tasks.statRows(scope, where(query && { ...query, root: renamed(query.root, PERIOD_FIELD, "closed") }, [
64
+ // Project tasks belong to no account: one board read, whatever the accounts.
65
+ const scopes = by === "project"
66
+ ? [{ scope: { board: true } }]
67
+ : list.map((one) => ({ account: one, scope: { account: taskAccount(one) } }));
68
+ const rowsOf = async (filter) => (await Promise.all(scopes.map(async ({ account, scope }) => (await store.tasks.statRows(scope, filter)).map((row) => (account ? { ...row, account } : row))))).flat();
69
+ const all = await rowsOf(where(withoutField(query, PERIOD_FIELD)));
70
+ const created = await rowsOf(where(query));
71
+ const closed = await rowsOf(where(query && { ...query, root: renamed(query.root, PERIOD_FIELD, "closed") }, [
63
72
  { sql: "t.closed_at IS NOT NULL", params: [] },
64
73
  ]));
65
- const keyOf = (row) => (by === "project" ? String(row.projectId) : (row.group ?? ""));
74
+ // Chat ids repeat across accounts, so a row is one account's chat.
75
+ const keyOf = (row) => by === "project" ? String(row.projectId) : `${row.account ? taskAccount(row.account) : ""}\t${row.group ?? ""}`;
66
76
  const groups = new Map();
67
77
  const slot = (row) => {
68
78
  const key = keyOf(row);
69
- const found = groups.get(key) ?? { open: [], created: 0, closeMs: [] };
79
+ const found = groups.get(key) ?? {
80
+ group: by === "project" ? String(row.projectId) : (row.group ?? ""),
81
+ ...(row.account ? { account: row.account } : {}),
82
+ first: row.createdAt,
83
+ open: [],
84
+ created: 0,
85
+ closeMs: [],
86
+ };
87
+ found.first = Math.min(found.first, row.createdAt);
70
88
  groups.set(key, found);
71
89
  return found;
72
90
  };
@@ -77,26 +95,26 @@ export const taskStatsOf = async (store, account, { by = "chat", query, timezone
77
95
  slot(row).created++;
78
96
  for (const row of closed)
79
97
  slot(row).closeMs.push((row.closedAt ?? row.createdAt) - row.createdAt);
80
- const kept = [...groups].filter(([, one]) => one.open.length + one.created + one.closeMs.length > 0);
81
- const ids = kept.map(([key]) => key);
82
- const names = by === "chat"
83
- ? await store.tasks.statNames("chat", ids, taskAccount(account))
84
- : by === "project"
85
- ? await store.tasks.statNames("project", ids)
86
- : await meetingNames(store, ids);
87
- const rows = kept.map(([key, one]) => ({
88
- group: key,
89
- name: names.get(key) ?? null,
98
+ const kept = [...groups.values()].filter((one) => one.open.length + one.created + one.closeMs.length > 0);
99
+ // Each account's rows come oldest first; across accounts the groups are put back in that order.
100
+ if (several)
101
+ kept.sort((a, b) => a.first - b.first);
102
+ const nameOf = await namesOf(store, by, kept);
103
+ const rows = kept.map((one) => ({
104
+ group: one.group,
105
+ ...(several && one.account ? { account: one.account } : {}),
106
+ name: nameOf(one) ?? null,
90
107
  open: one.open.length,
91
108
  created: one.created,
92
109
  closed: one.closeMs.length,
93
110
  ...(one.open[0] ? { oldestOpenAt: new Date(one.open[0].createdAt) } : {}),
94
111
  ...spread(one.open, one.closeMs, now),
95
112
  }));
96
- const open = kept.flatMap(([, one]) => one.open);
97
- const closeMs = kept.flatMap(([, one]) => one.closeMs);
113
+ const open = kept.flatMap((one) => one.open);
114
+ const closeMs = kept.flatMap((one) => one.closeMs);
98
115
  return {
99
116
  by,
117
+ ...(several ? { accounts: [...list] } : {}),
100
118
  open: open.length,
101
119
  created: created.length,
102
120
  closed: closeMs.length,
@@ -104,6 +122,21 @@ export const taskStatsOf = async (store, account, { by = "chat", query, timezone
104
122
  rows,
105
123
  };
106
124
  };
125
+ /** Each group's title: chats within their own account, meetings and projects by their store id. */
126
+ const namesOf = async (store, by, groups) => {
127
+ if (by === "project") {
128
+ const names = await store.tasks.statNames("project", groups.map(({ group }) => group));
129
+ return ({ group }) => names.get(group);
130
+ }
131
+ if (by === "meeting") {
132
+ const names = await meetingNames(store, groups.map(({ group }) => group));
133
+ return ({ group }) => names.get(group);
134
+ }
135
+ const byAccount = new Map();
136
+ for (const account of new Set(groups.flatMap(({ account }) => (account ? [taskAccount(account)] : []))))
137
+ byAccount.set(account, await store.tasks.statNames("chat", groups.filter((one) => one.account && taskAccount(one.account) === account).map(({ group }) => group), account));
138
+ return ({ group, account }) => (account ? byAccount.get(taskAccount(account))?.get(group) : undefined);
139
+ };
107
140
  const meetingIdOf = (group) => {
108
141
  try {
109
142
  return String(parseMeetingReference(group).meetingId);
@@ -179,6 +179,7 @@ export interface TasksService {
179
179
  /** `chat` narrows to one chat, by name or id; see `taskStatsOf` for what each count means. */
180
180
  stats(request?: Omit<TaskStatsRequest, "group"> & {
181
181
  chat?: string;
182
+ accounts?: readonly AccountKey[];
182
183
  }): Promise<TaskStats>;
183
184
  /** Title, description, due date and next check; `null` clears one. */
184
185
  plan(id: string, plan: TaskPlan, by: TaskOrigin): Promise<TaskCard>;
@@ -505,10 +505,22 @@ export const tasksService = (deps, categories) => {
505
505
  await owned(store, account, subject);
506
506
  return store.tasks.similar({ task: subject }, options);
507
507
  }),
508
- stats: ({ chat, ...request } = {}) => inStore(async (store, account) => {
509
- const group = await groupOf(store, account, chat);
510
- return taskStatsOf(store, account, { ...request, ...(group === undefined ? {} : { group }) }, await queryColumns(store, account, request.query));
511
- }),
508
+ stats: ({ chat, accounts, ...request } = {}) => accounts
509
+ ? (async () => {
510
+ const store = await deps.store();
511
+ const named = request.query
512
+ ? walkQuery(request.query.root).some(({ field, operator }) => field === "chat" && operator !== "wildcard")
513
+ : false;
514
+ if (chat !== undefined || named)
515
+ throw new CliError("validation_error", "a chat belongs to one account: name the account as well");
516
+ // No chat is named, so the columns need no account.
517
+ const columns = taskColumns(new Map(), await taskTagFilters(store, request.query));
518
+ return taskStatsOf(store, accounts, request, columns);
519
+ })()
520
+ : inStore(async (store, account) => {
521
+ const group = await groupOf(store, account, chat);
522
+ return taskStatsOf(store, account, { ...request, ...(group === undefined ? {} : { group }) }, await queryColumns(store, account, request.query));
523
+ }),
512
524
  };
513
525
  };
514
526
  const iso = (at) => (at === undefined ? null : at.toISOString());
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { MEETING_FINDINGS_KIND } from "../meetings/index.js";
3
3
  import { IDENTITY_LINK_KIND } from "./identity-links.js";
4
+ import { IDENTITY_SPLIT_KIND } from "./identity-splits.js";
4
5
  import { MAIL_FINDINGS_KIND } from "./mail-findings.js";
5
6
  import { SOURCE_REVIEW_KIND } from "./source-review.js";
6
7
  /** An agent's suggested close of a task: kept on the task, not in `proposed_actions`. */
@@ -14,7 +15,8 @@ export const isOwnerOnlyKind = (kind) => kind === MAIL_FINDINGS_KIND ||
14
15
  kind === MEETING_FINDINGS_KIND ||
15
16
  kind === TASK_CLOSE_KIND ||
16
17
  kind === SOURCE_REVIEW_KIND ||
17
- kind === IDENTITY_LINK_KIND;
18
+ kind === IDENTITY_LINK_KIND ||
19
+ kind === IDENTITY_SPLIT_KIND;
18
20
  /**
19
21
  * The one check every decide path runs before it confirms or rejects a proposal. `null` means allowed. Every Claude
20
22
  * Code session is the bot `claude-code`, so comparing bot names keeps one session from deciding another's proposal.
@@ -1,3 +1,4 @@
1
+ import { refuseOwnerStoreInTests } from "../path.js";
1
2
  import { loadVectorExtension, vectorExtension } from "../vector-extension.js";
2
3
  let customised = false;
3
4
  /**
@@ -33,6 +34,7 @@ export const bunDatabase = async () => {
33
34
  export const openWithBunSqlite = async (path) => cacheOverBunSqlite(await bunClient(path));
34
35
  /** A connection with the vector extension loaded; it closes again when the extension does not load. */
35
36
  export const bunClient = async (path, options) => {
37
+ refuseOwnerStoreInTests(path);
36
38
  const Database = await bunDatabase();
37
39
  const extension = await vectorExtension();
38
40
  const client = options ? new Database(path, options) : new Database(path);
@@ -1,6 +1,7 @@
1
1
  // biome-ignore-all lint/plugin/no-sqlite-driver: cli-core owns the store, so it opens the driver itself
2
2
  import { DatabaseSync } from "node:sqlite";
3
3
  import { beforeTimeLimit, TIME_LIMIT_FUNCTION, } from "../driver.js";
4
+ import { refuseOwnerStoreInTests } from "../path.js";
4
5
  import { loadVectorExtension, vectorExtension } from "../vector-extension.js";
5
6
  /**
6
7
  * Import this module only through a dynamic import that follows `quietSqliteWarning()`: a static import loads
@@ -9,6 +10,7 @@ import { loadVectorExtension, vectorExtension } from "../vector-extension.js";
9
10
  export const openWithNodeSqlite = async (path) => cacheOverNodeSqlite(await nodeClient(path));
10
11
  /** A connection with the vector extension loaded; it closes again when the extension does not load. */
11
12
  export const nodeClient = async (path, { readOnly = false } = {}) => {
13
+ refuseOwnerStoreInTests(path);
12
14
  const extension = await vectorExtension();
13
15
  const client = new DatabaseSync(path, { readOnly, allowExtension: true });
14
16
  try {
@@ -0,0 +1,60 @@
1
+ import type { Decider, Proposer } from "./decisions.js";
2
+ import type { Author } from "./sqlite/memories.js";
3
+ import type { IdentityRef } from "./types.js";
4
+ /**
5
+ * A stored kind of its own, not an `identity_link`: every reader of those takes a row for two people who may be one,
6
+ * and would settle a split of one person away as moot.
7
+ */
8
+ export declare const IDENTITY_SPLIT_KIND = "identity_split";
9
+ /** `unlink` moves the identities to one new person; `unmerge` gives a merge's identities back to their person. */
10
+ export type IdentitySplitMove = "unlink" | "unmerge";
11
+ /** An `identity_split` proposal's payload. */
12
+ export interface IdentitySplitPayload {
13
+ split: IdentitySplitMove;
14
+ /** The person the identities would leave, as a uid when it was proposed. */
15
+ person: string;
16
+ /** `provider:id` of each identity that would leave. */
17
+ identities: string[];
18
+ /** `merge:<to>-<from>` for an unmerge, `null` for an unlink. */
19
+ merge: string | null;
20
+ /** The person's identities when it was proposed, so a confirm after the person changed is refused. */
21
+ side: string;
22
+ evidence: string[];
23
+ }
24
+ /** Either the identities that leave, all of one person, or the merge to undo. */
25
+ export type IdentitySplitInput = ({
26
+ identities: IdentityRef[];
27
+ } | {
28
+ merge: string;
29
+ }) & {
30
+ by: Author;
31
+ reason: string;
32
+ evidence?: string[];
33
+ };
34
+ export interface IdentitySplitDecision {
35
+ confirm: boolean;
36
+ /** `"owner"` only on a path that established the owner decides; anyone else is refused. */
37
+ by: Decider;
38
+ reason?: string;
39
+ }
40
+ /** One `identity_split`, naming the person as they are now. */
41
+ export interface IdentitySplitRow {
42
+ id: string;
43
+ /** `dropped`: an older build approved it as a plain action, and nothing was split. */
44
+ status: "proposed" | "confirmed" | "rejected" | "dropped";
45
+ split: IdentitySplitMove;
46
+ /** `person:<uid>` the identities are on now. */
47
+ person: string;
48
+ identities: string[];
49
+ merge: string | null;
50
+ reason: string | null;
51
+ evidence: string[];
52
+ proposedBy: Proposer;
53
+ createdAt: string;
54
+ }
55
+ export interface IdentitySplitFilter {
56
+ /** `proposed` unless named. */
57
+ status?: IdentitySplitRow["status"] | "all";
58
+ limit: number;
59
+ offset: number;
60
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A stored kind of its own, not an `identity_link`: every reader of those takes a row for two people who may be one,
3
+ * and would settle a split of one person away as moot.
4
+ */
5
+ export const IDENTITY_SPLIT_KIND = "identity_split";
@@ -21,6 +21,7 @@ export { PRAGMAS } from "./driver.js";
21
21
  export { type CitableRecord, EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
22
22
  export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
23
23
  export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type MatchScan, } from "./identity-links.js";
24
+ export { IDENTITY_SPLIT_KIND, type IdentitySplitDecision, type IdentitySplitFilter, type IdentitySplitInput, type IdentitySplitMove, type IdentitySplitPayload, type IdentitySplitRow, } from "./identity-splits.js";
24
25
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
25
26
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
26
27
  export { clearDamageMark, type DamageMark, damageMarkPath, type HealthMark, healthMarkPath, type JournalMark, journalMarkPath, markStoreDamaged, readDamageMark, readHealthMark, readJournalMark, recordDeepCheck, } from "./marks.js";
@@ -48,7 +49,7 @@ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
48
49
  export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
49
50
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
50
51
  export type { ChatMetadata } from "./sqlite/chats.js";
51
- export { type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
52
+ export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId, } from "./sqlite/crm.js";
52
53
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, crmSettingKey, } from "./sqlite/crm-settings.js";
53
54
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
54
55
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
@@ -79,6 +80,7 @@ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from ".
79
80
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
80
81
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
81
82
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
83
+ export { DOUBT_REASONS, type DoubtIdentity, type DoubtReason, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
82
84
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
83
85
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
84
86
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -13,6 +13,7 @@ export { PRAGMAS } from "./driver.js";
13
13
  export { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "./evidence-findings.js";
14
14
  export { QUICK_HEALTH_CHECKS, storeHealth, } from "./health.js";
15
15
  export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, } from "./identity-links.js";
16
+ export { IDENTITY_SPLIT_KIND, } from "./identity-splits.js";
16
17
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
17
18
  export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
18
19
  export { clearDamageMark, damageMarkPath, healthMarkPath, journalMarkPath, markStoreDamaged, readDamageMark, readHealthMark, readJournalMark, recordDeepCheck, } from "./marks.js";
@@ -31,7 +32,7 @@ export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
31
32
  export { baseSettingKey } from "./sqlite/base-suggest.js";
32
33
  export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
33
34
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
34
- export { crmIdentityId } from "./sqlite/crm.js";
35
+ export { crmIdentityId, } from "./sqlite/crm.js";
35
36
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
36
37
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
37
38
  export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
@@ -40,6 +41,7 @@ export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js
40
41
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
41
42
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
42
43
  export { PEOPLE_SORTS, } from "./sqlite/people-list.js";
44
+ export { DOUBT_REASONS, } from "./sqlite/person-doubts.js";
43
45
  export { mergeId, parseMergeId } from "./sqlite/person-merges.js";
44
46
  export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
45
47
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
@@ -2,9 +2,11 @@ import type { Contact, Id, Page, PersonAlias, Provider } from "../domain/models.
2
2
  import type { PersonKind } from "../domain/person-kinds.js";
3
3
  import type { PeopleLookup } from "../resolve.js";
4
4
  import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
5
+ import type { IdentitySplitDecision, IdentitySplitFilter, IdentitySplitInput, IdentitySplitRow } from "./identity-splits.js";
5
6
  import type { ContactFilter } from "./sqlite/identities.js";
6
7
  import type { StoreContext } from "./sqlite/open.js";
7
8
  import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
9
+ import { type PersonDoubts } from "./sqlite/person-doubts.js";
8
10
  import type { PersonMerge } from "./sqlite/person-merges.js";
9
11
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
10
12
  import { type ShownBecause } from "./sqlite/person-ties.js";
@@ -98,6 +100,27 @@ export interface PeopleStore extends AccountPeople {
98
100
  items: IdentityLinkRow[];
99
101
  hasMore: boolean;
100
102
  }>;
103
+ /**
104
+ * Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides:
105
+ * an agent's unlink or unmerge waits for the owner beside the matches. An open one for the same identities is given
106
+ * back; one the owner turned down is refused.
107
+ */
108
+ proposeSplit(input: IdentitySplitInput): Promise<ProposedAction>;
109
+ /** The owner's decision on an `identity_split`; confirm is refused with `identity.stale` when the person changed. */
110
+ decideSplit(id: string, decision: IdentitySplitDecision): Promise<ProposedAction>;
111
+ /** The `identity_split` proposals, newest first; `proposed` unless `status` says. */
112
+ splitProposals(filter: IdentitySplitFilter): Promise<{
113
+ items: IdentitySplitRow[];
114
+ hasMore: boolean;
115
+ }>;
116
+ /**
117
+ * People that may be wrong, the owner first: the owner's person holding another name, test data, an address people
118
+ * with other names share, one person with different names and nothing in common. Each says why and how to fix it.
119
+ */
120
+ doubts(page: {
121
+ limit: number;
122
+ offset: number;
123
+ }): Promise<PersonDoubts>;
101
124
  /** The identity, and everyone linked with it, is the owner. */
102
125
  linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
103
126
  /** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
@@ -3,8 +3,10 @@ import { keysOver } from "./keys.js";
3
3
  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
+ import * as identitySplits from "./sqlite/identity-split-proposals.js";
6
7
  import { linkToOwner } from "./sqlite/own-identities.js";
7
8
  import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
9
+ import { personDoubts } from "./sqlite/person-doubts.js";
8
10
  import * as personLinks from "./sqlite/person-links.js";
9
11
  import { RULE, scanMatches } from "./sqlite/person-match-scan.js";
10
12
  import * as personMerges from "./sqlite/person-merges.js";
@@ -123,6 +125,10 @@ export const peopleStoreOver = (context, keyed) => {
123
125
  decideLink: async (id, decision) => identityProposals.decideIdentityLink(context, id, decision),
124
126
  scanMatches: async (options) => scanMatches(context, options),
125
127
  linkProposals: async (filter) => identityProposals.identityLinkRows(context, filter),
128
+ proposeSplit: async (input) => identitySplits.proposeIdentitySplit(context, input),
129
+ decideSplit: async (id, decision) => identitySplits.decideIdentitySplit(context, id, decision),
130
+ splitProposals: async (filter) => identitySplits.identitySplitRows(context, filter),
131
+ doubts: async (page) => personDoubts(context, page),
126
132
  linkToOwner: async (identity) => linkToOwner(context, identity),
127
133
  list: async (options) => listPeople(database, options),
128
134
  counts: async (query) => countPeople(database, query),
@@ -11,6 +11,13 @@ export declare const storedAccounts: ({ orm }: StoreContext) => StoredAccount[];
11
11
  export declare const storedAccount: ({ orm }: StoreContext, { provider, account }: AccountKey) => StoredAccount;
12
12
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
13
13
  export declare const purgeAccount: ({ orm, database, now }: StoreContext, accountKey: number) => void;
14
+ /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
15
+ export declare const OWN: Set<string>;
16
+ /**
17
+ * Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts.
18
+ * `among`, a subquery of ids, limits each arm to them, so each reads its index rather than its whole table.
19
+ */
20
+ export declare const referencesTo: (database: CacheDatabase, table: "identities" | "persons", skip: Set<string>, among?: string) => string;
14
21
  export declare const unreferenced: (database: CacheDatabase, table: "identities") => Set<number>;
15
22
  /**
16
23
  * People only the purged account had seen go with it. An identity stays while anything else points at it
@@ -3,6 +3,7 @@ import { and, asc, eq, inArray, sql } from "./drizzle/core.js";
3
3
  import { pointerPairs } from "./entity-types.js";
4
4
  import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
5
5
  import { forgetErasedLinks } from "./identity-link-rows.js";
6
+ import { forgetErasedSplits } from "./identity-split-proposals.js";
6
7
  import { mergeSql } from "./merged-persons.js";
7
8
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
8
9
  import { dropUnusedVectors } from "./vector-index.js";
@@ -149,17 +150,25 @@ export const purgeAccount = ({ orm, database, now }, accountKey) => {
149
150
  dropUnusedVectors(database, hashes);
150
151
  };
151
152
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
152
- const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
153
- /** Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts. */
154
- const referencesTo = (database, table, skip) => {
153
+ export const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
154
+ /**
155
+ * Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts.
156
+ * `among`, a subquery of ids, limits each arm to them, so each reads its index rather than its whole table.
157
+ */
158
+ export const referencesTo = (database, table, skip, among) => {
159
+ const within = (column) => (among === undefined ? "" : ` ${column} IN (${among})`);
155
160
  const keys = database
156
161
  .prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
157
162
  WHERE m.type = 'table' AND f."table" = ?`)
158
163
  .all(table)
159
164
  .filter((row) => !skip.has(String(row.tbl)))
160
- .map((row) => `SELECT "${String(row.col)}" AS id FROM "${String(row.tbl)}"`);
165
+ .map((row) => {
166
+ const column = `"${String(row.col)}"`;
167
+ return `SELECT ${column} AS id FROM "${String(row.tbl)}"${among === undefined ? "" : ` WHERE${within(column)}`}`;
168
+ });
161
169
  const type = table === "identities" ? "identity" : "person";
162
- const pointers = pointerPairs(database).map(({ table: tbl, pointer }) => `SELECT ${pointer}_id AS id FROM "${tbl}" WHERE ${pointer}_type = '${type}'`);
170
+ const pointers = pointerPairs(database).map(({ table: tbl, pointer }) => `SELECT ${pointer}_id AS id FROM "${tbl}" WHERE ${pointer}_type = '${type}'` +
171
+ (among === undefined ? "" : ` AND${within(`${pointer}_id`)}`));
163
172
  return [...keys, ...pointers].join(" UNION ");
164
173
  };
165
174
  export const unreferenced = (database, table) => new Set(database
@@ -200,9 +209,12 @@ export const dropOrphanPeople = (database, unseenBefore) => {
200
209
  database.prepare(`DELETE FROM ${table} WHERE identity_id IN (SELECT value FROM json_each(?))`).run(gone);
201
210
  database.prepare("DELETE FROM identities WHERE id IN (SELECT value FROM json_each(?))").run(gone);
202
211
  forgetErasedLinks(database);
212
+ forgetErasedSplits(database);
203
213
  database
204
214
  .prepare(`DELETE FROM persons WHERE id IN (SELECT value FROM json_each(?)) AND owner = 0
205
215
  AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = persons.id)
216
+ AND CAST(id AS TEXT) NOT IN (SELECT json_extract(payload, '$.person') FROM proposed_actions
217
+ WHERE kind = 'identity_split')
206
218
  AND id NOT IN (SELECT id FROM (${referencesTo(database, "persons", new Set(["identity_links"]))}) WHERE id IS NOT NULL)`)
207
219
  .run(JSON.stringify(persons));
208
220
  };
@@ -0,0 +1,26 @@
1
+ import type { AccountKey } from "../types.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** What removing a CRM account's contacts outside its scope did, or would do. */
4
+ export interface CrmContactsRemoved {
5
+ /** Contacts no kept deal, lead or company names, removed with their link to a person. */
6
+ contacts: number;
7
+ /** People those contacts made, deleted because nothing else was left on them. */
8
+ persons: number;
9
+ /** People those contacts were on that stay: another identity, a note, an alias, the owner's decision, a mention. */
10
+ personsKept: number;
11
+ /** People whose name still carried a CRM import's `null #<id>`, given the name without it. */
12
+ names: number;
13
+ }
14
+ export declare const withoutPlaceholder: (name: string) => string | null;
15
+ /**
16
+ * Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
17
+ * `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
18
+ * about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
19
+ * its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
20
+ * after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
21
+ */
22
+ export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
23
+ users?: readonly string[];
24
+ before: number;
25
+ dryRun?: boolean;
26
+ }) => CrmContactsRemoved;