@wirecat/cli-core 0.631.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 (46) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/calendar/mcp/index.d.ts +12 -12
  3. package/dist/cli/messenger/context.d.ts +2 -0
  4. package/dist/cli/messenger/reply-stats-command.js +1 -1
  5. package/dist/cli/messenger/serve-relay.d.ts +1 -0
  6. package/dist/cli/messenger/stats-answers.d.ts +5 -2
  7. package/dist/cli/messenger/stats-answers.js +8 -2
  8. package/dist/cli/messenger/tasks-command.js +5 -3
  9. package/dist/domain/test-data.d.ts +15 -0
  10. package/dist/domain/test-data.js +18 -0
  11. package/dist/entities/chat-stats.d.ts +2 -0
  12. package/dist/entities/chat-stats.js +2 -0
  13. package/dist/entities/index.d.ts +1 -0
  14. package/dist/errors/reasons.js +9 -0
  15. package/dist/kit/seed.js +6 -7
  16. package/dist/search/lucene/registry.js +11 -0
  17. package/dist/services/proposals/kinds/identity-split.d.ts +4 -0
  18. package/dist/services/proposals/kinds/identity-split.js +65 -0
  19. package/dist/services/proposals/registry.js +2 -0
  20. package/dist/services/reply-stats.js +11 -3
  21. package/dist/services/task-stats.d.ts +7 -2
  22. package/dist/services/task-stats.js +53 -20
  23. package/dist/services/tasks.d.ts +1 -0
  24. package/dist/services/tasks.js +16 -4
  25. package/dist/store/decisions.js +3 -1
  26. package/dist/store/drivers/bun-sqlite.js +2 -0
  27. package/dist/store/drivers/node-sqlite.js +2 -0
  28. package/dist/store/identity-splits.d.ts +60 -0
  29. package/dist/store/identity-splits.js +5 -0
  30. package/dist/store/index.d.ts +2 -0
  31. package/dist/store/index.js +2 -0
  32. package/dist/store/people.d.ts +23 -0
  33. package/dist/store/people.js +6 -0
  34. package/dist/store/sqlite/accounts.js +4 -0
  35. package/dist/store/sqlite/crm-contacts.js +5 -1
  36. package/dist/store/sqlite/identity-link-rows.d.ts +5 -0
  37. package/dist/store/sqlite/identity-link-rows.js +5 -3
  38. package/dist/store/sqlite/identity-split-proposals.d.ts +29 -0
  39. package/dist/store/sqlite/identity-split-proposals.js +195 -0
  40. package/dist/store/sqlite/lucene-fields.js +3 -0
  41. package/dist/store/sqlite/person-doubts.d.ts +36 -0
  42. package/dist/store/sqlite/person-doubts.js +229 -0
  43. package/dist/store/sqlite/proposed-actions.js +6 -0
  44. package/dist/store/sqlite/reply-times.d.ts +3 -1
  45. package/dist/store/sqlite/reply-times.js +11 -6
  46. package/package.json +1 -1
@@ -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";
@@ -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";
@@ -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),
@@ -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";
@@ -208,9 +209,12 @@ export const dropOrphanPeople = (database, unseenBefore) => {
208
209
  database.prepare(`DELETE FROM ${table} WHERE identity_id IN (SELECT value FROM json_each(?))`).run(gone);
209
210
  database.prepare("DELETE FROM identities WHERE id IN (SELECT value FROM json_each(?))").run(gone);
210
211
  forgetErasedLinks(database);
212
+ forgetErasedSplits(database);
211
213
  database
212
214
  .prepare(`DELETE FROM persons WHERE id IN (SELECT value FROM json_each(?)) AND owner = 0
213
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')
214
218
  AND id NOT IN (SELECT id FROM (${referencesTo(database, "persons", new Set(["identity_links"]))}) WHERE id IS NOT NULL)`)
215
219
  .run(JSON.stringify(persons));
216
220
  };
@@ -91,6 +91,9 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
91
91
  "AND from_type IN ('deal', 'lead') AND role IS NOT 'owner') OR (from_type = 'person' " +
92
92
  `AND from_id IN ${persons} AND kind = 'member-of' AND role = 'contact'))`)
93
93
  .run(accountId);
94
+ // A split names the identities that would leave, an address among them: it goes with them, whatever its status.
95
+ database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_split' AND EXISTS (SELECT 1 FROM json_each(payload, " +
96
+ `'$.identities') WHERE value IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
94
97
  database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_link' AND status = 'proposed' AND (" +
95
98
  `json_extract(payload, '$.identity') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}) ` +
96
99
  `OR json_extract(payload, '$.with') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
@@ -103,7 +106,8 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
103
106
  const proposed = "SELECT CAST(substr(value, 8) AS INTEGER) AS id FROM proposed_actions, json_each(json_array(" +
104
107
  "json_extract(payload, '$.from'), json_extract(payload, '$.to'))) WHERE value LIKE 'person:%' " +
105
108
  "UNION SELECT CAST(value AS INTEGER) FROM proposed_actions, json_each(payload, '$.persons') " +
106
- "WHERE json_type(payload, '$.persons') = 'array'";
109
+ "WHERE json_type(payload, '$.persons') = 'array' " +
110
+ "UNION SELECT CAST(json_extract(payload, '$.person') AS INTEGER) FROM proposed_actions WHERE kind = 'identity_split'";
107
111
  database.exec(`DELETE FROM temp.crm_persons WHERE id IN (SELECT id FROM persons WHERE owner <> 0) ` +
108
112
  "OR id IN (SELECT person_id FROM identity_links) " +
109
113
  `OR id IN (${personRefs}) OR id IN (${proposed})`);
@@ -9,6 +9,9 @@ export interface LinkRow {
9
9
  pair: [number, number] | undefined;
10
10
  }
11
11
  export declare const pairOf: (a: number | string, b: number | string) => string;
12
+ /** The identity a `provider:id` names, if the store still has it. */
13
+ export declare const pkOf: (database: CacheDatabase, ref: string) => number | undefined;
14
+ export declare const personOf: (database: CacheDatabase, identity: number | undefined) => number | undefined;
12
15
  /** The people a proposal's identities are on now; merges since may have moved either side. */
13
16
  export declare const currentPairOf: (database: CacheDatabase, payload: IdentityLinkPayload) => [number, number] | undefined;
14
17
  /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
@@ -38,6 +41,8 @@ export declare const linkIndex: (database: CacheDatabase) => {
38
41
  merged: (from: number, into: number) => void;
39
42
  };
40
43
  export type LinkIndex = ReturnType<typeof linkIndex>;
44
+ /** The identities on a person now, as one comparable string. */
45
+ export declare const sideOf: (database: CacheDatabase, person: number) => string;
41
46
  export declare const sidesOf: (database: CacheDatabase, a: number, b: number) => [string, string];
42
47
  /**
43
48
  * Brings open proposals up to date with the people they name: one whose two people are one now, whose identity a
@@ -1,14 +1,15 @@
1
1
  import { IDENTITY_LINK_KIND } from "../identity-links.js";
2
2
  import { currentPerson } from "./merged-persons.js";
3
3
  export const pairOf = (a, b) => [Number(a), Number(b)].sort((x, y) => x - y).join("-");
4
- const pkOf = (database, ref) => {
4
+ /** The identity a `provider:id` names, if the store still has it. */
5
+ export const pkOf = (database, ref) => {
5
6
  const at = ref.indexOf(":");
6
7
  const row = database
7
8
  .prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?")
8
9
  .get(ref.slice(0, at), ref.slice(at + 1));
9
10
  return row ? Number(row.id) : undefined;
10
11
  };
11
- const personOf = (database, identity) => {
12
+ export const personOf = (database, identity) => {
12
13
  if (identity === undefined)
13
14
  return undefined;
14
15
  const row = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
@@ -96,7 +97,8 @@ export const linkIndex = (database) => {
96
97
  },
97
98
  };
98
99
  };
99
- const sideOf = (database, person) => database
100
+ /** The identities on a person now, as one comparable string. */
101
+ export const sideOf = (database, person) => database
100
102
  .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
101
103
  .all(person)
102
104
  .map(({ identity_id }) => String(identity_id))
@@ -0,0 +1,29 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import { type IdentitySplitDecision, type IdentitySplitFilter, type IdentitySplitInput, type IdentitySplitRow } from "../identity-splits.js";
3
+ import type { StoreContext } from "./open.js";
4
+ import { type ProposedAction } from "./proposed-actions.js";
5
+ /**
6
+ * The identities the owner turned a split down for, by the person they are still on: the owner said they belong there.
7
+ * `people doubts` leaves them out. One that moved since counts no longer.
8
+ */
9
+ export declare const keptTogether: (database: CacheDatabase) => Map<number, Set<string>>;
10
+ /**
11
+ * Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides. An
12
+ * open proposal for the same identities is given back instead of a second, brought up to date with the person as it
13
+ * is now and with the new evidence added, so proposing again is how a stale one is renewed; its first reason and
14
+ * proposer stay. An identity the owner kept on this person by turning a split down is refused.
15
+ */
16
+ export declare const proposeIdentitySplit: (context: StoreContext, input: IdentitySplitInput) => ProposedAction;
17
+ /**
18
+ * Decides an `identity_split`, the owner's alone. Confirm carries it out as the owner's own unlink or unmerge, so no
19
+ * automatic match joins them again; it is refused with `identity.stale` when the person changed since it was proposed.
20
+ * Only a waiting proposal is carried out: one an older build approved as a plain action stays as it is.
21
+ */
22
+ export declare const decideIdentitySplit: (context: StoreContext, id: string, decision: IdentitySplitDecision) => ProposedAction;
23
+ /** The `identity_split` proposals, newest first, each naming the person as they are now. */
24
+ export declare const identitySplitRows: (context: StoreContext, { status, limit, offset }: IdentitySplitFilter) => {
25
+ items: IdentitySplitRow[];
26
+ hasMore: boolean;
27
+ };
28
+ /** Deletes every `identity_split` that names an identity no longer in the store: its payload names the address. */
29
+ export declare const forgetErasedSplits: (database: CacheDatabase) => void;