@wirecat/cli-core 0.676.0 → 0.677.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,22 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.677.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **An agent's link of two people merges at once on strong evidence** (`people.agentLink`). The store
13
+ decides, never the agent's word: one value only these two people hold, a mobile number or a personal address, from
14
+ two different sources, and for a phone at least one that keeps its user's own number (a messenger account or a
15
+ call's number). Anything weaker, the owner's own person, a pair the owner rejected, or `apply: false` opens a
16
+ proposal as before, whose payload now says why it is not strong (`strength`). The merge is recorded as an
17
+ `identity_link` the agent decided, with the evidence, the reason and the run, and `undoMerge` gives both people back.
18
+ - **`people.linkEvidence(pairs)`** answers what each pair of people shares and whether it is strong, reading the store
19
+ once; **`people.agentMerges()`** lists the agents' merges still in place; **`people.merges()`** names the agent, run,
20
+ reason and evidence of an agent's merge (`agent`).
21
+ - **`commandRunId()`** (`@wirecat/cli-core/cli`) gives the id `runs show` takes for the command under way, so a write
22
+ can name the run that made it.
23
+
8
24
  ## 0.676.0 — 16.11.2026
9
25
 
10
26
  ### Added
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
- action?: undefined;
28
27
  name: string;
29
28
  installed: boolean;
30
29
  active: boolean;
31
30
  servicePath: string;
32
31
  timerPath: string;
32
+ action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -57,6 +57,8 @@ export interface CommandRuns {
57
57
  events(event: RequestEvent): void;
58
58
  }
59
59
  export declare const commandRuns: (options: CommandRunOptions) => CommandRuns;
60
+ /** The id `runs show` takes for the command under way, so a write can name the run that made it. */
61
+ export declare const commandRunId: () => string | undefined;
60
62
  /**
61
63
  * For a provider client far from the program: the event lands in the current command's run — a `startCli` command's,
62
64
  * or the run `run()` opened — or nowhere.
@@ -111,6 +111,8 @@ const tracker = (options, typed) => {
111
111
  };
112
112
  export const commandRuns = (options) => tracker(options);
113
113
  const parses = new AsyncLocalStorage();
114
+ /** The id `runs show` takes for the command under way, so a write can name the run that made it. */
115
+ export const commandRunId = () => parses.getStore()?.runs.runId();
114
116
  /**
115
117
  * For a provider client far from the program: the event lands in the current command's run — a `startCli` command's,
116
118
  * or the run `run()` opened — or nowhere.
@@ -72,7 +72,7 @@ export { PressLog, UpdatesCursor } from "./bot/updates.js";
72
72
  export { addCallStatsCommand, type CallStatsCommandDeps, type CallStatsRead } from "./call-stats-command.js";
73
73
  export type { CommandAvailability, DiscoveredCommand } from "./command-availability.js";
74
74
  export { commandContract, type JsonSchema, SCHEMA_DIALECT } from "./command-contract.js";
75
- export { type CommandRunOptions, type CommandRuns, commandRuns, type ProviderAnswer, type ProviderCall, providerEvent, providerRequest, type RunSettings, recordRuns, runSettings, type SavedRunSettings, } from "./command-runs.js";
75
+ export { type CommandRunOptions, type CommandRuns, commandRunId, commandRuns, type ProviderAnswer, type ProviderCall, providerEvent, providerRequest, type RunSettings, recordRuns, runSettings, type SavedRunSettings, } from "./command-runs.js";
76
76
  export { CONTRACT } from "./commands-command.js";
77
77
  export { type CompactOptions, compactText, entityRows, GENERIC_ROW, type RowColumn, type RowShape, type RowsResolver, type RowTable, type RowValue, rowShapeOf, rowsOfEntity, SHARED_ROWS, } from "./compact.js";
78
78
  export type { AppCompletionOptions, CompletionRequest } from "./complete-command.js";
package/dist/cli/index.js CHANGED
@@ -64,7 +64,7 @@ export { BotTokenStore } from "./bot/token.js";
64
64
  export { PressLog, UpdatesCursor } from "./bot/updates.js";
65
65
  export { addCallStatsCommand } from "./call-stats-command.js";
66
66
  export { commandContract, SCHEMA_DIALECT } from "./command-contract.js";
67
- export { commandRuns, providerEvent, providerRequest, recordRuns, runSettings, } from "./command-runs.js";
67
+ export { commandRunId, commandRuns, providerEvent, providerRequest, recordRuns, runSettings, } from "./command-runs.js";
68
68
  export { CONTRACT } from "./commands-command.js";
69
69
  export { compactText, entityRows, GENERIC_ROW, rowShapeOf, rowsOfEntity, SHARED_ROWS, } from "./compact.js";
70
70
  export { refuseUnknownKey } from "./config-command.js";
@@ -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"),
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -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";
@@ -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";
@@ -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
+ };
@@ -19,6 +19,8 @@ export interface Opening {
19
19
  candidates?: number[] | undefined;
20
20
  shared?: SharedMailbox | undefined;
21
21
  mailbox?: string | undefined;
22
+ strength?: IdentityLinkPayload["strength"];
23
+ run?: string | undefined;
22
24
  }
23
25
  export type Opened = {
24
26
  outcome: "proposed" | "open";
@@ -70,6 +70,8 @@ export const openIdentityLink = (context, opening, index) => write(context.datab
70
70
  evidence: opening.evidence ?? [],
71
71
  ...(opening.shared === undefined ? {} : { shared: opening.shared }),
72
72
  ...(opening.mailbox === undefined ? {} : { mailbox: opening.mailbox }),
73
+ ...(opening.strength === undefined ? {} : { strength: opening.strength }),
74
+ ...(opening.run === undefined ? {} : { run: opening.run }),
73
75
  };
74
76
  const action = operations.propose({
75
77
  kind: IDENTITY_LINK_KIND,
@@ -1,3 +1,4 @@
1
+ import type { CacheDatabase } from "../driver.js";
1
2
  import type { MatchScan } from "../identity-links.js";
2
3
  import type { Author } from "./memories.js";
3
4
  import type { StoreContext } from "./open.js";
@@ -18,6 +19,34 @@ export declare const PROPOSAL_SCORE: {
18
19
  group: number;
19
20
  nameInChats: number;
20
21
  };
22
+ /**
23
+ * NEED-2445, safe option until the owner rules: a number two people share joins them only when a messenger, which
24
+ * keeps its user's own number, holds it; a CRM's or a card's number is someone's word and waits as a proposal.
25
+ * NEED-2600: a call's other side, kept as `phone:<number>`, is that number as the phone network gave it, as strong
26
+ * as a messenger's; it joins only on a mobile number, since an office's landline is everyone's who works there.
27
+ */
28
+ export declare const phonePairJoins: (phone: string, holders: Holder[]) => boolean;
29
+ export interface Holder {
30
+ identity: number;
31
+ provider: string;
32
+ externalId: string;
33
+ /** The list it comes from: its source, and for a CRM the kind of record, `<portal>/contact/` or `<portal>/user/`. */
34
+ list: string;
35
+ /** An organization holds this identity: its number or address is the company's. */
36
+ company: boolean;
37
+ }
38
+ /**
39
+ * SEC-177: a company's line or mailbox is everyone's who works there, so it never says two people are one. It is one
40
+ * when an organization holds it, or when two people of one list have it, such as two CRM contacts with one number. A
41
+ * CRM's contact and its user may be one person, so they are two lists. A messenger keeps one account per number, so
42
+ * two of its accounts on one number are a number that changed hands, not a company's line.
43
+ */
44
+ export declare const sharedLine: (context: StoreContext, holders: Holder[]) => boolean;
45
+ /** Identities by the value they share. */
46
+ export type Holders = Map<string, Holder[]>;
47
+ export declare const phoneHolders: (database: CacheDatabase) => Holders;
48
+ /** A company's address is an `org-email` identity, never a person's, so it never joins people. */
49
+ export declare const emailHolders: (database: CacheDatabase) => Holders;
21
50
  /**
22
51
  * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
23
52
  * each group it changes, so other writers are never kept waiting for the whole pass. After the first pass, only the
@@ -47,7 +47,7 @@ export const PROPOSAL_SCORE = {
47
47
  * NEED-2600: a call's other side, kept as `phone:<number>`, is that number as the phone network gave it, as strong
48
48
  * as a messenger's; it joins only on a mobile number, since an office's landline is everyone's who works there.
49
49
  */
50
- const phonePairJoins = (phone, holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider)) ||
50
+ export const phonePairJoins = (phone, holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider)) ||
51
51
  (holders.some(({ externalId }) => externalId === `phone:${phone}`) && isMobilePhone(phone));
52
52
  /** NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. */
53
53
  const addressGroupJoins = (people) => people <= 2;
@@ -60,7 +60,7 @@ const COMPANY = "EXISTS (SELECT 1 FROM organization_identities o WHERE o.identit
60
60
  * CRM's contact and its user may be one person, so they are two lists. A messenger keeps one account per number, so
61
61
  * two of its accounts on one number are a number that changed hands, not a company's line.
62
62
  */
63
- const sharedLine = (context, holders) => {
63
+ export const sharedLine = (context, holders) => {
64
64
  if (holders.some(({ company }) => company))
65
65
  return true;
66
66
  const seen = new Map();
@@ -136,7 +136,7 @@ const phonesOf = (row) => {
136
136
  catch { }
137
137
  return raws.filter((raw) => typeof raw === "string" && raw.trim() !== "");
138
138
  };
139
- const phoneHolders = (database) => {
139
+ export const phoneHolders = (database) => {
140
140
  const found = new Map();
141
141
  const countries = storePhoneCountries(database);
142
142
  for (const row of database
@@ -153,7 +153,7 @@ const addressOf = (value) => {
153
153
  return isEmailAddress(address) ? address : undefined;
154
154
  };
155
155
  /** A company's address is an `org-email` identity, never a person's, so it never joins people. */
156
- const emailHolders = (database) => {
156
+ export const emailHolders = (database) => {
157
157
  const found = new Map();
158
158
  for (const row of database
159
159
  .prepare(`SELECT i.id, i.provider, i.external_id, i.email, ${COMPANY} FROM identities i ` +
@@ -1,3 +1,4 @@
1
+ import type { AgentMerge } from "../identity-links.js";
1
2
  import type { IdentityRef, PersonRecord } from "../types.js";
2
3
  import type { StoreContext } from "./open.js";
3
4
  export interface PersonMerge {
@@ -11,6 +12,8 @@ export interface PersonMerge {
11
12
  method: string;
12
13
  by: string;
13
14
  at: string;
15
+ /** An agent's merge: which agent, in which run, why, and the evidence the store found. */
16
+ agent?: AgentMerge;
14
17
  }
15
18
  export declare const mergeId: (to: number | string, from: number | string) => string;
16
19
  /** The two uids a `merge:<to>-<from>` id names. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.676.0",
3
+ "version": "0.677.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",