@wirecat/cli-core 0.634.0 → 0.636.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 (66) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/dist/cli/bot/people.js +1 -1
  3. package/dist/cli/messenger/contacts-command.js +6 -2
  4. package/dist/domain/display-names.d.ts +20 -2
  5. package/dist/domain/display-names.js +21 -2
  6. package/dist/entities/contact-activity.d.ts +2 -0
  7. package/dist/entities/contact-activity.js +2 -0
  8. package/dist/entities/contact-context.d.ts +3 -0
  9. package/dist/entities/index.d.ts +3 -0
  10. package/dist/errors/reasons.js +9 -0
  11. package/dist/search/groups.d.ts +2 -0
  12. package/dist/search/groups.js +1 -0
  13. package/dist/services/account-groups.d.ts +30 -1
  14. package/dist/services/account-groups.js +27 -0
  15. package/dist/services/index.d.ts +1 -1
  16. package/dist/services/index.js +1 -1
  17. package/dist/services/metadata.d.ts +1 -1
  18. package/dist/services/people.d.ts +5 -1
  19. package/dist/services/people.js +18 -5
  20. package/dist/services/stored-project-gathering.d.ts +2 -0
  21. package/dist/services/stored-project-gathering.js +1 -1
  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 +1 -1
  27. package/dist/store/identity-links.d.ts +23 -0
  28. package/dist/store/identity-splits.d.ts +2 -0
  29. package/dist/store/index.d.ts +2 -2
  30. package/dist/store/keys.d.ts +1 -1
  31. package/dist/store/keys.js +1 -1
  32. package/dist/store/people.d.ts +17 -5
  33. package/dist/store/people.js +10 -3
  34. package/dist/store/sqlite/accounts.d.ts +12 -2
  35. package/dist/store/sqlite/accounts.js +42 -3
  36. package/dist/store/sqlite/address-organization.d.ts +18 -0
  37. package/dist/store/sqlite/address-organization.js +48 -0
  38. package/dist/store/sqlite/chats.d.ts +3 -1
  39. package/dist/store/sqlite/chats.js +8 -0
  40. package/dist/store/sqlite/identity-link-rows.d.ts +5 -1
  41. package/dist/store/sqlite/identity-link-rows.js +9 -3
  42. package/dist/store/sqlite/identity-proposals.d.ts +5 -3
  43. package/dist/store/sqlite/identity-proposals.js +85 -8
  44. package/dist/store/sqlite/identity-split-proposals.d.ts +5 -0
  45. package/dist/store/sqlite/identity-split-proposals.js +29 -1
  46. package/dist/store/sqlite/mail-findings.js +10 -44
  47. package/dist/store/sqlite/manifest.js +2 -0
  48. package/dist/store/sqlite/migrations.generated.js +14 -0
  49. package/dist/store/sqlite/name-traces.d.ts +5 -2
  50. package/dist/store/sqlite/name-traces.js +8 -5
  51. package/dist/store/sqlite/open-store.js +2 -0
  52. package/dist/store/sqlite/people-list.js +15 -9
  53. package/dist/store/sqlite/person-doubts.d.ts +15 -1
  54. package/dist/store/sqlite/person-doubts.js +51 -9
  55. package/dist/store/sqlite/person-links.d.ts +7 -2
  56. package/dist/store/sqlite/person-links.js +33 -2
  57. package/dist/store/sqlite/person-match-scan.d.ts +14 -0
  58. package/dist/store/sqlite/person-match-scan.js +101 -5
  59. package/dist/store/sqlite/person-merges.d.ts +1 -0
  60. package/dist/store/sqlite/person-merges.js +4 -8
  61. package/dist/store/sqlite/task-titles.d.ts +12 -1
  62. package/dist/store/sqlite/task-titles.js +42 -1
  63. package/dist/store/sqlite/tasks.js +6 -1
  64. package/dist/store/types.d.ts +6 -0
  65. package/package.json +3 -3
  66. package/parity.json +6 -3
@@ -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";
@@ -40,8 +42,17 @@ export const openIdentityLink = (context, opening, index) => write(context.datab
40
42
  const operations = proposalOperationsOver(context);
41
43
  const links = index ?? linkIndex(context.database);
42
44
  const open = links.open(from, to);
43
- if (open)
45
+ if (open) {
46
+ // NEED-2529: a rule's proposal from before scores were recorded takes its score when the scan meets it again.
47
+ if (open.payload.score === null && opening.score !== undefined && open.payload.signal === opening.signal) {
48
+ context.database
49
+ .prepare("UPDATE proposed_actions SET payload = json_set(payload, '$.score', ?), updated_at = ? " +
50
+ "WHERE id = ? AND status = 'proposed'")
51
+ .run(opening.score, context.now(), Number(open.id));
52
+ open.payload.score = opening.score;
53
+ }
44
54
  return { outcome: "open", action: operations.get(open.id) };
55
+ }
45
56
  const identity = refOf(context, opening.identity);
46
57
  const other = opening.with === null ? null : refOf(context, opening.with);
47
58
  if (links.rejected(from, to)?.has(evidenceKeyOf({ signal: opening.signal, identity, with: other })))
@@ -56,6 +67,8 @@ export const openIdentityLink = (context, opening, index) => write(context.datab
56
67
  score: opening.score ?? null,
57
68
  ...(opening.candidates && opening.candidates.length > 2 ? { candidates: opening.candidates.map(String) } : {}),
58
69
  evidence: opening.evidence ?? [],
70
+ ...(opening.shared === undefined ? {} : { shared: opening.shared }),
71
+ ...(opening.mailbox === undefined ? {} : { mailbox: opening.mailbox }),
59
72
  };
60
73
  const action = operations.propose({
61
74
  kind: IDENTITY_LINK_KIND,
@@ -145,6 +158,62 @@ const settleMentions = ({ database, now }, payload, to) => {
145
158
  "AND target_id = ?")
146
159
  .run(to, now(), Number(identity.id));
147
160
  };
161
+ const organizationExists = ({ database }, id) => Number.isSafeInteger(id) &&
162
+ database.prepare("SELECT 1 FROM organizations WHERE id = ? AND deleted_at IS NULL").get(id) !== undefined;
163
+ /**
164
+ * NEED-2528: the shared mailbox is a company's, not one of the two people. The address goes to the organization and
165
+ * the proposal is turned down, so the pair is not proposed again on it (the rejected evidence), and nobody is joined.
166
+ */
167
+ const toCompany = (context, proposal, company, author, noted) => {
168
+ const payload = proposal.payload;
169
+ if (proposal.status !== "proposed")
170
+ throw new CliError("validation_error", `${proposal.id} is already ${proposal.status}`, {
171
+ reason: "proposal.wrong-state",
172
+ });
173
+ const address = payload.mailbox;
174
+ if (payload.shared === undefined || address === undefined)
175
+ throw new CliError("validation_error", `${proposal.id} is not about a shared mailbox; confirm or reject it`, {
176
+ reason: "identity.not-shared",
177
+ });
178
+ const name = company.name?.trim() || undefined;
179
+ const domain = address.split("@")[1] ?? "";
180
+ let organization;
181
+ if (company.organization !== undefined) {
182
+ if (!organizationExists(context, company.organization))
183
+ throw new CliError("not_found", `no organization:${company.organization}`, { reason: "organization.not-found" });
184
+ organization = company.organization;
185
+ holdAddress(context, organization, address, { method: CONFIRMED, author: "owner" });
186
+ }
187
+ else {
188
+ if (name === undefined && FREE_MAIL.has(domain))
189
+ throw new CliError("validation_error", `${address} is a free mailbox; name the company or its organization`, {
190
+ reason: "organization.unnamed",
191
+ });
192
+ organization = organizationOfAddress(context, {
193
+ name: name ?? domain,
194
+ email: address,
195
+ method: CONFIRMED,
196
+ author: "owner",
197
+ reason: "organization.ambiguous",
198
+ });
199
+ }
200
+ const operations = proposalOperationsOver(context);
201
+ const others = company.all
202
+ ? context.database
203
+ .prepare("SELECT id FROM proposed_actions WHERE kind = ? AND status = 'proposed' AND id <> ? " +
204
+ "AND json_extract(payload, '$.mailbox') = ? ORDER BY id")
205
+ .all(IDENTITY_LINK_KIND, Number(proposal.id), address)
206
+ .map((row) => String(row.id))
207
+ : [];
208
+ const result = { dismissed: true, organization: `organization:${organization}`, ...noted };
209
+ for (const other of others) {
210
+ const closed = operations.reject(other, author, { ...result, with: proposal.id });
211
+ settleMentions(context, closed.payload, "found");
212
+ }
213
+ const rejected = operations.reject(proposal.id, author, { ...result, closed: [proposal.id, ...others] });
214
+ settleMentions(context, payload, "found");
215
+ return rejected;
216
+ };
148
217
  /**
149
218
  * Decides an `identity_link`, the owner's alone. Confirm links the two people as the owner's link, refused with
150
219
  * `identity.stale` when either person changed since it was proposed; reject keeps them apart, and only new evidence
@@ -159,6 +228,11 @@ export const decideIdentityLink = (context, id, decision) => write(context.datab
159
228
  const author = deciderAuthor(decision.by);
160
229
  const reason = decision.reason?.trim() || undefined;
161
230
  const noted = reason === undefined ? {} : { reason };
231
+ if (decision.company !== undefined) {
232
+ if (decision.confirm)
233
+ throw new CliError("validation_error", "a company's mailbox keeps the two people apart; it is not a confirm");
234
+ return toCompany(context, proposal, decision.company, author, noted);
235
+ }
162
236
  if (!decision.confirm) {
163
237
  const rejected = operations.reject(id, author, { dismissed: true, ...noted });
164
238
  settleMentions(context, proposal.payload, "found");
@@ -200,8 +274,10 @@ const SHOWN = {
200
274
  executed: "confirmed",
201
275
  failed: "confirmed",
202
276
  };
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 }) => {
277
+ /** Newest first in, highest score first out, proposals without a score last; a stable sort keeps the dates' order. */
278
+ const byOrder = (rows, order) => order !== "score" ? rows : rows.sort((a, b) => (b.payload.score ?? -1) - (a.payload.score ?? -1));
279
+ /** The `identity_link` proposals, newest first or by score, each naming its people as they are now; a page and whether more follow. */
280
+ export const identityLinkRows = (context, { person, status = "proposed", order = "newest", limit, offset }) => {
205
281
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
206
282
  throw new CliError("validation_error", "a list of link proposals takes 1–500 items");
207
283
  const asked = person === undefined ? undefined : currentPerson(context.database, Number(person));
@@ -209,11 +285,10 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
209
285
  const statuses = Object.keys(SHOWN).filter((one) => status === "all" || SHOWN[one] === status);
210
286
  // Whose a proposal is now depends on merges since, so only a list for one person reads every proposal.
211
287
  const rows = asked === undefined
212
- ? linkRows(context.database, statuses, { limit: limit + 1, offset })
213
- : linkRows(context.database, statuses)
288
+ ? linkRows(context.database, statuses, { limit: limit + 1, offset, order })
289
+ : byOrder(linkRows(context.database, statuses)
214
290
  .filter((row) => row.pair?.includes(asked) ?? false)
215
- .reverse()
216
- .slice(offset, offset + limit + 1);
291
+ .reverse(), order).slice(offset, offset + limit + 1);
217
292
  const items = rows.slice(0, limit).map((row) => {
218
293
  const action = operations.get(row.id);
219
294
  const payload = row.payload;
@@ -227,6 +302,8 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
227
302
  joins: payload.joins,
228
303
  signal: payload.signal,
229
304
  score: payload.score,
305
+ shared: payload.shared ?? null,
306
+ mailbox: payload.mailbox ?? null,
230
307
  candidates: (payload.candidates ?? []).map((uid) => `person:${uid}`),
231
308
  reason: action.reason,
232
309
  evidence: payload.evidence,
@@ -7,6 +7,11 @@ import { type ProposedAction } from "./proposed-actions.js";
7
7
  * `people doubts` leaves them out. One that moved since counts no longer.
8
8
  */
9
9
  export declare const keptTogether: (database: CacheDatabase) => Map<number, Set<string>>;
10
+ /**
11
+ * The owner says these identities belong on this person: recorded as a split the owner turned down, which is what
12
+ * `keptTogether` reads, so it lapses as soon as one of them moves. An agent's open split of any of them is turned down.
13
+ */
14
+ export declare const keepTogether: (context: StoreContext, person: number, identities: readonly string[]) => ProposedAction;
10
15
  /**
11
16
  * Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides. An
12
17
  * open proposal for the same identities is given back instead of a second, brought up to date with the person as it
@@ -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", {
@@ -73,6 +75,32 @@ export const keptTogether = (database) => {
73
75
  }
74
76
  return kept;
75
77
  };
78
+ /**
79
+ * The owner says these identities belong on this person: recorded as a split the owner turned down, which is what
80
+ * `keptTogether` reads, so it lapses as soon as one of them moves. An agent's open split of any of them is turned down.
81
+ */
82
+ export const keepTogether = (context, person, identities) => {
83
+ const operations = proposalOperationsOver(context);
84
+ const payload = {
85
+ split: "unlink",
86
+ person: String(person),
87
+ identities: [...identities],
88
+ merge: null,
89
+ side: sideOf(context.database, person),
90
+ evidence: [],
91
+ };
92
+ const keeping = new Set(identities);
93
+ for (const row of splitRows(context.database, ["proposed"]))
94
+ if (holder(context.database, row.payload) === person && row.payload.identities.some((ref) => keeping.has(ref)))
95
+ operations.reject(row.id, "owner", { reason: "the owner kept them" });
96
+ const proposed = operations.propose({
97
+ kind: IDENTITY_SPLIT_KIND,
98
+ by: "owner",
99
+ payload,
100
+ reason: "the owner kept them",
101
+ });
102
+ return operations.reject(proposed.id, "owner", { reason: "the owner kept them" });
103
+ };
76
104
  /**
77
105
  * Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides. An
78
106
  * open proposal for the same identities is given back instead of a second, brought up to date with the person as it
@@ -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,8 @@ 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 },
133
+ { name: "20261110233711_version-66-identity-name-trigger", version: 66, minCompatible: 56 },
132
134
  ];
133
135
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
134
136
  const migrations = [];
@@ -1321,5 +1321,19 @@ 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
+ ]
1330
+ },
1331
+ {
1332
+ "name": "20261110233711_version-66-identity-name-trigger",
1333
+ "statements": [
1334
+ "DROP TRIGGER IF EXISTS person_kind_identity_au;",
1335
+ "CREATE TRIGGER person_kind_identity_au AFTER UPDATE OF provider, external_id, name, username, phone, email, bot ON identities\nWHEN OLD.provider IS NOT NEW.provider OR OLD.external_id IS NOT NEW.external_id OR OLD.name IS NOT NEW.name OR OLD.username IS NOT NEW.username OR OLD.phone IS NOT NEW.phone OR OLD.email IS NOT NEW.email OR OLD.bot IS NOT NEW.bot BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.id);\nEND;",
1336
+ "UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND trim(coalesce(name, '')) = '';"
1337
+ ]
1324
1338
  }
1325
1339
  ];
@@ -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);
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
3
- import { displayName, isReadable, nameKey } from "../../domain/display-names.js";
3
+ import { displayName, isReadable, nameKey, takeFallbacks } from "../../domain/display-names.js";
4
4
  import { spellings, variantKey } from "../../domain/name-variants.js";
5
5
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
6
6
  import { isQueryOnly } from "../driver.js";
@@ -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,12 +78,17 @@ 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);
80
- if (one.username === null && text(row.username) !== null) {
81
- one.username = text(row.username);
81
+ const hadUsername = one.username !== null;
82
+ takeFallbacks(one, {
83
+ provider: String(row.provider),
84
+ id: String(row.external_id),
85
+ name: text(row.name),
86
+ username: text(row.username),
87
+ phone: text(row.phone),
88
+ email: text(row.email),
89
+ });
90
+ if (!hadUsername && one.username !== null)
82
91
  one.usernameSource = String(row.provider);
83
- }
84
- one.phone ??= text(row.phone) ?? (row.provider === "phone" ? text(row.external_id) : null);
85
- one.email ??= email;
86
92
  if (email !== null)
87
93
  one.emails.push(email);
88
94
  one.bot ||= Number(row.bot) === 1;
@@ -143,7 +149,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
143
149
  return people.map(({ id, name, owner }) => {
144
150
  const own = facts.get(id);
145
151
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
146
- const shown = displayName(name, contact);
152
+ const shown = displayName(name, { ...contact, name: own?.name ?? null });
147
153
  const ties = reasons.get(id) ?? [];
148
154
  const { kind, signals } = kindOf(shown, own, ties, mail.get(id));
149
155
  return {
@@ -179,7 +185,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
179
185
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
180
186
  * every stored one is worked out again on the next list.
181
187
  */
182
- const KIND_RULES = "2";
188
+ const KIND_RULES = "3";
183
189
  const RULES_KEY = "people.kind_rules";
184
190
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
185
191
  const WHOLE_PASS = 20_000;
@@ -1,3 +1,4 @@
1
+ import type { Decider } from "../decisions.js";
1
2
  import type { StoreContext } from "./open.js";
2
3
  /** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
3
4
  export declare const DOUBT_REASONS: readonly ["owner-other-name", "test-data", "shared-address", "mixed-names"];
@@ -30,9 +31,12 @@ export interface PersonDoubt {
30
31
  export type DoubtMove = {
31
32
  op: "unmerge";
32
33
  merge: string;
33
- } | {
34
+ }
35
+ /** `from` is the person they leave, `person:<uid>`. */
36
+ | {
34
37
  op: "unlink";
35
38
  identities: string[];
39
+ from: string;
36
40
  };
37
41
  export interface PersonDoubts {
38
42
  items: PersonDoubt[];
@@ -44,3 +48,13 @@ export declare const personDoubts: (context: StoreContext, { limit, offset }: {
44
48
  limit: number;
45
49
  offset: number;
46
50
  }) => PersonDoubts;
51
+ export interface KeptPerson {
52
+ person: string;
53
+ /** The identities the owner said belong here; a doubt about them comes back once one of them moves. */
54
+ kept: string[];
55
+ }
56
+ /**
57
+ * The owner's answer to a doubt: this person is right as they are. Test data is not a link and stays listed. Refused
58
+ * when nothing about the person is in doubt.
59
+ */
60
+ export declare const keepPerson: (context: StoreContext, uid: string, by: Decider) => KeptPerson;
@@ -2,8 +2,9 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { displayName } from "../../domain/display-names.js";
3
3
  import { nameSkeletons } from "../../domain/name-variants.js";
4
4
  import { RESERVED_ADDRESS_GLOBS, SEED_ID_GLOBS, SEED_PEOPLE } from "../../domain/test-data.js";
5
- import { keptTogether } from "./identity-split-proposals.js";
6
- import { merges } from "./person-merges.js";
5
+ import { keepTogether, keptTogether } from "./identity-split-proposals.js";
6
+ import { currentPerson } from "./merged-persons.js";
7
+ import { merges, ownerOnly } from "./person-merges.js";
7
8
  /** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
8
9
  export const DOUBT_REASONS = ["owner-other-name", "test-data", "shared-address", "mixed-names"];
9
10
  const COLUMNS = "l.person_id AS person, p.owner, p.name AS person_name, i.id AS pk, i.provider, i.external_id, i.name, i.phone, " +
@@ -121,7 +122,7 @@ const doubtsOf = (held, kept, test) => {
121
122
  .filter(({ by, ref }) => by !== "owner" && !kept.has(ref));
122
123
  const base = { person: first.person, owner: first.owner, name: first.personName };
123
124
  if (first.owner)
124
- return outside.length ? [{ ...base, reason: "owner-other-name", held: outside }] : [];
125
+ return outside.length ? [{ ...base, reason: "owner-other-name", held: outside, doubted: outside }] : [];
125
126
  const found = [];
126
127
  const mixed = [];
127
128
  for (const one of outside) {
@@ -129,12 +130,16 @@ const doubtsOf = (held, kept, test) => {
129
130
  continue;
130
131
  const address = one.email === null ? undefined : main.find(({ email }) => email === one.email)?.email;
131
132
  if (typeof address === "string")
132
- found.push({ ...base, reason: "shared-address", held: [one], address });
133
+ found.push({ ...base, reason: "shared-address", held: [one], address, doubted: [one] });
133
134
  else
134
135
  mixed.push(one);
135
136
  }
136
- if (mixed.length)
137
- found.push({ ...base, reason: "mixed-names", held: [...main, ...mixed] });
137
+ // A link only moves the identities of the person joining, so the ones already here keep a rule's method, though the
138
+ // owner saw their names beside the new one. A shared address is not something a name shows, so it stays.
139
+ const vouched = held.reduce((newest, { by, at }) => (by === "owner" && at > newest ? at : newest), -Infinity);
140
+ const unseen = mixed.filter(({ at }) => at > vouched);
141
+ if (unseen.length)
142
+ found.push({ ...base, reason: "mixed-names", held: [...main, ...unseen], doubted: unseen });
138
143
  return found;
139
144
  };
140
145
  const byPerson = (held) => {
@@ -160,7 +165,14 @@ const everyDoubt = (database) => {
160
165
  found.push(one);
161
166
  for (const held of byPerson(test).values()) {
162
167
  const [first] = held;
163
- found.push({ person: first.person, owner: first.owner, name: first.personName, reason: "test-data", held });
168
+ found.push({
169
+ person: first.person,
170
+ owner: first.owner,
171
+ name: first.personName,
172
+ reason: "test-data",
173
+ held,
174
+ doubted: [],
175
+ });
164
176
  }
165
177
  return found.sort((a, b) => Number(b.owner) - Number(a.owner) ||
166
178
  (ORDER.get(a.reason) ?? 0) - (ORDER.get(b.reason) ?? 0) ||
@@ -186,10 +198,12 @@ const movesOf = (context, found) => {
186
198
  }
187
199
  const rest = found.held.filter(({ ref }) => !unmerged.has(ref));
188
200
  for (const group of nameGroups(rest))
189
- moves.push({ op: "unlink", identities: group.map(({ ref }) => ref) });
201
+ moves.push({ op: "unlink", identities: group.map(({ ref }) => ref), from: `person:${found.person}` });
190
202
  return moves;
191
203
  };
192
- const commandOf = (move) => move.op === "unmerge" ? `people unmerge ${move.merge}` : `people unlink ${move.identities.map(shellWord).join(" ")}`;
204
+ const commandOf = (move) => move.op === "unmerge"
205
+ ? `people unmerge ${move.merge}`
206
+ : `people unlink ${move.identities.map(shellWord).join(" ")} --from ${move.from}`;
193
207
  /** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
194
208
  const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
195
209
  const shown = (context, found) => {
@@ -229,3 +243,31 @@ export const personDoubts = (context, { limit, offset }) => {
229
243
  hasMore: found.length > offset + limit,
230
244
  };
231
245
  };
246
+ /**
247
+ * The owner's answer to a doubt: this person is right as they are. Test data is not a link and stays listed. Refused
248
+ * when nothing about the person is in doubt.
249
+ */
250
+ export const keepPerson = (context, uid, by) => {
251
+ ownerOnly(by, "says a person's links are right");
252
+ const asked = /^(?:person:)?([1-9]\d*)$/u.exec(uid.trim())?.[1];
253
+ const known = asked === undefined || !Number.isSafeInteger(Number(asked))
254
+ ? undefined
255
+ : context.database.prepare("SELECT id FROM persons WHERE id = ?").get(Number(asked));
256
+ if (known === undefined)
257
+ throw new CliError("not_found", `the store has no person for "${uid}"`, { reason: "person.unknown" });
258
+ const person = currentPerson(context.database, Number(known.id));
259
+ const held = context.database.prepare(`SELECT ${COLUMNS} WHERE l.person_id = ? ORDER BY i.id`).all(person).map(heldOf);
260
+ const test = new Set(testData(context.database).map(({ pk }) => pk));
261
+ const doubted = [
262
+ ...new Set(doubtsOf(held, keptTogether(context.database).get(person) ?? new Set(), test).flatMap((found) => found.doubted.map(({ ref }) => ref))),
263
+ ];
264
+ if (doubted.length === 0) {
265
+ if (held.some(({ pk }) => test.has(pk)))
266
+ throw new CliError("validation_error", `person:${person} is in doubt only as test data, which is not kept`, {
267
+ reason: "person.test-data",
268
+ });
269
+ throw new CliError("not_found", `nothing about person:${person} is in doubt`, { reason: "person.no-doubt" });
270
+ }
271
+ keepTogether(context, person, doubted);
272
+ return { person: `person:${person}`, kept: doubted };
273
+ };
@@ -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;