@wirecat/cli-core 0.676.0 → 0.678.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 +47 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/background/report/render.d.ts +3 -1
  4. package/dist/background/report/render.js +2 -2
  5. package/dist/background/report/schema.d.ts +7 -4
  6. package/dist/background/report/schema.js +23 -7
  7. package/dist/background/report/templates/morning-digest.email.en.liquid +3 -2
  8. package/dist/background/report/templates/morning-digest.email.ru.liquid +3 -2
  9. package/dist/background/report/templates/morning-digest.telegram.en.liquid +3 -2
  10. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +3 -2
  11. package/dist/background/report/templates/morning-digest.text.en.liquid +3 -2
  12. package/dist/background/report/templates/morning-digest.text.ru.liquid +3 -2
  13. package/dist/background/report/view.js +2 -0
  14. package/dist/background/schedules.js +21 -11
  15. package/dist/cli/command-runs.d.ts +2 -0
  16. package/dist/cli/command-runs.js +2 -0
  17. package/dist/cli/index.d.ts +1 -1
  18. package/dist/cli/index.js +1 -1
  19. package/dist/cli/list-query.d.ts +1 -1
  20. package/dist/cli/list-query.js +2 -2
  21. package/dist/cli/setup-command.js +5 -2
  22. package/dist/crm/cli/activities.d.ts +17 -0
  23. package/dist/crm/cli/activities.js +133 -0
  24. package/dist/crm/cli/changes.d.ts +23 -0
  25. package/dist/crm/cli/changes.js +255 -0
  26. package/dist/crm/cli/index.d.ts +1 -0
  27. package/dist/crm/cli/index.js +7 -4
  28. package/dist/crm/digest.d.ts +27 -0
  29. package/dist/crm/digest.js +166 -0
  30. package/dist/crm/stage-tasks.d.ts +1 -1
  31. package/dist/crm/stage-tasks.js +1 -1
  32. package/dist/crm/sync.d.ts +9 -0
  33. package/dist/crm/sync.js +27 -0
  34. package/dist/crm/testing/source.d.ts +5 -1
  35. package/dist/crm/testing/source.js +19 -0
  36. package/dist/crm/testing/sync-contract.d.ts +2 -0
  37. package/dist/crm/testing/sync-contract.js +56 -2
  38. package/dist/errors/reasons.js +1 -0
  39. package/dist/store/identity-links.d.ts +73 -0
  40. package/dist/store/identity-links.js +14 -0
  41. package/dist/store/index.d.ts +3 -1
  42. package/dist/store/index.js +2 -1
  43. package/dist/store/people.d.ts +23 -1
  44. package/dist/store/people.js +12 -1
  45. package/dist/store/sqlite/agent-links.d.ts +34 -0
  46. package/dist/store/sqlite/agent-links.js +184 -0
  47. package/dist/store/sqlite/crm-activities.d.ts +41 -1
  48. package/dist/store/sqlite/crm-activities.js +152 -14
  49. package/dist/store/sqlite/crm-changes.d.ts +84 -0
  50. package/dist/store/sqlite/crm-changes.js +199 -0
  51. package/dist/store/sqlite/crm.d.ts +2 -1
  52. package/dist/store/sqlite/crm.js +2 -0
  53. package/dist/store/sqlite/identity-proposals.d.ts +2 -0
  54. package/dist/store/sqlite/identity-proposals.js +2 -0
  55. package/dist/store/sqlite/person-match-scan.d.ts +29 -0
  56. package/dist/store/sqlite/person-match-scan.js +4 -4
  57. package/dist/store/sqlite/person-merges.d.ts +3 -0
  58. package/package.json +1 -1
@@ -4,7 +4,7 @@ const DAY = 86_400_000;
4
4
  /**
5
5
  * Opens the owner's task for each stage a deal or lead of the account entered that its `stage-tasks` setting names:
6
6
  * one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
7
- * Answers how many it opened.
7
+ * Answers how many it opened. `now` is the sync's start: the tasks then fall in the digest window that sync closes.
8
8
  */
9
9
  export const openStageTasks = async (store, account, now, { history = false } = {}) => {
10
10
  const rules = await store.crm.stageTasks(account);
@@ -127,6 +127,15 @@ export declare const crmGapsOf: (store: MessageStore, account: AccountKey) => Pr
127
127
  * `--rescan`.
128
128
  */
129
129
  export declare const syncCrm: (source: CrmSource, store: MessageStore, account: AccountKey, options?: CrmSyncOptions) => Promise<CrmSyncReport>;
130
+ /** The sync state the last failed `sync` leaves, `{ at, kinds }`; a sync with no failed kind clears it. */
131
+ export declare const SYNC_FAILED = "crm:sync-failed";
132
+ /**
133
+ * The sync state holding when the last complete `sync` started: everything the CRM changed before it is in the copy,
134
+ * so the digest's window ends there.
135
+ */
136
+ export declare const SYNCED_FROM = "crm:synced-from";
137
+ /** `syncCrm`, leaving how it ended for the digest's health: the kinds that failed, or none. */
138
+ export declare const syncRecorded: (...args: Parameters<typeof syncCrm>) => ReturnType<typeof syncCrm>;
130
139
  /** Each kind's sync in the WC-LIFE-14 shape: `cursor_age_ms` growing on a `partial` one means nothing moves it. */
131
140
  export declare const crmStatus: (store: MessageStore, account: AccountKey, { profile, now, kinds }: {
132
141
  profile: string;
package/dist/crm/sync.js CHANGED
@@ -699,6 +699,33 @@ export const syncCrm = async (source, store, account, options = {}) => {
699
699
  report.groupHint = groupHint;
700
700
  return report;
701
701
  };
702
+ /** The sync state the last failed `sync` leaves, `{ at, kinds }`; a sync with no failed kind clears it. */
703
+ export const SYNC_FAILED = "crm:sync-failed";
704
+ /**
705
+ * The sync state holding when the last complete `sync` started: everything the CRM changed before it is in the copy,
706
+ * so the digest's window ends there.
707
+ */
708
+ export const SYNCED_FROM = "crm:synced-from";
709
+ /** `syncCrm`, leaving how it ended for the digest's health: the kinds that failed, or none. */
710
+ export const syncRecorded = async (...args) => {
711
+ const [, store, account, options] = args;
712
+ const at = options?.now ?? Date.now();
713
+ const record = (kinds) => store.sync
714
+ .setSyncState(account, SYNC_FAILED, kinds.length ? JSON.stringify({ at, kinds }) : "")
715
+ .catch(() => undefined);
716
+ try {
717
+ const report = await syncCrm(...args);
718
+ const failed = report.synced.filter((one) => one.error !== undefined).map((one) => one.kind);
719
+ await record(failed);
720
+ if (report.state === "complete" && !failed.length)
721
+ await store.sync.setSyncState(account, SYNCED_FROM, String(at));
722
+ return report;
723
+ }
724
+ catch (error) {
725
+ await record(["all"]);
726
+ throw error;
727
+ }
728
+ };
702
729
  /** Each kind's sync in the WC-LIFE-14 shape: `cursor_age_ms` growing on a `partial` one means nothing moves it. */
703
730
  export const crmStatus = async (store, account, { profile, now, kinds = CRM_KINDS }) => {
704
731
  const saved = await store.crm.scope(account);
@@ -1,4 +1,4 @@
1
- import type { CrmField, CrmItem, CrmKind, CrmOrganization, CrmPerson, CrmPipeline, CrmRecords } from "../../domain/crm.js";
1
+ import type { CrmActivity, CrmField, CrmItem, CrmKind, CrmOrganization, CrmPerson, CrmPipeline, CrmRecords, CrmStageEntry } from "../../domain/crm.js";
2
2
  import type { DealKind } from "../../domain/deals.js";
3
3
  import type { CrmLiveKind, CrmSource, CrmSourceTraits } from "../source.js";
4
4
  import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
@@ -14,6 +14,10 @@ export interface FakeCrmSourceOptions {
14
14
  admin?: boolean;
15
15
  /** The contacts and companies `ownClients()` counts as the sign-in's own; with it, the fake has `ownClients`. */
16
16
  ownClients?: Partial<Record<CrmLiveKind, readonly string[]>>;
17
+ /** Gives the fake `stageHistory()` over these entries, the array read on each call so a test may add to it. */
18
+ stageHistory?: CrmStageEntry[];
19
+ /** Gives the fake `activities()` over these, the array read on each call, by `updatedAt` after `since`. */
20
+ activities?: CrmActivity[];
17
21
  }
18
22
  /** One write the fake CRM was sent, in order. */
19
23
  export interface FakeCrmWrite {
@@ -246,6 +246,25 @@ export const fakeCrmSource = (options = {}) => {
246
246
  return answer;
247
247
  },
248
248
  ...(options.admin === undefined ? {} : { isAdmin: async () => options.admin }),
249
+ ...(options.stageHistory === undefined
250
+ ? {}
251
+ : {
252
+ stageHistory: async (kind, since, after) => {
253
+ const all = options.stageHistory;
254
+ const from = after === undefined ? -1 : all.findIndex((one) => one.externalId === after);
255
+ const items = all.filter((one, at) => one.kind === kind && at > from && (after !== undefined || one.at >= since));
256
+ return { items, hasMore: false, cursor: items.at(-1)?.externalId ?? after ?? null };
257
+ },
258
+ }),
259
+ ...(options.activities === undefined
260
+ ? {}
261
+ : {
262
+ activities: async (since) => {
263
+ const items = options.activities.filter((one) => one.updatedAt > since);
264
+ const newest = Math.max(since, ...items.map((one) => one.updatedAt));
265
+ return { items, hasMore: false, cursor: String(newest) };
266
+ },
267
+ }),
249
268
  ...(options.ownClients === undefined
250
269
  ? {}
251
270
  : {
@@ -6,6 +6,8 @@ import type { CrmSourceTraits } from "../source.js";
6
6
  export interface CrmSyncFixture {
7
7
  store: MessageStore;
8
8
  account: AccountKey;
9
+ /** Turns the account's `activities` setting on, as `config set` does; without it the activity case is left out. */
10
+ activitiesOn?: () => Promise<void>;
9
11
  }
10
12
  /** Both ways a CRM may report deletions: the engine must handle each. */
11
13
  export declare const CRM_TRAIT_COMBINATIONS: readonly Pick<CrmSourceTraits, "removedInChanges">[];
@@ -12,12 +12,12 @@ const DAY = 86_400_000;
12
12
  export const crmSyncContract = (make) => CRM_TRAIT_COMBINATIONS.flatMap((traits) => {
13
13
  const label = traits.removedInChanges ? "(deletions in changes)" : "(deletions by id pass)";
14
14
  let now = Date.now();
15
- const test = (name, check) => ({
15
+ const test = (name, check, fake = {}) => ({
16
16
  name: `${name} ${label}`,
17
17
  async run() {
18
18
  now = Date.now();
19
19
  const fixture = await make();
20
- const source = fakeCrmSource({ traits });
20
+ const source = fakeCrmSource({ traits, ...fake });
21
21
  const sync = (options = {}) => syncCrm(source, fixture.store, fixture.account, { now, ...options });
22
22
  const deals = async () => (await fixture.store.deals.list({ account: fixture.account, kind: "deal" })).items
23
23
  .map(({ externalId }) => externalId)
@@ -169,6 +169,60 @@ export const crmSyncContract = (make) => CRM_TRAIT_COMBINATIONS.flatMap((traits)
169
169
  const person = await store.people.personOf({ provider: "email", id: "person@example.com" });
170
170
  assert.equal(deal?.people[0]?.ref, `person:${person?.uid}`);
171
171
  }),
172
+ test("a stage entry on a deal the copy does not hold yet counts once the deal arrives", async ({ source, sync, store, account }) => {
173
+ await sync();
174
+ source.put("deal", exampleDeal("d9", { stage: "won" }));
175
+ await sync();
176
+ const { items: [deal], } = await store.deals.list({ account });
177
+ assert.deepEqual((await store.deals.stages(deal?.ref)).map(({ to, exact }) => [to, exact]), [["Quote sent", true]]);
178
+ }, {
179
+ stageHistory: [
180
+ {
181
+ externalId: "h1",
182
+ kind: "deal",
183
+ item: "d9",
184
+ pipeline: SALES_PIPELINE.externalId,
185
+ stage: "quote",
186
+ at: Date.now() - DAY,
187
+ },
188
+ ],
189
+ }),
190
+ test("an activity on a contact the copy holds is kept, and one on a contact it does not hold is not", async ({ source, sync, store, account, activitiesOn }) => {
191
+ if (!activitiesOn)
192
+ return;
193
+ await activitiesOn();
194
+ source.put("person", examplePerson("p1"));
195
+ await sync();
196
+ const { items } = await store.crm.activities(account, { limit: 10, offset: 0 });
197
+ assert.deepEqual(items.map(({ externalId, on }) => [externalId, on.map((one) => one.kind)]), [["a1", ["person"]]]);
198
+ }, {
199
+ activities: [
200
+ {
201
+ externalId: "a1",
202
+ kind: "call",
203
+ subject: "Example call",
204
+ body: null,
205
+ dueAt: null,
206
+ done: false,
207
+ assignee: null,
208
+ createdAt: 1,
209
+ updatedAt: Date.now(),
210
+ on: [{ kind: "person", externalId: "p1" }],
211
+ },
212
+ {
213
+ externalId: "a2",
214
+ kind: "call",
215
+ subject: "Example call elsewhere",
216
+ body: null,
217
+ dueAt: null,
218
+ done: false,
219
+ assignee: null,
220
+ createdAt: 1,
221
+ updatedAt: Date.now(),
222
+ on: [{ kind: "person", externalId: "elsewhere" }],
223
+ },
224
+ ],
225
+ }),
172
226
  test("a cancelled run stops and keeps what it saved", async ({ source, sync, deals }) => {
173
227
  seeded(source, 4);
174
228
  const controller = new AbortController();
@@ -549,6 +549,7 @@ const OTHERS = [
549
549
  "the owner rejected linking these people on this evidence; only a new signal or identity proposes them again",
550
550
  ],
551
551
  validation("identity.same", "the two identities are one person already"),
552
+ validation("identity.agent-unnamed", "an agent's link names the agent, and never as the owner"),
552
553
  validation("identity.not-shared", "only a match on a shared mailbox can say the mailbox is a company's"),
553
554
  ["organization.not-found", "not_found", "no stored organization has that id"],
554
555
  validation("organization.unnamed", "a free mailbox names no company; name the organization or the company"),
@@ -32,6 +32,79 @@ export interface IdentityLinkPayload {
32
32
  shared?: SharedMailbox;
33
33
  /** The shared mailbox's address, with `shared`. */
34
34
  mailbox?: string;
35
+ /** What the store found between the two people when an agent linked them, and whether it was strong. */
36
+ strength?: LinkEvidence;
37
+ /** The agent's run (`meta.run_id`) that linked them. */
38
+ run?: string;
39
+ /** `agent`: an agent's link the store applied at once on strong evidence; the row records it, decided. */
40
+ applied?: "agent";
41
+ }
42
+ /**
43
+ * Why a shared phone or address is not strong enough for an agent to merge on: an office's number, more people have
44
+ * it, a company's line or mailbox, a role or no-reply address, only one source gives it, or for a phone no source that
45
+ * keeps its user's own number (a CRM's or a card's is someone's word, NEED-2445).
46
+ */
47
+ export declare const LINK_WEAKNESSES: readonly ["landline", "shared", "company", "role-address", "no-reply", "one-source", "not-own-number"];
48
+ export type LinkWeakness = (typeof LINK_WEAKNESSES)[number];
49
+ /** A phone or address both people hold. */
50
+ export interface LinkFact {
51
+ kind: "phone" | "email";
52
+ /** E.164 for a phone, lower case for an address. */
53
+ value: string;
54
+ /** `provider:id` of the identities that hold it, on each of the two people. */
55
+ holders: [string[], string[]];
56
+ /** How many other people hold it. */
57
+ others: number;
58
+ strong: boolean;
59
+ weak: LinkWeakness | null;
60
+ }
61
+ /**
62
+ * Why an agent's link did not merge at once: the evidence is weak (`LinkWeakness`), they share no phone or address
63
+ * (`nothing-shared`), one is the owner's person, the owner rejected the pair before, or the owner's setting says
64
+ * agents only propose.
65
+ */
66
+ export type LinkHold = LinkWeakness | "nothing-shared" | "owner" | "rejected" | "propose-only";
67
+ /**
68
+ * What the store finds between two people, never what an agent says. Strong is one value that is a mobile number or a
69
+ * personal address, that only these two people hold, from two different sources, and for a phone at least one that
70
+ * keeps its user's own number: a messenger account or a call's number.
71
+ */
72
+ export interface LinkEvidence {
73
+ /** `person:<uid>` of each. */
74
+ persons: [string, string];
75
+ strong: boolean;
76
+ facts: LinkFact[];
77
+ /** `null` when strong. */
78
+ weak: LinkHold | null;
79
+ }
80
+ export interface AgentLinkInput {
81
+ identity: IdentityRef;
82
+ with: IdentityRef;
83
+ /** The agent's name, as `whoRuns` gives it. */
84
+ bot: string;
85
+ run?: string;
86
+ reason: string;
87
+ /** False when the owner's setting says agents only propose. */
88
+ apply: boolean;
89
+ }
90
+ export type AgentLink = {
91
+ outcome: "merged";
92
+ person: string;
93
+ merge: string;
94
+ proposal: string;
95
+ evidence: LinkEvidence;
96
+ } | {
97
+ outcome: "proposed";
98
+ proposal: string;
99
+ evidence: LinkEvidence;
100
+ };
101
+ /** An agent's merge still in place, newest first: what the owner sees to undo. */
102
+ export interface AgentMerge {
103
+ proposal: string;
104
+ bot: string;
105
+ run: string | null;
106
+ reason: string | null;
107
+ evidence: LinkEvidence | null;
35
108
  }
36
109
  export interface IdentityLinkInput {
37
110
  identity: IdentityRef;
@@ -5,3 +5,17 @@ export const IDENTITY_LINK_KIND = "identity_link";
5
5
  * an account the owner connected carries another name than the owner's (`account`).
6
6
  */
7
7
  export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email", "name", "account"];
8
+ /**
9
+ * Why a shared phone or address is not strong enough for an agent to merge on: an office's number, more people have
10
+ * it, a company's line or mailbox, a role or no-reply address, only one source gives it, or for a phone no source that
11
+ * keeps its user's own number (a CRM's or a card's is someone's word, NEED-2445).
12
+ */
13
+ export const LINK_WEAKNESSES = [
14
+ "landline",
15
+ "shared",
16
+ "company",
17
+ "role-address",
18
+ "no-reply",
19
+ "one-source",
20
+ "not-own-number",
21
+ ];
@@ -20,7 +20,7 @@ export type { CacheDatabase, CacheStatement, OpenDatabase, SqlValue } from "./dr
20
20
  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
- export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type MatchScan, type SharedMailbox, } from "./identity-links.js";
23
+ export { type AgentLink, type AgentLinkInput, type AgentMerge, IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, LINK_WEAKNESSES, type LinkEvidence, type LinkFact, type LinkHold, type LinkWeakness, type MatchScan, type SharedMailbox, } from "./identity-links.js";
24
24
  export { IDENTITY_SPLIT_KIND, type IdentitySplitDecision, type IdentitySplitFilter, type IdentitySplitInput, type IdentitySplitMove, type IdentitySplitPayload, type IdentitySplitRow, } from "./identity-splits.js";
25
25
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
26
26
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
@@ -51,6 +51,8 @@ export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogSto
51
51
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
52
52
  export type { ChatMetadata } from "./sqlite/chats.js";
53
53
  export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId, } from "./sqlite/crm.js";
54
+ export type { ActivityFilter, ActivityTarget, ListedActivity } from "./sqlite/crm-activities.js";
55
+ export { type ChangeFilter, CRM_CHANGES, type CrmChange, type CrmChangeKind } from "./sqlite/crm-changes.js";
54
56
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
55
57
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
56
58
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
@@ -12,7 +12,7 @@ export { applyDocumentTransfer, previewDocumentTransfer } from "./document-trans
12
12
  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
- export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, } from "./identity-links.js";
15
+ export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, LINK_WEAKNESSES, } from "./identity-links.js";
16
16
  export { IDENTITY_SPLIT_KIND, } from "./identity-splits.js";
17
17
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
18
18
  export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
@@ -34,6 +34,7 @@ export { baseSettingKey } from "./sqlite/base-suggest.js";
34
34
  export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
35
35
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
36
36
  export { crmIdentityId, } from "./sqlite/crm.js";
37
+ export { CRM_CHANGES } from "./sqlite/crm-changes.js";
37
38
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
38
39
  export { DOCUMENT_KINDS, } from "./sqlite/document-listing.js";
39
40
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
@@ -2,7 +2,7 @@ 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 { Decider } from "./decisions.js";
5
- import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
5
+ import type { AgentLink, AgentLinkInput, AgentMerge, IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, LinkEvidence, MatchScan } from "./identity-links.js";
6
6
  import type { IdentitySplitDecision, IdentitySplitFilter, IdentitySplitInput, IdentitySplitRow } from "./identity-splits.js";
7
7
  import type { ContactFilter } from "./sqlite/identities.js";
8
8
  import { type IdentityRekey, type IdentityRekeys } from "./sqlite/identity-rekey.js";
@@ -100,6 +100,28 @@ export interface PeopleStore extends AccountPeople {
100
100
  * owner's separation or rejection; an open proposal for the same two people is given back instead of a second.
101
101
  */
102
102
  proposeLink(input: IdentityLinkInput): Promise<ProposedAction>;
103
+ /**
104
+ * An agent's link. It merges at once only on strong evidence the store finds itself, never on the agent's word:
105
+ * one value only these two people hold, a mobile number or a personal address, from two different sources, and for a
106
+ * phone at least one that keeps its user's own number (a messenger account or a call's number; NEED-2445, NEED-2600).
107
+ * A landline, a value more people share, a company's line, a role address, a name or a CRM's word alone is weak. The
108
+ * merge is recorded as an `identity_link` the agent decided, with the evidence, the reason and the run, and the owner
109
+ * undoes it with `undoMerge`. Weak evidence, the owner's person, a pair the owner rejected, or `apply: false` (the
110
+ * owner's setting) open a proposal instead, which says why. Refused over the owner's separation.
111
+ */
112
+ agentLink(input: AgentLinkInput): Promise<AgentLink>;
113
+ /** What two people share and whether it is strong, for each pair of `person:<uid>` or uids; reads the store once. */
114
+ linkEvidence(pairs: readonly (readonly [string, string])[]): Promise<LinkEvidence[]>;
115
+ /** The merges agents made that are still in place, newest first. */
116
+ agentMerges(page: {
117
+ limit: number;
118
+ offset: number;
119
+ }): Promise<{
120
+ items: (PersonMerge & {
121
+ agent: AgentMerge;
122
+ })[];
123
+ hasMore: boolean;
124
+ }>;
103
125
  /**
104
126
  * The owner's decision on an `identity_link`; confirm is refused with `identity.stale` when either person changed.
105
127
  * `company` turns down a shared-mailbox proposal and gives its address to an organization (NEED-2528);
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { keysOver } from "./keys.js";
3
3
  import { ownerPerson } from "./sqlite/actors.js";
4
+ import { agentLink, agentMergeOf, agentMerges, linkEvidenceOver } from "./sqlite/agent-links.js";
4
5
  import * as identities from "./sqlite/identities.js";
5
6
  import * as identityProposals from "./sqlite/identity-proposals.js";
6
7
  import { rekeyIdentities } from "./sqlite/identity-rekey.js";
@@ -131,10 +132,20 @@ export const peopleStoreOver = (context, keyed) => {
131
132
  linkPhones(context, new Set(done.touched));
132
133
  return done;
133
134
  },
134
- merges: async (uid) => personMerges.merges(context, uid),
135
+ merges: async (uid) => personMerges.merges(context, uid).map((merge) => {
136
+ const agent = merge.method === "agent" ? agentMergeOf(context, merge.id) : undefined;
137
+ return agent === undefined ? merge : { ...merge, agent };
138
+ }),
135
139
  undoMerge: async (to, from, by) => write(database, () => personMerges.undoMerge(context, to, from, by)),
136
140
  split: async (uid, chosen, by) => write(database, () => personMerges.split(context, uid, chosen, by)),
137
141
  proposeLink: async (input) => identityProposals.proposeIdentityLink(context, input),
142
+ agentLink: async (input) => agentLink(context, input),
143
+ linkEvidence: async (pairs) => {
144
+ const evidence = linkEvidenceOver(context);
145
+ const uid = (person) => Number(person.replace(/^person:/, ""));
146
+ return pairs.map(([a, b]) => evidence(uid(a), uid(b)));
147
+ },
148
+ agentMerges: async (page) => agentMerges(context, page),
138
149
  decideLink: async (id, decision) => identityProposals.decideIdentityLink(context, id, decision),
139
150
  scanMatches: async (options) => scanMatches(context, options),
140
151
  linkProposals: async (filter) => identityProposals.identityLinkRows(context, filter),
@@ -0,0 +1,34 @@
1
+ import { type AgentLink, type AgentLinkInput, type AgentMerge, type LinkEvidence } from "../identity-links.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /**
4
+ * Reads every phone and address once, then answers for any number of pairs of people: what they share, and whether it
5
+ * is strong enough for an agent to merge them.
6
+ */
7
+ export declare const linkEvidenceOver: (context: StoreContext) => ((a: number, b: number) => LinkEvidence);
8
+ /**
9
+ * An agent's link: merged at once on strong evidence the store finds itself, recorded as an `identity_link` decided by
10
+ * the agent, with the evidence, its reason and its run; otherwise it waits for the owner as a proposal, which says why
11
+ * it is not strong. Refused over the owner's separation, as any agent's link is.
12
+ */
13
+ export declare const agentLink: (context: StoreContext, input: AgentLinkInput) => AgentLink;
14
+ /** Who merged, why and in which run, for a merge an agent made; `undefined` for any other. */
15
+ export declare const agentMergeOf: (context: StoreContext, merge: string) => AgentMerge | undefined;
16
+ /** The merges agents made that are still in place, newest first: what the owner may want to undo. */
17
+ export declare const agentMerges: (context: StoreContext, { limit, offset }: {
18
+ limit: number;
19
+ offset: number;
20
+ }) => {
21
+ items: {
22
+ id: string;
23
+ from: string;
24
+ to: string;
25
+ identities: (import("../types.js").IdentityRef & {
26
+ name: string | null;
27
+ })[];
28
+ method: string;
29
+ by: string;
30
+ at: string;
31
+ agent: AgentMerge;
32
+ }[];
33
+ hasMore: boolean;
34
+ };
@@ -0,0 +1,184 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
3
+ import { isMobilePhone } from "../../domain/phones.js";
4
+ import { IDENTITY_LINK_KIND, } from "../identity-links.js";
5
+ import { rejectedEvidence, sidesOf } from "./identity-link-rows.js";
6
+ import { openIdentityLink } from "./identity-proposals.js";
7
+ import { isOwner, mergePerson, recordOf, required, survivorOf } from "./person-links.js";
8
+ import { emailHolders, phoneHolders, phonePairJoins, sharedLine, } from "./person-match-scan.js";
9
+ import { mergeId, merges } from "./person-merges.js";
10
+ import { resolvePersonLinks } from "./person-resolution.js";
11
+ import { separated } from "./person-separation.js";
12
+ import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
13
+ import { write } from "./transaction.js";
14
+ /** An agent's merge moves identities as `agent:<name>`, never as a bare name an agent could set to `owner`. */
15
+ const AGENT_METHOD = "agent";
16
+ const personsOf = ({ database }) => new Map(database
17
+ .prepare("SELECT identity_id, person_id FROM identity_links")
18
+ .all()
19
+ .map((row) => [Number(row.identity_id), Number(row.person_id)]));
20
+ const weaknessOf = (context, kind, value, holders, sides, others) => {
21
+ if (kind === "email" && isNoReplyAddress(value))
22
+ return "no-reply";
23
+ if (kind === "email" && isRoleAddress(value))
24
+ return "role-address";
25
+ if (sharedLine(context, holders))
26
+ return "company";
27
+ if (others > 0)
28
+ return "shared";
29
+ if (kind === "phone" && !isMobilePhone(value))
30
+ return "landline";
31
+ const [one, other] = sides;
32
+ if (!one.some((a) => other.some((b) => a.provider !== b.provider)))
33
+ return "one-source";
34
+ if (kind === "phone" && !phonePairJoins(value, holders))
35
+ return "not-own-number";
36
+ return null;
37
+ };
38
+ /**
39
+ * Reads every phone and address once, then answers for any number of pairs of people: what they share, and whether it
40
+ * is strong enough for an agent to merge them.
41
+ */
42
+ export const linkEvidenceOver = (context) => {
43
+ let read;
44
+ return (a, b) => {
45
+ read ??= {
46
+ holders: [
47
+ ["phone", phoneHolders(context.database)],
48
+ ["email", emailHolders(context.database)],
49
+ ],
50
+ persons: personsOf(context),
51
+ };
52
+ const { holders: all, persons } = read;
53
+ const facts = [];
54
+ for (const [kind, holders] of all)
55
+ for (const [value, held] of holders) {
56
+ const on = (person) => held.filter(({ identity }) => persons.get(identity) === person);
57
+ const sides = [on(a), on(b)];
58
+ if (sides[0].length === 0 || sides[1].length === 0)
59
+ continue;
60
+ const people = new Set(held.map(({ identity }) => persons.get(identity)).filter((p) => p !== undefined));
61
+ const others = people.size - 2;
62
+ const weak = weaknessOf(context, kind, value, held, sides, others);
63
+ const refs = (side) => side.map(({ provider, externalId }) => `${provider}:${externalId}`);
64
+ facts.push({ kind, value, holders: [refs(sides[0]), refs(sides[1])], others, strong: weak === null, weak });
65
+ }
66
+ facts.sort((x, y) => Number(y.strong) - Number(x.strong));
67
+ const strong = facts.some((fact) => fact.strong);
68
+ return {
69
+ persons: [`person:${a}`, `person:${b}`],
70
+ strong,
71
+ facts,
72
+ weak: strong ? null : (facts[0]?.weak ?? "nothing-shared"),
73
+ };
74
+ };
75
+ };
76
+ const held = (evidence, weak) => ({ ...evidence, strong: false, weak });
77
+ /**
78
+ * An agent's link: merged at once on strong evidence the store finds itself, recorded as an `identity_link` decided by
79
+ * the agent, with the evidence, its reason and its run; otherwise it waits for the owner as a proposal, which says why
80
+ * it is not strong. Refused over the owner's separation, as any agent's link is.
81
+ */
82
+ export const agentLink = (context, input) => write(context.database, () => {
83
+ const bot = input.bot.trim();
84
+ if (!bot || bot === "owner")
85
+ throw new CliError("validation_error", "an agent's link names the agent", { reason: "identity.agent-unnamed" });
86
+ const identity = required(context, input.identity);
87
+ const other = required(context, input.with);
88
+ const [from, to] = [identity.personPk, other.personPk];
89
+ if (from === to)
90
+ throw new CliError("validation_error", "those identities are one person already", { reason: "identity.same" });
91
+ if (separated(context, from, to))
92
+ throw new CliError("conflict", "the owner separated these people; only the owner links them again", {
93
+ reason: "identity.separated",
94
+ });
95
+ const found = linkEvidenceOver(context)(from, to);
96
+ const hold = !input.apply
97
+ ? "propose-only"
98
+ : isOwner(context, from) || isOwner(context, to)
99
+ ? "owner"
100
+ : rejectedEvidence(context.database, from, to) !== undefined
101
+ ? "rejected"
102
+ : undefined;
103
+ const evidence = hold === undefined || !found.strong ? found : held(found, hold);
104
+ const run = input.run?.trim() ? { run: input.run.trim() } : {};
105
+ const by = { bot, kind: "agent" };
106
+ const operations = proposalOperationsOver(context);
107
+ if (!evidence.strong) {
108
+ const opened = openIdentityLink(context, {
109
+ identity: identity.pk,
110
+ with: other.pk,
111
+ from,
112
+ to,
113
+ joins: "person",
114
+ signal: "agent",
115
+ by,
116
+ reason: input.reason,
117
+ evidence: evidence.facts.map(({ value }) => value),
118
+ strength: evidence,
119
+ ...run,
120
+ });
121
+ if (opened.outcome === "skipped")
122
+ throw new CliError("conflict", opened.reason === "identity.rejected"
123
+ ? "the owner rejected linking these people on this evidence; only new evidence proposes them again"
124
+ : "those identities are one person already", { reason: opened.reason });
125
+ return { outcome: "proposed", proposal: opened.action.id, evidence };
126
+ }
127
+ const [fact] = evidence.facts;
128
+ const kept = survivorOf(context, from, to);
129
+ const merge = mergeId(kept, kept === to ? from : to);
130
+ const payload = {
131
+ identity: `${input.identity.provider}:${input.identity.id}`,
132
+ with: `${input.with.provider}:${input.with.id}`,
133
+ persons: [String(from), String(to)],
134
+ sides: sidesOf(context.database, from, to),
135
+ joins: "person",
136
+ signal: fact.kind,
137
+ score: null,
138
+ evidence: [fact.value],
139
+ strength: evidence,
140
+ applied: "agent",
141
+ ...run,
142
+ };
143
+ const proposal = operations.propose({ kind: IDENTITY_LINK_KIND, by, payload, reason: input.reason });
144
+ operations.approve(proposal.id, { person: String(kept), merge }, by);
145
+ mergePerson(context, from, to, { method: AGENT_METHOD, by: `agent:${bot}` });
146
+ resolvePersonLinks(context.database, recordOf(context, kept).identities.flatMap(({ name, username }) => [name, username]));
147
+ return { outcome: "merged", person: `person:${kept}`, merge, proposal: proposal.id, evidence };
148
+ });
149
+ /** Who merged, why and in which run, for a merge an agent made; `undefined` for any other. */
150
+ export const agentMergeOf = (context, merge) => {
151
+ const row = context.database
152
+ .prepare("SELECT id FROM proposed_actions WHERE kind = ? AND status = 'approved' " +
153
+ "AND json_extract(payload, '$.applied') = 'agent' AND json_extract(result, '$.merge') = ? ORDER BY id DESC LIMIT 1")
154
+ .get(IDENTITY_LINK_KIND, merge);
155
+ if (!row)
156
+ return undefined;
157
+ const action = proposalOperationsOver(context).get(String(row.id));
158
+ const payload = action.payload;
159
+ const proposer = proposerOfAction(action);
160
+ return {
161
+ proposal: action.id,
162
+ bot: proposer.type === "bot" ? proposer.name : "unknown",
163
+ run: payload.run ?? null,
164
+ reason: action.reason,
165
+ evidence: payload.strength ?? null,
166
+ };
167
+ };
168
+ /** The merges agents made that are still in place, newest first: what the owner may want to undo. */
169
+ export const agentMerges = (context, { limit, offset }) => {
170
+ const rows = context.database
171
+ .prepare("SELECT json_extract(result, '$.merge') AS merge FROM proposed_actions WHERE kind = ? AND status = 'approved' " +
172
+ "AND json_extract(payload, '$.applied') = 'agent' ORDER BY id DESC")
173
+ .all(IDENTITY_LINK_KIND);
174
+ const found = [];
175
+ for (const { merge } of rows) {
176
+ const [, to] = /^merge:(\d+)-\d+$/.exec(String(merge)) ?? [];
177
+ if (to === undefined)
178
+ continue;
179
+ const inPlace = merges(context, to).find((one) => one.id === merge && one.method === AGENT_METHOD);
180
+ if (inPlace)
181
+ found.push({ ...inPlace, agent: agentMergeOf(context, inPlace.id) });
182
+ }
183
+ return { items: found.slice(offset, offset + limit), hasMore: found.length > offset + limit };
184
+ };