@wirecat/cli-core 0.633.0 → 0.635.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 (71) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/domain/display-names.d.ts +4 -2
  4. package/dist/domain/display-names.js +5 -2
  5. package/dist/domain/relation-role-labels.d.ts +10 -0
  6. package/dist/domain/relation-role-labels.js +40 -0
  7. package/dist/domain/relations.d.ts +7 -0
  8. package/dist/domain/relations.js +10 -0
  9. package/dist/errors/reasons.js +5 -0
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +2 -1
  12. package/dist/search/groups.d.ts +2 -0
  13. package/dist/search/groups.js +1 -0
  14. package/dist/services/account-groups.d.ts +30 -1
  15. package/dist/services/account-groups.js +27 -0
  16. package/dist/services/index.d.ts +2 -1
  17. package/dist/services/index.js +2 -1
  18. package/dist/services/project-activity.d.ts +45 -0
  19. package/dist/services/project-activity.js +76 -0
  20. package/dist/services/project-status/index.d.ts +11 -1
  21. package/dist/services/project-status/index.js +3 -3
  22. package/dist/store/accounts.d.ts +10 -1
  23. package/dist/store/accounts.js +3 -2
  24. package/dist/store/chats.d.ts +5 -0
  25. package/dist/store/chats.js +6 -0
  26. package/dist/store/exports.d.ts +2 -1
  27. package/dist/store/identity-links.d.ts +21 -0
  28. package/dist/store/identity-splits.d.ts +2 -0
  29. package/dist/store/index.d.ts +3 -3
  30. package/dist/store/keys.d.ts +1 -1
  31. package/dist/store/keys.js +1 -1
  32. package/dist/store/messages.d.ts +13 -0
  33. package/dist/store/messages.js +7 -0
  34. package/dist/store/people.d.ts +10 -4
  35. package/dist/store/sqlite/accounts.d.ts +12 -2
  36. package/dist/store/sqlite/accounts.js +42 -3
  37. package/dist/store/sqlite/address-organization.d.ts +18 -0
  38. package/dist/store/sqlite/address-organization.js +48 -0
  39. package/dist/store/sqlite/chat-activity-counts.d.ts +19 -0
  40. package/dist/store/sqlite/chat-activity-counts.js +26 -0
  41. package/dist/store/sqlite/chats.d.ts +3 -1
  42. package/dist/store/sqlite/chats.js +8 -0
  43. package/dist/store/sqlite/identity-link-rows.d.ts +5 -1
  44. package/dist/store/sqlite/identity-link-rows.js +9 -3
  45. package/dist/store/sqlite/identity-proposals.d.ts +5 -3
  46. package/dist/store/sqlite/identity-proposals.js +66 -7
  47. package/dist/store/sqlite/identity-split-proposals.js +3 -1
  48. package/dist/store/sqlite/mail-findings.js +10 -44
  49. package/dist/store/sqlite/manifest.js +1 -0
  50. package/dist/store/sqlite/migrations.generated.js +6 -0
  51. package/dist/store/sqlite/name-traces.d.ts +5 -2
  52. package/dist/store/sqlite/name-traces.js +8 -5
  53. package/dist/store/sqlite/open-store.js +2 -0
  54. package/dist/store/sqlite/people-list.js +7 -3
  55. package/dist/store/sqlite/person-doubts.d.ts +13 -0
  56. package/dist/store/sqlite/person-doubts.js +12 -8
  57. package/dist/store/sqlite/person-links.d.ts +7 -2
  58. package/dist/store/sqlite/person-links.js +26 -1
  59. package/dist/store/sqlite/person-match-scan.js +74 -4
  60. package/dist/store/sqlite/person-merges.js +3 -7
  61. package/dist/store/sqlite/relation-list.d.ts +3 -1
  62. package/dist/store/sqlite/relation-list.js +16 -9
  63. package/dist/store/sqlite/relation-roles.d.ts +4 -0
  64. package/dist/store/sqlite/relation-roles.js +19 -5
  65. package/dist/store/sqlite/reply-times.d.ts +2 -0
  66. package/dist/store/sqlite/reply-times.js +2 -1
  67. package/dist/store/sqlite/task-titles.d.ts +12 -1
  68. package/dist/store/sqlite/task-titles.js +42 -1
  69. package/dist/store/sqlite/tasks.js +6 -1
  70. package/dist/store/types.d.ts +4 -0
  71. package/package.json +2 -2
@@ -1,8 +1,10 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { FREE_MAIL } from "../../mail/score.js";
2
3
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
3
4
  import { IDENTITY_LINK_KIND, } from "../identity-links.js";
5
+ import { holdAddress, organizationOfAddress } from "./address-organization.js";
4
6
  import { ensurePerson } from "./identities.js";
5
- import { evidenceKeyOf, linkIndex, linkRows, settleLinks, sidesOf } from "./identity-link-rows.js";
7
+ import { evidenceKeyOf, linkIndex, linkRows, settleLinks, sidesOf, } from "./identity-link-rows.js";
6
8
  import { currentPerson } from "./merged-persons.js";
7
9
  import { linkIdentityToPerson, mergePerson, move, recordOf, required, survivorOf } from "./person-links.js";
8
10
  import { resolvePersonLinks } from "./person-resolution.js";
@@ -56,6 +58,8 @@ export const openIdentityLink = (context, opening, index) => write(context.datab
56
58
  score: opening.score ?? null,
57
59
  ...(opening.candidates && opening.candidates.length > 2 ? { candidates: opening.candidates.map(String) } : {}),
58
60
  evidence: opening.evidence ?? [],
61
+ ...(opening.shared === undefined ? {} : { shared: opening.shared }),
62
+ ...(opening.mailbox === undefined ? {} : { mailbox: opening.mailbox }),
59
63
  };
60
64
  const action = operations.propose({
61
65
  kind: IDENTITY_LINK_KIND,
@@ -145,6 +149,53 @@ const settleMentions = ({ database, now }, payload, to) => {
145
149
  "AND target_id = ?")
146
150
  .run(to, now(), Number(identity.id));
147
151
  };
152
+ const organizationExists = ({ database }, id) => Number.isSafeInteger(id) &&
153
+ database.prepare("SELECT 1 FROM organizations WHERE id = ? AND deleted_at IS NULL").get(id) !== undefined;
154
+ /**
155
+ * NEED-2528: the shared mailbox is a company's, not one of the two people. The address goes to the organization and
156
+ * the proposal is turned down, so the pair is not proposed again on it (the rejected evidence), and nobody is joined.
157
+ */
158
+ const toCompany = (context, proposal, company, author, noted) => {
159
+ const payload = proposal.payload;
160
+ if (proposal.status !== "proposed")
161
+ throw new CliError("validation_error", `${proposal.id} is already ${proposal.status}`, {
162
+ reason: "proposal.wrong-state",
163
+ });
164
+ const address = payload.mailbox;
165
+ if (payload.shared === undefined || address === undefined)
166
+ throw new CliError("validation_error", `${proposal.id} is not about a shared mailbox; confirm or reject it`, {
167
+ reason: "identity.not-shared",
168
+ });
169
+ const name = company.name?.trim() || undefined;
170
+ const domain = address.split("@")[1] ?? "";
171
+ let organization;
172
+ if (company.organization !== undefined) {
173
+ if (!organizationExists(context, company.organization))
174
+ throw new CliError("not_found", `no organization:${company.organization}`, { reason: "organization.not-found" });
175
+ organization = company.organization;
176
+ holdAddress(context, organization, address, { method: CONFIRMED, author: "owner" });
177
+ }
178
+ else {
179
+ if (name === undefined && FREE_MAIL.has(domain))
180
+ throw new CliError("validation_error", `${address} is a free mailbox; name the company or its organization`, {
181
+ reason: "organization.unnamed",
182
+ });
183
+ organization = organizationOfAddress(context, {
184
+ name: name ?? domain,
185
+ email: address,
186
+ method: CONFIRMED,
187
+ author: "owner",
188
+ reason: "organization.ambiguous",
189
+ });
190
+ }
191
+ const rejected = proposalOperationsOver(context).reject(proposal.id, author, {
192
+ dismissed: true,
193
+ organization: `organization:${organization}`,
194
+ ...noted,
195
+ });
196
+ settleMentions(context, payload, "found");
197
+ return rejected;
198
+ };
148
199
  /**
149
200
  * Decides an `identity_link`, the owner's alone. Confirm links the two people as the owner's link, refused with
150
201
  * `identity.stale` when either person changed since it was proposed; reject keeps them apart, and only new evidence
@@ -159,6 +210,11 @@ export const decideIdentityLink = (context, id, decision) => write(context.datab
159
210
  const author = deciderAuthor(decision.by);
160
211
  const reason = decision.reason?.trim() || undefined;
161
212
  const noted = reason === undefined ? {} : { reason };
213
+ if (decision.company !== undefined) {
214
+ if (decision.confirm)
215
+ throw new CliError("validation_error", "a company's mailbox keeps the two people apart; it is not a confirm");
216
+ return toCompany(context, proposal, decision.company, author, noted);
217
+ }
162
218
  if (!decision.confirm) {
163
219
  const rejected = operations.reject(id, author, { dismissed: true, ...noted });
164
220
  settleMentions(context, proposal.payload, "found");
@@ -200,8 +256,10 @@ const SHOWN = {
200
256
  executed: "confirmed",
201
257
  failed: "confirmed",
202
258
  };
203
- /** The `identity_link` proposals, newest first, each naming its people as they are now; a page and whether more follow. */
204
- export const identityLinkRows = (context, { person, status = "proposed", limit, offset }) => {
259
+ /** Newest first in, highest score first out, proposals without a score last; a stable sort keeps the dates' order. */
260
+ const byOrder = (rows, order) => order !== "score" ? rows : rows.sort((a, b) => (b.payload.score ?? -1) - (a.payload.score ?? -1));
261
+ /** The `identity_link` proposals, newest first or by score, each naming its people as they are now; a page and whether more follow. */
262
+ export const identityLinkRows = (context, { person, status = "proposed", order = "newest", limit, offset }) => {
205
263
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
206
264
  throw new CliError("validation_error", "a list of link proposals takes 1–500 items");
207
265
  const asked = person === undefined ? undefined : currentPerson(context.database, Number(person));
@@ -209,11 +267,10 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
209
267
  const statuses = Object.keys(SHOWN).filter((one) => status === "all" || SHOWN[one] === status);
210
268
  // Whose a proposal is now depends on merges since, so only a list for one person reads every proposal.
211
269
  const rows = asked === undefined
212
- ? linkRows(context.database, statuses, { limit: limit + 1, offset })
213
- : linkRows(context.database, statuses)
270
+ ? linkRows(context.database, statuses, { limit: limit + 1, offset, order })
271
+ : byOrder(linkRows(context.database, statuses)
214
272
  .filter((row) => row.pair?.includes(asked) ?? false)
215
- .reverse()
216
- .slice(offset, offset + limit + 1);
273
+ .reverse(), order).slice(offset, offset + limit + 1);
217
274
  const items = rows.slice(0, limit).map((row) => {
218
275
  const action = operations.get(row.id);
219
276
  const payload = row.payload;
@@ -227,6 +284,8 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
227
284
  joins: payload.joins,
228
285
  signal: payload.signal,
229
286
  score: payload.score,
287
+ shared: payload.shared ?? null,
288
+ mailbox: payload.mailbox ?? null,
230
289
  candidates: (payload.candidates ?? []).map((uid) => `person:${uid}`),
231
290
  reason: action.reason,
232
291
  evidence: payload.evidence,
@@ -4,7 +4,7 @@ import { IDENTITY_SPLIT_KIND, } from "../identity-splits.js";
4
4
  import { personOf, pkOf, sideOf } from "./identity-link-rows.js";
5
5
  import { parseIdentityRef } from "./identity-proposals.js";
6
6
  import { currentPerson } from "./merged-persons.js";
7
- import { recordOf, required, unlinkIdentity } from "./person-links.js";
7
+ import { heldBy, recordOf, required, unlinkIdentity } from "./person-links.js";
8
8
  import { mergeId, merges, parseMergeId, split, undoMerge } from "./person-merges.js";
9
9
  import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
10
10
  import { write } from "./transaction.js";
@@ -25,6 +25,8 @@ const planOf = (context, input) => {
25
25
  const chosen = [...new Map(input.identities.map((ref) => [refOf(ref), ref])).values()];
26
26
  if (chosen.length === 0)
27
27
  throw new CliError("validation_error", "name at least one identity to split off");
28
+ if (input.from !== undefined)
29
+ heldBy(context, input.from, chosen);
28
30
  const persons = new Set(chosen.map((ref) => required(context, ref).personPk));
29
31
  if (persons.size > 1)
30
32
  throw new CliError("validation_error", "the identities that leave are all of one person", {
@@ -2,11 +2,11 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { contextEvidenceFingerprint } from "../../context/evidence.js";
3
3
  import { parseLocator } from "../../domain/locator.js";
4
4
  import { checkMailFindings, MAIL_FINDINGS_PER_SENDER, mailFindingFingerprint, mailFindingProblem, validateMailFindings, } from "../../mail/findings.js";
5
- import { FREE_MAIL } from "../../mail/score.js";
6
5
  import { findingHash } from "../../meetings/index.js";
7
6
  import { assertMayDecide } from "../decisions.js";
8
7
  import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
9
8
  import { fold } from "../normalize.js";
9
+ import { organizationOfAddress } from "./address-organization.js";
10
10
  import { financeOperationsOver } from "./finance.js";
11
11
  import { findingsAgent, findingsCoreOver } from "./findings-core.js";
12
12
  import { authorActor, linkEvidence, memoriesStoreOver } from "./memories.js";
@@ -141,51 +141,17 @@ export const mailFindingsStoreOver = (context) => {
141
141
  }
142
142
  return read;
143
143
  };
144
- const organizationsOf = (sql, ...params) => [
145
- ...new Set(database
146
- .prepare(sql)
147
- .all(...params)
148
- .map((row) => Number(row.id))),
149
- ];
150
- const BY_ADDRESS = "SELECT o.id FROM organizations o JOIN organization_identities oi ON oi.organization_id = o.id " +
151
- "JOIN identities i ON i.id = oi.identity_id WHERE o.deleted_at IS NULL AND i.provider = 'email' AND ";
152
144
  /**
153
- * The organization a finding names but does not reference: the one its address belongs to, else the one its
154
- * company domain belongs to, else the one of exactly this name; else a new company. Its address joins it, so the
155
- * next mail from it finds it. Only the owner's accept runs this for real; staging runs it and rolls it back.
145
+ * The organization a finding names but does not reference, found or made by `organizationOfAddress`. Only the
146
+ * owner's accept runs this for real; staging runs it and rolls it back.
156
147
  */
157
- const organizationNamed = (name, email) => {
158
- const domain = email?.split("@")[1];
159
- let found = email === undefined ? [] : organizationsOf(`${BY_ADDRESS}lower(i.external_id) = ?`, email);
160
- if (!found.length && domain && !FREE_MAIL.has(domain))
161
- found = organizationsOf(`${BY_ADDRESS}substr(lower(i.external_id), -length(?)) = ?`, `@${domain}`, `@${domain}`);
162
- if (!found.length)
163
- found = database
164
- .prepare("SELECT id, name FROM organizations WHERE deleted_at IS NULL")
165
- .all()
166
- .filter((row) => fold(String(row.name)).trim() === fold(name).trim())
167
- .map((row) => Number(row.id));
168
- if (found.length > 1)
169
- return invalid(`${found.length} organizations match ${name} (${found.map((id) => `organization:${id}`).join(", ")}); ` +
170
- "name the one meant as a reference", "finance.party");
171
- const at = now();
172
- const id = found[0] ??
173
- Number(database
174
- .prepare("INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'work', ?, ?) RETURNING id")
175
- .get(name, at, at)?.id);
176
- if (email !== undefined) {
177
- database
178
- .prepare("INSERT INTO identities (provider, external_id, created_at, updated_at) VALUES ('email', ?, ?, ?) " +
179
- "ON CONFLICT (provider, external_id) DO NOTHING")
180
- .run(email, at, at);
181
- database
182
- .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
183
- "SELECT id, ?, 'mail-finding', 'owner', ?, ? FROM identities WHERE provider = 'email' AND external_id = ? " +
184
- "ON CONFLICT (identity_id, organization_id) DO NOTHING")
185
- .run(id, at, at, email);
186
- }
187
- return `organization:${id}`;
188
- };
148
+ const organizationNamed = (name, email) => `organization:${organizationOfAddress(context, {
149
+ name,
150
+ ...(email === undefined ? {} : { email }),
151
+ method: "mail-finding",
152
+ author: "owner",
153
+ reason: "finance.party",
154
+ })}`;
189
155
  const partyOf = (reference, name, email) => reference ?? (name === undefined ? undefined : organizationNamed(name, email));
190
156
  /** The invoice, payment or order an accepted finding records: the owner's own entry, citing the mail it came from. */
191
157
  const entry = (finding, evidence) => {
@@ -129,6 +129,7 @@ export const MANIFEST = [
129
129
  { name: "20261110005200_version-62-person-kinds-triggers", version: 62, minCompatible: 56 },
130
130
  { name: "20261110020704_version-63-people-ties-messages-crm", version: 63, minCompatible: 56 },
131
131
  { name: "20261110084658_version-64-deal-link-triggers", version: 64, minCompatible: 56 },
132
+ { name: "20261110182602_version-65-found-task-titles", version: 65, minCompatible: 56 },
132
133
  ];
133
134
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
134
135
  const migrations = [];
@@ -1321,5 +1321,11 @@ export const GENERATED = [
1321
1321
  "DROP TRIGGER IF EXISTS person_kind_deal_owner_person_au;",
1322
1322
  "CREATE TRIGGER person_kind_deal_owner_person_au AFTER UPDATE OF owner ON persons\nWHEN OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' WHERE o.to_type = 'person' AND o.role = 'owner' AND o.from_type IN ('deal', 'lead') AND o.to_id IN (SELECT NEW.id UNION SELECT e.from_person_id FROM identity_link_events e JOIN identity_links l ON l.identity_id = e.identity_id WHERE l.person_id = NEW.id));\nEND;"
1323
1323
  ]
1324
+ },
1325
+ {
1326
+ "name": "20261110182602_version-65-found-task-titles",
1327
+ "statements": [
1328
+ "-- A found task's title was its message's first line only while reading, so it went blank when the message was deleted.\n-- The line comes from displayTitleOf in code, so the next writable open stores it for the tasks still titled\n-- `<kind> — <source>` and deletes this key (fillFoundTaskTitles). A store with no such task gets no key.\nINSERT OR REPLACE INTO store_settings (key, value, at)\nSELECT 'found_task_titles_to_fill', '1', unixepoch() * 1000 WHERE EXISTS (\n SELECT 1 FROM tasks WHERE package_id IS NOT NULL AND deleted_at IS NULL AND source_locator LIKE 'msg:%'\n AND title = type || ' — ' || source_locator\n);"
1329
+ ]
1324
1330
  }
1325
1331
  ];
@@ -18,5 +18,8 @@ export interface SharedTrace {
18
18
  evidence: string[];
19
19
  reason: string;
20
20
  }
21
- /** The traces two people share, strongest first: each phone, each address, a chat, a company's domain. */
22
- export declare function sharedTraces(database: CacheDatabase, a: number, b: number, name: string): Generator<SharedTrace>;
21
+ /**
22
+ * The traces two people share, strongest first: each phone, each address, a chat, a company's domain. `except` is an
23
+ * address left out, with its domain, when it is the very thing being weighed.
24
+ */
25
+ export declare function sharedTraces(database: CacheDatabase, a: number, b: number, name: string, except?: string): Generator<SharedTrace>;
@@ -33,7 +33,7 @@ const companyDomain = (address) => {
33
33
  const domain = address.split("@")[1];
34
34
  return domain === undefined || FREE_MAIL.has(domain) || isRoleAddress(address) ? undefined : domain;
35
35
  };
36
- const tracesOf = (database, person) => {
36
+ const tracesOf = (database, person, except) => {
37
37
  const traces = { phones: [], emails: [], domains: [] };
38
38
  for (const row of database
39
39
  .prepare("SELECT i.id, i.provider, i.external_id, i.phone, i.email FROM identity_links l " +
@@ -46,7 +46,7 @@ const tracesOf = (database, person) => {
46
46
  if (stored !== undefined)
47
47
  traces.phones.push({ identity, value: stored });
48
48
  for (const address of [addressOf(row.email), provider === "email" ? addressOf(row.external_id) : undefined]) {
49
- if (address === undefined)
49
+ if (address === undefined || address === except)
50
50
  continue;
51
51
  traces.emails.push({ identity, value: address });
52
52
  const domain = companyDomain(address);
@@ -73,9 +73,12 @@ const commonChat = (database, a, b) => database
73
73
  "JOIN identity_links l2 ON l2.identity_id = m2.identity_id " +
74
74
  "WHERE l1.person_id = ? AND l2.person_id = ? ORDER BY m1.chat_id LIMIT 1")
75
75
  .get(a, b);
76
- /** The traces two people share, strongest first: each phone, each address, a chat, a company's domain. */
77
- export function* sharedTraces(database, a, b, name) {
78
- const [one, other] = [tracesOf(database, a), tracesOf(database, b)];
76
+ /**
77
+ * The traces two people share, strongest first: each phone, each address, a chat, a company's domain. `except` is an
78
+ * address left out, with its domain, when it is the very thing being weighed.
79
+ */
80
+ export function* sharedTraces(database, a, b, name, except) {
81
+ const [one, other] = [tracesOf(database, a, except), tracesOf(database, b, except)];
79
82
  for (const phone of common(one.phones, other.phones))
80
83
  yield {
81
84
  identity: phone[0].identity,
@@ -22,6 +22,7 @@ import { pruneRollbackCopies } from "./rollback-copy.js";
22
22
  import { stemsState } from "./stems.js";
23
23
  import { fillStems, followDefaultStemmers } from "./stems-fill.js";
24
24
  import { moveSuggestedLinks } from "./suggested-links.js";
25
+ import { fillFoundTaskTitles } from "./task-titles.js";
25
26
  import { purgeTestAccounts } from "./test-accounts.js";
26
27
  import { fillVectorIndexes } from "./vector-index.js";
27
28
  export const BACKFILL_ON_OPEN = 5_000;
@@ -107,6 +108,7 @@ export const openStoreContext = async (options = {}) => {
107
108
  movePaymentFacts({ ...opened, now, decisions });
108
109
  purgeTestAccounts({ ...opened, now, decisions }, warn);
109
110
  maskStoredBotTokens({ ...opened, now, decisions });
111
+ fillFoundTaskTitles(database, warn);
110
112
  const pending = pendingNormalization(database);
111
113
  if (pending > 0 && pending <= BACKFILL_ON_OPEN)
112
114
  backfillNormalized(database);
@@ -43,7 +43,7 @@ const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum
43
43
  "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
44
44
  "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
45
45
  `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`;
46
- const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.username, i.phone, i.email, i.bot " +
46
+ const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.name, i.username, i.phone, i.email, i.bot " +
47
47
  `FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE ${IN_SCOPE(scope, "l.person_id")} ORDER BY i.id`;
48
48
  /** Few identities have these; one pass each beats a lookup per identity. */
49
49
  const NEVER_REPLIED = "SELECT identity_id FROM account_identities WHERE mail_signals LIKE '%bulk_never_replied%'";
@@ -67,6 +67,7 @@ const factsOf = (database, scope) => {
67
67
  for (const row of database.prepare(IDENTITIES(scope)).all(...scopeParams(scope))) {
68
68
  const person = Number(row.person);
69
69
  const one = facts.get(person) ?? {
70
+ name: null,
70
71
  username: null,
71
72
  usernameSource: null,
72
73
  phone: null,
@@ -77,6 +78,9 @@ const factsOf = (database, scope) => {
77
78
  organization: false,
78
79
  };
79
80
  const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
81
+ const named = displayName(text(row.name));
82
+ if (one.name === null && isReadable(named) && !named?.startsWith("@"))
83
+ one.name = named;
80
84
  if (one.username === null && text(row.username) !== null) {
81
85
  one.username = text(row.username);
82
86
  one.usernameSource = String(row.provider);
@@ -143,7 +147,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
143
147
  return people.map(({ id, name, owner }) => {
144
148
  const own = facts.get(id);
145
149
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
146
- const shown = displayName(name, contact);
150
+ const shown = displayName(name, { ...contact, name: own?.name ?? null });
147
151
  const ties = reasons.get(id) ?? [];
148
152
  const { kind, signals } = kindOf(shown, own, ties, mail.get(id));
149
153
  return {
@@ -179,7 +183,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
179
183
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
180
184
  * every stored one is worked out again on the next list.
181
185
  */
182
- const KIND_RULES = "2";
186
+ const KIND_RULES = "3";
183
187
  const RULES_KEY = "people.kind_rules";
184
188
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
185
189
  const WHOLE_PASS = 20_000;
@@ -23,7 +23,20 @@ export interface PersonDoubt {
23
23
  evidence: string[];
24
24
  /** memo commands, after `memo`, that would take the doubted identities off; empty when none fits. */
25
25
  fix: string[];
26
+ /** The same moves as `fix`, one each, for an app that runs them without a command line. */
27
+ moves: DoubtMove[];
26
28
  }
29
+ /** Undo a merge, or move identities to one new person. */
30
+ export type DoubtMove = {
31
+ op: "unmerge";
32
+ merge: string;
33
+ }
34
+ /** `from` is the person they leave, `person:<uid>`. */
35
+ | {
36
+ op: "unlink";
37
+ identities: string[];
38
+ from: string;
39
+ };
27
40
  export interface PersonDoubts {
28
41
  items: PersonDoubt[];
29
42
  total: number;
@@ -170,29 +170,32 @@ const everyDoubt = (database) => {
170
170
  * The owner's moves that take the doubted identities off: undoing a merge that brought only doubted ones, and one
171
171
  * unlink per name group of the rest, so two strangers on one person do not land on one new person together.
172
172
  */
173
- const fixOf = (context, found) => {
173
+ const movesOf = (context, found) => {
174
174
  if (found.reason === "test-data" || found.reason === "mixed-names")
175
175
  return [];
176
176
  const doubted = new Set(found.held.map(({ ref }) => ref));
177
- const commands = [];
177
+ const moves = [];
178
178
  const unmerged = new Set();
179
179
  for (const merge of merges(context, String(found.person))) {
180
180
  const refs = merge.identities.map(({ provider, id }) => `${provider}:${id}`);
181
181
  if (refs.length === 0 || !refs.every((ref) => doubted.has(ref)))
182
182
  continue;
183
- commands.push(`people unmerge ${merge.id}`);
183
+ moves.push({ op: "unmerge", merge: merge.id });
184
184
  for (const ref of refs)
185
185
  unmerged.add(ref);
186
186
  }
187
187
  const rest = found.held.filter(({ ref }) => !unmerged.has(ref));
188
188
  for (const group of nameGroups(rest))
189
- commands.push(`people unlink ${group.map(({ ref }) => shellWord(ref)).join(" ")}`);
190
- return commands;
189
+ moves.push({ op: "unlink", identities: group.map(({ ref }) => ref), from: `person:${found.person}` });
190
+ return moves;
191
191
  };
192
+ const commandOf = (move) => move.op === "unmerge"
193
+ ? `people unmerge ${move.merge}`
194
+ : `people unlink ${move.identities.map(shellWord).join(" ")} --from ${move.from}`;
192
195
  /** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
193
196
  const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
194
197
  const shown = (context, found) => {
195
- const fix = fixOf(context, found);
198
+ const moves = movesOf(context, found);
196
199
  return {
197
200
  person: `person:${found.person}`,
198
201
  name: found.name,
@@ -209,9 +212,10 @@ const shown = (context, found) => {
209
212
  evidence: [
210
213
  ...found.held.map(({ ref }) => ref),
211
214
  ...(found.address === undefined ? [] : [`email:${found.address}`]),
212
- ...fix.flatMap((command) => command.match(/merge:\d+-\d+/u) ?? []),
215
+ ...moves.flatMap((move) => (move.op === "unmerge" ? [move.merge] : [])),
213
216
  ],
214
- fix,
217
+ fix: moves.map(commandOf),
218
+ moves,
215
219
  };
216
220
  };
217
221
  /** People that may be wrong, a page at a time, each with why and the owner's moves that would set it right. */
@@ -1,5 +1,5 @@
1
1
  import type { Id, Page } from "../../domain/models.js";
2
- import type { IdentityRef, LinkOptions, PersonRecord, StoredHit } from "../types.js";
2
+ import type { IdentityRef, LinkOptions, PersonRecord, StoredHit, UnlinkOptions } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
4
  export declare const required: (context: StoreContext, ref: IdentityRef) => {
5
5
  pk: number;
@@ -55,8 +55,13 @@ export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, ad
55
55
  * owner merged with a partner's CRM contact kept the partner's name after the split (BUG-677).
56
56
  */
57
57
  export declare const renameAfterLeaving: (context: StoreContext, person: number, left: readonly number[]) => void;
58
+ /**
59
+ * Refuses identities that sit on anyone but `from` (a uid, or `person:<uid>` as doubts and refusals give it), so a
60
+ * caller that guessed the person never takes them off someone else. The refusal names who holds them.
61
+ */
62
+ export declare const heldBy: (context: StoreContext, from: string, refs: readonly IdentityRef[]) => void;
58
63
  /** Gives the identity a person of its own again; the ones left keep theirs. */
59
- export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options: LinkOptions) => PersonRecord;
64
+ export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options: UnlinkOptions) => PersonRecord;
60
65
  /** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */
61
66
  export declare const mentioning: (context: StoreContext, accountKey: number, { id, username }: {
62
67
  id: Id;
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { isEmailAddress, isRoleAddress } from "../../domain/addresses.js";
3
+ import { displayName } from "../../domain/display-names.js";
3
4
  import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
4
5
  import { identityOf } from "./identities.js";
5
6
  import { rejectedEvidence, settleLinks } from "./identity-link-rows.js";
@@ -262,8 +263,32 @@ export const renameAfterLeaving = (context, person, left) => {
262
263
  .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ?")
263
264
  .run(typeof kept === "string" ? kept : null, context.now(), person);
264
265
  };
266
+ const shownAs = (person) => `${displayName(person.name, { name: person.identities.find((identity) => identity.name)?.name ?? null }) ?? "a person with no name"} (person:${person.uid})`;
267
+ /**
268
+ * Refuses identities that sit on anyone but `from` (a uid, or `person:<uid>` as doubts and refusals give it), so a
269
+ * caller that guessed the person never takes them off someone else. The refusal names who holds them.
270
+ */
271
+ export const heldBy = (context, from, refs) => {
272
+ const uid = from.startsWith("person:") ? from.slice("person:".length) : from;
273
+ const found = /^[1-9]\d*$/.test(uid)
274
+ ? context.database.prepare("SELECT id FROM persons WHERE id = ?").get(uid)
275
+ : undefined;
276
+ if (found === undefined)
277
+ throw new CliError("not_found", `no person:${uid} in the store`, { param: "from" });
278
+ const pk = currentPerson(context.database, Number(found.id));
279
+ for (const ref of refs) {
280
+ const row = required(context, ref);
281
+ if (row.personPk === pk)
282
+ continue;
283
+ const holder = recordOf(context, row.personPk);
284
+ throw new CliError("validation_error", `${ref.provider}:${ref.id} sits on ${shownAs(holder)}, not on ${shownAs(recordOf(context, pk))}; nothing changed. ` +
285
+ `Name person:${holder.uid} to take it off them`, { reason: "identity.held-elsewhere", param: "from", reference: `person:${holder.uid}` });
286
+ }
287
+ };
265
288
  /** Gives the identity a person of its own again; the ones left keep theirs. */
266
289
  export const unlinkIdentity = (context, ref, options) => {
290
+ if (options.from !== undefined)
291
+ heldBy(context, options.from, [ref]);
267
292
  const found = required(context, ref);
268
293
  const others = context.orm
269
294
  .select({ n: sql `count(*)` })
@@ -279,7 +304,7 @@ export const unlinkIdentity = (context, ref, options) => {
279
304
  .values({ name: named?.name ?? null, createdAt: at, updatedAt: at })
280
305
  .returning({ pk: persons.id })
281
306
  .get()?.pk);
282
- move(context, found.pk, found.personPk, alone, { ...options, method: "unlink" });
307
+ move(context, found.pk, found.personPk, alone, { method: "unlink", by: options.by });
283
308
  renameAfterLeaving(context, found.personPk, [found.pk]);
284
309
  return recordOf(context, alone);
285
310
  };
@@ -1,4 +1,5 @@
1
1
  import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { variantKey } from "../../domain/name-variants.js";
2
3
  import { BARE_INTERNATIONAL_PROVIDERS, storedPhone } from "../../domain/phones.js";
3
4
  import { linkIndex, settleLinks } from "./identity-link-rows.js";
4
5
  import { openIdentityLink } from "./identity-proposals.js";
@@ -15,6 +16,13 @@ export const RULE = { bot: "rule", kind: "rule" };
15
16
  /** More people than this on one number or address is a shared line or mailbox: nobody is proposed from it. */
16
17
  const MOST_SHARING = 6;
17
18
  const CURSOR = "people.scan";
19
+ /** Raised when a rule changes what a pass finds in values nobody touched: the next pass then reads everything once. */
20
+ const RULES = 2;
21
+ /**
22
+ * NEED-2526: a shared mailbox says little alone, so its proposal is scored by what else the two people have in common.
23
+ * The role word itself does not move the score: the list does not tell a department's inbox from a company's.
24
+ */
25
+ const SHARED_SCORE = { alone: 0.1, name: 0.4, trace: 0.3, weakTrace: 0.2 };
18
26
  /**
19
27
  * NEED-2445, safe option until the owner rules: a number two people share joins them only when a messenger, which
20
28
  * 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.
@@ -54,10 +62,12 @@ const cursorNow = (database) => ({
54
62
  revision: maxOf(database, "SELECT max(id) AS n FROM identity_revisions"),
55
63
  participant: maxOf(database, "SELECT max(id) AS n FROM meeting_participants"),
56
64
  at: maxOf(database, "SELECT max(updated_at) AS n FROM identities"),
65
+ rules: RULES,
57
66
  });
58
67
  const savedCursor = (database) => {
59
68
  const value = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(CURSOR)?.value;
60
- return value === undefined ? undefined : JSON.parse(String(value));
69
+ const cursor = value === undefined ? undefined : JSON.parse(String(value));
70
+ return cursor?.rules === RULES ? cursor : undefined;
61
71
  };
62
72
  /** The identities changed since `since`: new ones, moved ones, edited ones and ones a new meeting guest row names. */
63
73
  const changedSince = (database, since) => new Set(database
@@ -218,9 +228,63 @@ const samePhone = (pass, holders) => {
218
228
  else
219
229
  proposeEachPair(pass, people, "phone");
220
230
  };
231
+ const nameOf = ({ database }, person) => {
232
+ const name = database.prepare("SELECT name FROM persons WHERE id = ?").get(person)?.name;
233
+ return typeof name === "string" ? name : null;
234
+ };
235
+ const TRACE_WORDS = {
236
+ phone: "the same phone",
237
+ email: "another address only they have",
238
+ chat: "a chat they are both in",
239
+ "email-domain": "mail at the same company",
240
+ };
241
+ /** What two people on one shared mailbox have in common besides it, as a score and the words that say why. */
242
+ const sharedMailboxCase = (context, address, from, to) => {
243
+ const reasons = [`both have the shared mailbox ${address}`];
244
+ let score = SHARED_SCORE.alone;
245
+ const name = nameOf(context, from);
246
+ const key = variantKey(name);
247
+ if (key !== null && key === variantKey(nameOf(context, to))) {
248
+ score += SHARED_SCORE.name;
249
+ reasons.push(`the same name «${name}»`);
250
+ }
251
+ let evidence = [];
252
+ for (const trace of sharedTraces(context.database, from, to, name ?? "", address))
253
+ if (!(trace.kind === "email" && isRoleAddress(trace.value ?? "")) && strongEnough(context, from, to, trace)) {
254
+ score += trace.value === undefined ? SHARED_SCORE.weakTrace : SHARED_SCORE.trace;
255
+ reasons.push(TRACE_WORDS[trace.kind]);
256
+ evidence = trace.evidence;
257
+ break;
258
+ }
259
+ return { score: Math.round(score * 10) / 10, reason: reasons.join("; "), evidence };
260
+ };
261
+ /**
262
+ * NEED-2526: a shared mailbox never joins anyone (SEC-177), but each pair on it is proposed to the owner, scored by
263
+ * what else they share.
264
+ */
265
+ const proposeShared = (pass, { address, holders, shared }) => {
266
+ const people = peopleOf(pass.context, holders);
267
+ if (people.size < 2)
268
+ return;
269
+ const persons = [...people.keys()].sort((a, b) => a - b);
270
+ for (const [at, from] of persons.entries())
271
+ for (const to of persons.slice(at + 1))
272
+ propose(pass, {
273
+ identity: people.get(from),
274
+ with: people.get(to),
275
+ from,
276
+ to,
277
+ joins: "person",
278
+ signal: "email",
279
+ candidates: persons,
280
+ shared,
281
+ mailbox: address,
282
+ ...sharedMailboxCase(pass.context, address, from, to),
283
+ });
284
+ };
221
285
  /**
222
286
  * One address is one person in any scope (NEED-2382), unless more than two people have it (NEED-2446). A no-reply
223
- * address is no one's; a role address such as `info@` and a company's mailbox say nothing about who is who (SEC-177).
287
+ * address is no one's. A role address such as `info@` and a company's mailbox only propose (NEED-2526).
224
288
  */
225
289
  const sameEmail = (pass, address, holders) => {
226
290
  if (isNoReplyAddress(address))
@@ -228,8 +292,11 @@ const sameEmail = (pass, address, holders) => {
228
292
  const people = peopleOf(pass.context, holders);
229
293
  if (people.size < 2 || tooMany(pass, people, "identity.shared-email", "email"))
230
294
  return;
231
- if (isRoleAddress(address) || sharedLine(pass.context, holders))
232
- return skipShared(pass, people, "email");
295
+ const role = isRoleAddress(address);
296
+ if (role || sharedLine(pass.context, holders)) {
297
+ pass.shared.push({ address, holders, shared: role ? "role" : "line" });
298
+ return;
299
+ }
233
300
  if (!addressGroupJoins(people.size))
234
301
  return proposeEachPair(pass, people, "email");
235
302
  const contact = holders.find(({ provider }) => provider === "email");
@@ -343,6 +410,7 @@ export const scanMatches = (context, { full = false } = {}) => {
343
410
  context,
344
411
  index: linkIndex(database),
345
412
  result: { full: changed === undefined, merged: [], proposed: [], skipped: [] },
413
+ shared: [],
346
414
  };
347
415
  for (const [address, holders] of emailHolders(database))
348
416
  if (holders.length > 1 && touched(holders))
@@ -350,6 +418,8 @@ export const scanMatches = (context, { full = false } = {}) => {
350
418
  for (const holders of phoneHolders(database).values())
351
419
  if (holders.length > 1 && touched(holders))
352
420
  write(database, () => samePhone(pass, holders));
421
+ for (const group of pass.shared)
422
+ write(database, () => proposeShared(pass, group));
353
423
  for (const row of guestRows(database))
354
424
  if ((changed === undefined || changed.has(row.identity)) && !pass.index.names(row.ref))
355
425
  write(database, () => guestEmail(pass, row));