@wirecat/cli-core 0.617.0 → 0.619.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 (306) hide show
  1. package/CHANGELOG.md +406 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/backfill.d.ts +21 -0
  5. package/dist/background/backfill.js +41 -0
  6. package/dist/background/daily-archive-timer.d.ts +1 -1
  7. package/dist/background/deliver.d.ts +5 -2
  8. package/dist/background/deliver.js +30 -12
  9. package/dist/background/report/messages.js +4 -1
  10. package/dist/background/report/render.d.ts +3 -1
  11. package/dist/background/report/render.js +3 -1
  12. package/dist/background/report/view.js +4 -1
  13. package/dist/background/schedules.d.ts +17 -0
  14. package/dist/background/schedules.js +21 -8
  15. package/dist/calendar/cli/answers.d.ts +1 -0
  16. package/dist/calendar/cli/answers.js +6 -1
  17. package/dist/calendar/cli/index.js +2 -14
  18. package/dist/calendar/cli/people-link.d.ts +3 -0
  19. package/dist/calendar/cli/people-link.js +23 -0
  20. package/dist/calendar/index.d.ts +1 -1
  21. package/dist/calendar/index.js +1 -1
  22. package/dist/calendar/mcp/index.d.ts +12 -12
  23. package/dist/cli/base-stages-command.d.ts +22 -0
  24. package/dist/cli/base-stages-command.js +174 -0
  25. package/dist/cli/command-runs.d.ts +2 -0
  26. package/dist/cli/command-runs.js +3 -1
  27. package/dist/cli/config-command.js +6 -1
  28. package/dist/cli/context.d.ts +5 -0
  29. package/dist/cli/context.js +1 -0
  30. package/dist/cli/group-lock.d.ts +42 -0
  31. package/dist/cli/group-lock.js +130 -0
  32. package/dist/cli/index.d.ts +10 -4
  33. package/dist/cli/index.js +10 -4
  34. package/dist/cli/messenger/backfill-command.js +27 -15
  35. package/dist/cli/messenger/contacts-command.js +10 -3
  36. package/dist/cli/messenger/context.js +1 -0
  37. package/dist/cli/messenger/doctor-command.js +3 -1
  38. package/dist/cli/messenger/models-command.js +1 -1
  39. package/dist/cli/messenger/serve-command.js +24 -2
  40. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  41. package/dist/cli/messenger/serve-outdated.js +100 -0
  42. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  43. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  44. package/dist/cli/model-catalogue-command.d.ts +3 -1
  45. package/dist/cli/model-catalogue-command.js +46 -2
  46. package/dist/cli/profile.d.ts +8 -0
  47. package/dist/cli/profile.js +25 -0
  48. package/dist/cli/program.js +2 -0
  49. package/dist/cli/runs/search-query.d.ts +1 -1
  50. package/dist/cli/runs/search-query.js +4 -0
  51. package/dist/cli/runs/search.d.ts +5 -1
  52. package/dist/cli/runs/search.js +12 -1
  53. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  54. package/dist/cli/schedule/schedule-command.js +13 -0
  55. package/dist/cli/search-left-out.d.ts +6 -1
  56. package/dist/cli/search-left-out.js +9 -4
  57. package/dist/cli/settings.d.ts +8 -0
  58. package/dist/cli/settings.js +17 -2
  59. package/dist/cli/shared-command-exports.d.ts +16 -0
  60. package/dist/cli/store-recover.d.ts +3 -3
  61. package/dist/cli/store-recover.js +47 -23
  62. package/dist/cli/store-settings.d.ts +2 -0
  63. package/dist/cli/store-settings.js +37 -9
  64. package/dist/crm/cli/index.js +38 -6
  65. package/dist/crm/group-hint.d.ts +8 -0
  66. package/dist/crm/group-hint.js +13 -0
  67. package/dist/crm/source.d.ts +12 -1
  68. package/dist/crm/sync.d.ts +31 -2
  69. package/dist/crm/sync.js +110 -3
  70. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  71. package/dist/crm/testing/acme-scenario.js +170 -0
  72. package/dist/crm/testing/index.d.ts +1 -0
  73. package/dist/crm/testing/index.js +1 -0
  74. package/dist/crm/testing/source-contract.js +12 -0
  75. package/dist/crm/testing/source.d.ts +2 -0
  76. package/dist/crm/testing/source.js +1 -0
  77. package/dist/domain/addresses.d.ts +13 -0
  78. package/dist/domain/addresses.js +63 -0
  79. package/dist/domain/categories.d.ts +3 -0
  80. package/dist/domain/categories.js +2 -0
  81. package/dist/domain/crm.d.ts +23 -0
  82. package/dist/domain/crm.js +7 -0
  83. package/dist/domain/links.d.ts +17 -4
  84. package/dist/domain/links.js +20 -7
  85. package/dist/domain/mentions.d.ts +2 -12
  86. package/dist/domain/mentions.js +2 -19
  87. package/dist/domain/orders.d.ts +8 -1
  88. package/dist/domain/orders.js +6 -2
  89. package/dist/domain/phones.d.ts +26 -0
  90. package/dist/domain/phones.js +48 -0
  91. package/dist/domain/record-types.d.ts +1 -1
  92. package/dist/domain/record-types.js +1 -0
  93. package/dist/domain/records.d.ts +5 -0
  94. package/dist/domain/ref-summaries.d.ts +39 -0
  95. package/dist/domain/ref-summaries.js +51 -3
  96. package/dist/domain/relations.d.ts +27 -2
  97. package/dist/domain/relations.js +37 -3
  98. package/dist/domain/vcard.d.ts +2 -2
  99. package/dist/domain/vcard.js +4 -10
  100. package/dist/embeddings/models.d.ts +11 -3
  101. package/dist/embeddings/models.js +28 -4
  102. package/dist/entities/business-context.d.ts +149 -0
  103. package/dist/entities/business-context.js +192 -0
  104. package/dist/entities/contact-activity.d.ts +2 -0
  105. package/dist/entities/contact-activity.js +7 -1
  106. package/dist/entities/contact-context.d.ts +157 -0
  107. package/dist/entities/contact-context.js +2 -0
  108. package/dist/entities/deal.d.ts +10 -0
  109. package/dist/entities/deal.js +2 -0
  110. package/dist/entities/index.d.ts +23 -3
  111. package/dist/entities/index.js +5 -0
  112. package/dist/entities/mention.d.ts +4 -3
  113. package/dist/entities/mention.js +2 -1
  114. package/dist/entities/message-transfer.d.ts +4 -2
  115. package/dist/entities/message-transfer.js +2 -2
  116. package/dist/entities/model.d.ts +2 -2
  117. package/dist/entities/model.js +1 -1
  118. package/dist/entities/relationship.d.ts +4 -0
  119. package/dist/entities/relationship.js +4 -0
  120. package/dist/errors/reasons.js +44 -4
  121. package/dist/fetch/page.js +2 -1
  122. package/dist/index.d.ts +4 -3
  123. package/dist/index.js +4 -3
  124. package/dist/meetings/context-store.d.ts +2 -0
  125. package/dist/meetings/findings-rules.d.ts +4 -0
  126. package/dist/meetings/findings-rules.js +5 -2
  127. package/dist/meetings/mcp/index.d.ts +15 -15
  128. package/dist/meetings/result-items.d.ts +1 -0
  129. package/dist/meetings/result-items.js +1 -0
  130. package/dist/models/index.js +22 -5
  131. package/dist/runs/events.d.ts +11 -1
  132. package/dist/runs/events.js +3 -1
  133. package/dist/runs/log-attributes.js +4 -0
  134. package/dist/runs/log-events.js +2 -0
  135. package/dist/runs/recording.d.ts +3 -0
  136. package/dist/runs/recording.js +36 -12
  137. package/dist/runs/run.d.ts +12 -3
  138. package/dist/runs/run.js +32 -13
  139. package/dist/search/account-list.d.ts +6 -0
  140. package/dist/search/account-list.js +9 -3
  141. package/dist/search/groups.d.ts +68 -0
  142. package/dist/search/groups.js +172 -0
  143. package/dist/services/account-groups.d.ts +28 -0
  144. package/dist/services/account-groups.js +89 -0
  145. package/dist/services/archive.d.ts +7 -1
  146. package/dist/services/archive.js +19 -3
  147. package/dist/services/business-context.d.ts +113 -0
  148. package/dist/services/business-context.js +156 -0
  149. package/dist/services/communications.d.ts +50 -0
  150. package/dist/services/communications.js +140 -0
  151. package/dist/services/deal-context.d.ts +90 -0
  152. package/dist/services/deal-context.js +131 -0
  153. package/dist/services/deps.d.ts +2 -0
  154. package/dist/services/enrichment.d.ts +7 -2
  155. package/dist/services/enrichment.js +46 -5
  156. package/dist/services/events-search.js +2 -1
  157. package/dist/services/group-guard.d.ts +28 -0
  158. package/dist/services/group-guard.js +131 -0
  159. package/dist/services/index.d.ts +15 -2
  160. package/dist/services/index.js +9 -2
  161. package/dist/services/ingest.d.ts +12 -0
  162. package/dist/services/ingest.js +4 -0
  163. package/dist/services/link-scorers/chat-senders.js +39 -29
  164. package/dist/services/link-scorers/member-chats.js +4 -3
  165. package/dist/services/link-scorers/member-dialog.js +5 -7
  166. package/dist/services/link-scorers/scan.js +17 -8
  167. package/dist/services/link-scorers/shared.d.ts +6 -2
  168. package/dist/services/link-scorers/shared.js +6 -2
  169. package/dist/services/link-scorers/types.d.ts +2 -0
  170. package/dist/services/meaning-model.d.ts +7 -0
  171. package/dist/services/meaning-model.js +20 -0
  172. package/dist/services/meeting-context.d.ts +6 -1
  173. package/dist/services/meeting-context.js +12 -5
  174. package/dist/services/message-resolution.js +2 -3
  175. package/dist/services/messages-meaning.js +4 -5
  176. package/dist/services/messages-search.d.ts +5 -1
  177. package/dist/services/messages-search.js +1 -1
  178. package/dist/services/model-downloads.d.ts +1 -1
  179. package/dist/services/model-downloads.js +6 -4
  180. package/dist/services/money-context.d.ts +73 -0
  181. package/dist/services/money-context.js +77 -0
  182. package/dist/services/notes-search.d.ts +4 -1
  183. package/dist/services/notes-search.js +19 -7
  184. package/dist/services/organization-context.d.ts +80 -0
  185. package/dist/services/organization-context.js +154 -0
  186. package/dist/services/people.d.ts +22 -6
  187. package/dist/services/people.js +38 -8
  188. package/dist/services/person-business.d.ts +43 -0
  189. package/dist/services/person-business.js +67 -0
  190. package/dist/services/person-context.d.ts +9 -1
  191. package/dist/services/person-context.js +5 -3
  192. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  193. package/dist/services/proposals/kinds/identity-link.js +48 -0
  194. package/dist/services/proposals/kinds/orders.js +1 -1
  195. package/dist/services/proposals/registry.js +2 -0
  196. package/dist/services/search-kind.d.ts +12 -5
  197. package/dist/services/search-kind.js +49 -10
  198. package/dist/services/text-model-choice.js +1 -1
  199. package/dist/store/accounts.d.ts +18 -0
  200. package/dist/store/accounts.js +18 -3
  201. package/dist/store/damage.d.ts +43 -10
  202. package/dist/store/damage.js +119 -36
  203. package/dist/store/decisions.js +3 -1
  204. package/dist/store/evidence-findings.d.ts +14 -0
  205. package/dist/store/evidence-findings.js +2 -0
  206. package/dist/store/exports.d.ts +2 -1
  207. package/dist/store/identity-links.d.ts +92 -0
  208. package/dist/store/identity-links.js +6 -0
  209. package/dist/store/index.d.ts +11 -5
  210. package/dist/store/index.js +5 -2
  211. package/dist/store/journal.d.ts +10 -0
  212. package/dist/store/journal.js +33 -0
  213. package/dist/store/marks.d.ts +19 -1
  214. package/dist/store/marks.js +23 -1
  215. package/dist/store/migrations.d.ts +1 -1
  216. package/dist/store/migrations.js +35 -12
  217. package/dist/store/people.d.ts +22 -0
  218. package/dist/store/people.js +15 -1
  219. package/dist/store/recover.d.ts +34 -0
  220. package/dist/store/recover.js +188 -6
  221. package/dist/store/refill.d.ts +28 -0
  222. package/dist/store/refill.js +120 -0
  223. package/dist/store/sqlite/accounts.js +2 -0
  224. package/dist/store/sqlite/base-stages.d.ts +122 -0
  225. package/dist/store/sqlite/base-stages.js +443 -0
  226. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  227. package/dist/store/sqlite/base-suggest.js +62 -0
  228. package/dist/store/sqlite/business-contracts.js +10 -1
  229. package/dist/store/sqlite/clients.d.ts +7 -3
  230. package/dist/store/sqlite/clients.js +11 -7
  231. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  232. package/dist/store/sqlite/crm-settings.js +56 -13
  233. package/dist/store/sqlite/crm.d.ts +13 -1
  234. package/dist/store/sqlite/crm.js +20 -4
  235. package/dist/store/sqlite/deals.d.ts +33 -0
  236. package/dist/store/sqlite/deals.js +42 -4
  237. package/dist/store/sqlite/decision-requests.js +7 -3
  238. package/dist/store/sqlite/email-index.js +17 -15
  239. package/dist/store/sqlite/evidence-findings.js +29 -5
  240. package/dist/store/sqlite/findings-core.js +4 -2
  241. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  242. package/dist/store/sqlite/identity-link-rows.js +146 -0
  243. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  244. package/dist/store/sqlite/identity-proposals.js +234 -0
  245. package/dist/store/sqlite/knowledge.js +5 -3
  246. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  247. package/dist/store/sqlite/link-kinds.js +1 -0
  248. package/dist/store/sqlite/link-row.d.ts +6 -0
  249. package/dist/store/sqlite/link-row.js +35 -0
  250. package/dist/store/sqlite/link-source.d.ts +10 -0
  251. package/dist/store/sqlite/link-source.js +16 -0
  252. package/dist/store/sqlite/manifest.js +1 -0
  253. package/dist/store/sqlite/meeting-context-links.js +9 -6
  254. package/dist/store/sqlite/memories.js +9 -7
  255. package/dist/store/sqlite/mentions.d.ts +4 -1
  256. package/dist/store/sqlite/mentions.js +14 -9
  257. package/dist/store/sqlite/migrations.generated.js +8 -0
  258. package/dist/store/sqlite/note-index.js +9 -7
  259. package/dist/store/sqlite/notes.d.ts +2 -3
  260. package/dist/store/sqlite/notes.js +6 -29
  261. package/dist/store/sqlite/open-store.js +3 -0
  262. package/dist/store/sqlite/open.js +11 -2
  263. package/dist/store/sqlite/orders.d.ts +2 -0
  264. package/dist/store/sqlite/orders.js +9 -3
  265. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  266. package/dist/store/sqlite/organization-categories.js +34 -0
  267. package/dist/store/sqlite/organizations.d.ts +5 -1
  268. package/dist/store/sqlite/organizations.js +14 -4
  269. package/dist/store/sqlite/person-links.d.ts +19 -4
  270. package/dist/store/sqlite/person-links.js +49 -11
  271. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  272. package/dist/store/sqlite/person-match-scan.js +251 -0
  273. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  274. package/dist/store/sqlite/person-matcher.js +32 -0
  275. package/dist/store/sqlite/proposed-actions.js +6 -0
  276. package/dist/store/sqlite/record-matching.d.ts +2 -8
  277. package/dist/store/sqlite/record-matching.js +8 -40
  278. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  279. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  280. package/dist/store/sqlite/record-relationships.js +243 -0
  281. package/dist/store/sqlite/record-run.d.ts +5 -0
  282. package/dist/store/sqlite/record-run.js +62 -2
  283. package/dist/store/sqlite/record-writes.d.ts +1 -1
  284. package/dist/store/sqlite/record-writes.js +4 -2
  285. package/dist/store/sqlite/records.js +27 -2
  286. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  287. package/dist/store/sqlite/ref-accounts.js +117 -0
  288. package/dist/store/sqlite/ref-summaries.js +5 -1
  289. package/dist/store/sqlite/relation-list.d.ts +4 -1
  290. package/dist/store/sqlite/relation-list.js +20 -2
  291. package/dist/store/sqlite/relation-proposals.d.ts +18 -1
  292. package/dist/store/sqlite/relation-proposals.js +53 -11
  293. package/dist/store/sqlite/relation-roles.js +12 -6
  294. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  295. package/dist/store/sqlite/reported-relations.js +59 -18
  296. package/dist/store/sqlite/schema.d.ts +32 -0
  297. package/dist/store/sqlite/schema.js +3 -0
  298. package/dist/store/sqlite/transaction.d.ts +13 -0
  299. package/dist/store/sqlite/transaction.js +33 -15
  300. package/dist/store/store.d.ts +3 -0
  301. package/dist/store/store.js +5 -0
  302. package/dist/store/write-events.d.ts +18 -0
  303. package/dist/store/write-events.js +88 -0
  304. package/package.json +3 -3
  305. package/parity.json +11 -4
  306. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -0,0 +1,251 @@
1
+ import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { BARE_INTERNATIONAL_PROVIDERS, storedPhone } from "../../domain/phones.js";
3
+ import { linkIndex, settleLinks } from "./identity-link-rows.js";
4
+ import { openIdentityLink } from "./identity-proposals.js";
5
+ import { mergePerson } from "./person-links.js";
6
+ import { personsByIdentifiers } from "./person-matcher.js";
7
+ import { resolvePersonLinks } from "./person-resolution.js";
8
+ import { separated } from "./person-separation.js";
9
+ import { referenceOfThing } from "./things.js";
10
+ import { write } from "./transaction.js";
11
+ /** Who an automatic link is recorded as: never the owner, whose moves count as separations. */
12
+ const BY = "rule";
13
+ export const RULE = { bot: "rule", kind: "rule" };
14
+ /** More people than this on one number or address is a shared line or mailbox: nobody is proposed from it. */
15
+ const MOST_SHARING = 6;
16
+ const CURSOR = "people.scan";
17
+ /**
18
+ * NEED-2445, safe option until the owner rules: a number two people share joins them only when a messenger, which
19
+ * 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.
20
+ */
21
+ const phonePairJoins = (holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider));
22
+ /**
23
+ * NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. So is
24
+ * a role address such as `info@` or `hello@`, even when two people have it.
25
+ */
26
+ const addressGroupJoins = (address, people) => people <= 2 && !isRoleAddress(address);
27
+ const maxOf = (database, sql) => Number(database.prepare(sql).get()?.n ?? 0);
28
+ const cursorNow = (database) => ({
29
+ identity: maxOf(database, "SELECT max(id) AS n FROM identities"),
30
+ event: maxOf(database, "SELECT max(id) AS n FROM identity_link_events"),
31
+ revision: maxOf(database, "SELECT max(id) AS n FROM identity_revisions"),
32
+ participant: maxOf(database, "SELECT max(id) AS n FROM meeting_participants"),
33
+ at: maxOf(database, "SELECT max(updated_at) AS n FROM identities"),
34
+ });
35
+ const savedCursor = (database) => {
36
+ const value = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(CURSOR)?.value;
37
+ return value === undefined ? undefined : JSON.parse(String(value));
38
+ };
39
+ /** The identities changed since `since`: new ones, moved ones, edited ones and ones a new meeting guest row names. */
40
+ const changedSince = (database, since) => new Set(database
41
+ .prepare("SELECT id FROM identities WHERE id > ? OR updated_at > ? " +
42
+ "UNION SELECT identity_id FROM identity_link_events WHERE id > ? " +
43
+ "UNION SELECT identity_id FROM identity_revisions WHERE id > ? " +
44
+ "UNION SELECT identity_id FROM meeting_participants WHERE id > ?")
45
+ .all(since.identity, since.at, since.event, since.revision, since.participant)
46
+ .map(({ id }) => Number(id)));
47
+ const add = (found, key, holder) => {
48
+ if (key === undefined)
49
+ return;
50
+ const held = found.get(key) ?? [];
51
+ if (!held.some(({ identity }) => identity === holder.identity))
52
+ held.push(holder);
53
+ found.set(key, held);
54
+ };
55
+ const phoneHolders = (database) => {
56
+ const found = new Map();
57
+ for (const row of database
58
+ .prepare("SELECT i.id, i.provider, i.external_id, i.phone FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
59
+ "WHERE i.provider = 'phone' OR i.phone IS NOT NULL ORDER BY i.id")
60
+ .all()) {
61
+ const provider = String(row.provider);
62
+ const raw = String(provider === "phone" ? row.external_id : row.phone);
63
+ add(found, storedPhone(raw, provider), { identity: Number(row.id), provider });
64
+ }
65
+ return found;
66
+ };
67
+ const addressOf = (value) => {
68
+ const address = typeof value === "string" ? value.trim().toLowerCase() : "";
69
+ return isEmailAddress(address) ? address : undefined;
70
+ };
71
+ /** A company's address is an `org-email` identity, never a person's, so it never joins people. */
72
+ const emailHolders = (database) => {
73
+ const found = new Map();
74
+ for (const row of database
75
+ .prepare("SELECT i.id, i.provider, i.external_id, i.email FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
76
+ "WHERE i.provider <> 'org-email' AND (i.provider = 'email' OR i.email IS NOT NULL) ORDER BY i.id")
77
+ .all()) {
78
+ const holder = { identity: Number(row.id), provider: String(row.provider) };
79
+ add(found, addressOf(row.email), holder);
80
+ if (row.provider === "email")
81
+ add(found, addressOf(row.external_id), holder);
82
+ }
83
+ return found;
84
+ };
85
+ const personOf = ({ database }, identity) => {
86
+ const row = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
87
+ return row ? Number(row.person_id) : undefined;
88
+ };
89
+ /** The people the identities are on now, each once, with an identity of each that holds the value. */
90
+ const peopleOf = (context, holders) => {
91
+ const found = new Map();
92
+ for (const { identity } of holders) {
93
+ const person = personOf(context, identity);
94
+ if (person !== undefined && !found.has(person))
95
+ found.set(person, identity);
96
+ }
97
+ return found;
98
+ };
99
+ const resolveNames = (context, person) => resolvePersonLinks(context.database, context.database
100
+ .prepare("SELECT i.name, i.username FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE l.person_id = ?")
101
+ .all(person)
102
+ .flatMap((row) => [row.name, row.username]));
103
+ /**
104
+ * Joins two people unless the owner separated them, or rejected the pair (NEED-2444): then the pair is proposed when
105
+ * this evidence is new to the owner. Gives the person that stays.
106
+ */
107
+ const join = (pass, sides, signal) => {
108
+ const { context, index, result } = pass;
109
+ const { from, into } = sides;
110
+ const method = signal === "email" ? "same-email" : "same-phone";
111
+ if (separated(context, from, into)) {
112
+ result.skipped.push({ persons: [String(from), String(into)], signal: method, reason: "identity.separated" });
113
+ return into;
114
+ }
115
+ if (index.rejected(from, into) !== undefined) {
116
+ propose(pass, { identity: sides.identity, with: sides.with, from, to: into, joins: "person", signal });
117
+ return into;
118
+ }
119
+ const kept = mergePerson(context, from, into, { method, by: BY });
120
+ index.merged(kept === into ? from : into, kept);
121
+ resolveNames(context, kept);
122
+ result.merged.push({ into: String(kept), from: String(kept === into ? from : into), signal: method });
123
+ return kept;
124
+ };
125
+ const propose = ({ context, index, result }, opening) => {
126
+ const opened = openIdentityLink(context, { ...opening, by: RULE }, index);
127
+ const persons = [String(opening.from), String(opening.to)];
128
+ if (opened.outcome === "skipped") {
129
+ if (opened.reason !== "identity.same")
130
+ result.skipped.push({ persons, signal: opening.signal, reason: opened.reason });
131
+ return;
132
+ }
133
+ result.proposed.push({ id: opened.action.id, persons, signal: opening.signal, opened: opened.outcome === "proposed" });
134
+ };
135
+ const proposeEachPair = (pass, people, signal) => {
136
+ const persons = [...people.keys()].sort((a, b) => a - b);
137
+ for (const [at, from] of persons.entries())
138
+ for (const to of persons.slice(at + 1))
139
+ propose(pass, {
140
+ identity: people.get(from),
141
+ with: people.get(to),
142
+ from,
143
+ to,
144
+ joins: "person",
145
+ signal,
146
+ candidates: persons,
147
+ });
148
+ };
149
+ const tooMany = (pass, people, reason, signal) => {
150
+ if (people.size <= MOST_SHARING)
151
+ return false;
152
+ pass.result.skipped.push({ persons: [...people.keys()].map(String), signal, reason });
153
+ return true;
154
+ };
155
+ /** A number two people have joins them (NEED-2445); one that more share, or that once proposed, proposes. */
156
+ const samePhone = (pass, holders) => {
157
+ const people = peopleOf(pass.context, holders);
158
+ if (people.size < 2 || tooMany(pass, people, "identity.shared-phone", "phone"))
159
+ return;
160
+ const [into, from] = [...people.keys()].sort((a, b) => a - b);
161
+ if (people.size === 2 && phonePairJoins(holders) && !pass.index.known(from, into))
162
+ join(pass, { from, into, identity: people.get(from), with: people.get(into) }, "phone");
163
+ else
164
+ proposeEachPair(pass, people, "phone");
165
+ };
166
+ /**
167
+ * One address is one person in any scope (NEED-2382), unless more than two people have it or it is a role address
168
+ * (NEED-2446). A no-reply address is no one's.
169
+ */
170
+ const sameEmail = (pass, address, holders) => {
171
+ if (isNoReplyAddress(address))
172
+ return;
173
+ const people = peopleOf(pass.context, holders);
174
+ if (people.size < 2 || tooMany(pass, people, "identity.shared-email", "email"))
175
+ return;
176
+ if (!addressGroupJoins(address, people.size))
177
+ return proposeEachPair(pass, people, "email");
178
+ const contact = holders.find(({ provider }) => provider === "email");
179
+ const held = contact === undefined ? undefined : personOf(pass.context, contact.identity);
180
+ let into = held !== undefined && people.has(held) ? held : [...people.keys()].reduce((a, b) => Math.min(a, b));
181
+ // The mail contact stands for its person, as at import, so both paths name the same evidence to the owner.
182
+ const intoIdentity = contact !== undefined && held === into ? contact.identity : people.get(into);
183
+ for (const from of people.keys())
184
+ if (from !== into)
185
+ into = join(pass, { from, into, identity: people.get(from), with: intoIdentity }, "email");
186
+ };
187
+ /** What a meeting guest typed is their word only: it is proposed, and only when it names exactly one person. */
188
+ const guestEmail = (pass, row) => {
189
+ const { context } = pass;
190
+ const address = addressOf(row.email);
191
+ const from = personOf(context, row.identity);
192
+ if (address === undefined || from === undefined || isNoReplyAddress(address))
193
+ return;
194
+ const others = personsByIdentifiers(context.database, { emails: [address], phones: [] }).filter((one) => one !== from);
195
+ if (others.length !== 1)
196
+ return;
197
+ const meeting = referenceOfThing(context.database, { type: "meeting", id: row.meeting });
198
+ propose(pass, {
199
+ identity: row.identity,
200
+ with: null,
201
+ from,
202
+ to: others[0],
203
+ joins: "identity",
204
+ signal: "guest-email",
205
+ ...(meeting === undefined ? {} : { evidence: [meeting] }),
206
+ });
207
+ };
208
+ const guestRows = (database) => database
209
+ .prepare("SELECT mp.identity_id, i.provider, i.external_id, mp.email, min(mp.meeting_id) AS meeting " +
210
+ "FROM meeting_participants mp JOIN identity_links l ON l.identity_id = mp.identity_id " +
211
+ "JOIN identities i ON i.id = mp.identity_id WHERE mp.email IS NOT NULL " +
212
+ "GROUP BY mp.identity_id, lower(trim(mp.email)) ORDER BY mp.identity_id")
213
+ .all()
214
+ .map((row) => ({
215
+ identity: Number(row.identity_id),
216
+ ref: `${String(row.provider)}:${String(row.external_id)}`,
217
+ email: row.email,
218
+ meeting: Number(row.meeting),
219
+ }));
220
+ /**
221
+ * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
222
+ * each group it changes, so other writers are never kept waiting for the whole pass. After the first pass, only the
223
+ * values of identities changed since the last one are looked at, unless `full`. The owner's separations and
224
+ * rejections hold throughout.
225
+ */
226
+ export const scanMatches = (context, { full = false } = {}) => {
227
+ const { database } = context;
228
+ const started = cursorNow(database);
229
+ const since = full ? undefined : savedCursor(database);
230
+ const changed = since === undefined ? undefined : changedSince(database, since);
231
+ const touched = (holders) => changed === undefined || holders.some(({ identity }) => changed.has(identity));
232
+ write(database, () => settleLinks(database));
233
+ const pass = {
234
+ context,
235
+ index: linkIndex(database),
236
+ result: { full: changed === undefined, merged: [], proposed: [], skipped: [] },
237
+ };
238
+ for (const [address, holders] of emailHolders(database))
239
+ if (holders.length > 1 && touched(holders))
240
+ write(database, () => sameEmail(pass, address, holders));
241
+ for (const holders of phoneHolders(database).values())
242
+ if (holders.length > 1 && touched(holders))
243
+ write(database, () => samePhone(pass, holders));
244
+ for (const row of guestRows(database))
245
+ if ((changed === undefined || changed.has(row.identity)) && !pass.index.names(row.ref))
246
+ write(database, () => guestEmail(pass, row));
247
+ write(database, () => database
248
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
249
+ .run(CURSOR, JSON.stringify(started), context.now()));
250
+ return pass.result;
251
+ };
@@ -0,0 +1,16 @@
1
+ export { e164Of, storedPhone } from "../../domain/phones.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ /** What a person is matched by: lower-cased addresses, E.164 numbers and a source's own contact identity. */
4
+ export interface PersonIdentifiers {
5
+ emails: readonly string[];
6
+ phones: readonly string[];
7
+ contact?: {
8
+ provider: string;
9
+ externalId: string;
10
+ } | undefined;
11
+ }
12
+ /**
13
+ * The people the identifiers point at, each once, by id. The one lookup the records import and the people matcher
14
+ * share; it reads the store and nothing else.
15
+ */
16
+ export declare const personsByIdentifiers: (database: CacheDatabase, ids: PersonIdentifiers) => number[];
@@ -0,0 +1,32 @@
1
+ export { e164Of, storedPhone } from "../../domain/phones.js";
2
+ /** The spellings of an E.164 number `storedPhone` reads back as it. */
3
+ const spellingsOf = (value) => [value, value.slice(1)];
4
+ const PERSON_BY = {
5
+ // UNION, not OR: each branch reads its own index.
6
+ email: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
7
+ "WHERE i.provider = 'email' AND i.external_id = ? UNION " +
8
+ "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE i.email = ?",
9
+ phone: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
10
+ "WHERE i.provider = 'phone' AND i.external_id = ? UNION " +
11
+ "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE i.phone IN (?, ?)",
12
+ contact: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
13
+ "WHERE i.provider = ? AND i.external_id = ?",
14
+ };
15
+ /**
16
+ * The people the identifiers point at, each once, by id. The one lookup the records import and the people matcher
17
+ * share; it reads the store and nothing else.
18
+ */
19
+ export const personsByIdentifiers = (database, ids) => {
20
+ const found = new Set();
21
+ const add = (rows) => {
22
+ for (const row of rows)
23
+ found.add(Number(row.person_id));
24
+ };
25
+ for (const email of ids.emails)
26
+ add(database.prepare(PERSON_BY.email).all(email, email));
27
+ for (const value of ids.phones)
28
+ add(database.prepare(PERSON_BY.phone).all(value, ...spellingsOf(value)));
29
+ if (ids.contact)
30
+ add(database.prepare(PERSON_BY.contact).all(ids.contact.provider, ids.contact.externalId));
31
+ return [...found].sort((a, b) => a - b);
32
+ };
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { MEETING_FINDINGS_KIND } from "../../meetings/index.js";
3
3
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
4
4
  import { EVIDENCE_FINDINGS_KIND } from "../evidence-findings.js";
5
+ import { IDENTITY_LINK_KIND } from "../identity-links.js";
5
6
  import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
6
7
  import { SOURCE_REVIEW_KIND } from "../source-review.js";
7
8
  import { proposedBySql } from "./actors.js";
@@ -185,6 +186,11 @@ const DEDICATED_REVIEW = {
185
186
  reason: "source-review.dedicated-review",
186
187
  through: "the review of memories and facts, which signs their sources again",
187
188
  },
189
+ [IDENTITY_LINK_KIND]: {
190
+ what: "a proposed identity link",
191
+ reason: "identity-link.dedicated-review",
192
+ through: "the people review, which checks that neither person changed",
193
+ },
188
194
  };
189
195
  /** Refuses a dedicated kind on a generic action path: approving one as an action would skip its own checks. */
190
196
  export const assertGenericAction = (kind) => {
@@ -37,20 +37,14 @@ export type Match = {
37
37
  ids: number[];
38
38
  reason: "record.ambiguous" | "record.separated";
39
39
  };
40
- /**
41
- * A phone as E.164, `null` for a number written without `+` or `00` when the envelope names no `phone_region`, or
42
- * nothing when it is no phone. Only the envelope says which country a national number is from: the store's
43
- * `phone_countries` setting reads `4155550100` as Russian, so it never decides an identifier.
44
- */
45
- export declare const e164Of: (phone: string, region: string | undefined) => string | null | undefined;
46
40
  /**
47
41
  * A record's identifiers. What does not read as an e-mail, a phone or a `{scheme, value}` of a known scheme is no
48
42
  * identifier and stays in the fields, as v1 kept it; a free-mail domain claimed as an organization's is refused.
49
43
  */
50
44
  export declare const identifiersOf: (type: IdentityType, fields: Row, source: EnvelopeSource, externalId: string, options?: EnvelopeOptions) => Identifiers;
51
45
  /**
52
- * The entities the identifiers point at, each once. The one lookup an import matches by: the Memory workstream's
53
- * shared matcher (D5) takes it over as it is, so it reads the store and nothing else.
46
+ * The entities the identifiers point at, each once. A person is matched by the people matcher's lookup, which
47
+ * `people.scanMatches` reads phones and addresses with too.
54
48
  */
55
49
  export declare const entitiesByIdentifiers: (database: CacheDatabase, type: IdentityType, ids: Identifiers) => number[];
56
50
  /** Whether the owner separated `person` from an identity the record brings: linking would join what he told apart. */
@@ -1,11 +1,11 @@
1
- import { typedPhone } from "../../domain/mentions.js";
2
- import { nationalPhone } from "../../domain/phones.js";
1
+ import { isEmailAddress } from "../../domain/addresses.js";
3
2
  import { isObject } from "../../domain/record-fields.js";
4
3
  import { RECORD_TABLES } from "../../domain/record-types.js";
5
4
  import { FREE_MAIL } from "../../mail/score.js";
6
5
  import { fold } from "../normalize.js";
7
6
  import { crmIdentityId } from "./crm.js";
8
7
  import { insertProject } from "./knowledge.js";
8
+ import { e164Of, personsByIdentifiers } from "./person-matcher.js";
9
9
  import { identitySeparated } from "./person-separation.js";
10
10
  import { refusal } from "./record-projection.js";
11
11
  const valuesOf = (value) => (Array.isArray(value) ? value : [value]).filter((one) => typeof one === "string");
@@ -20,21 +20,6 @@ const domainOf = (value) => value
20
20
  .trim()
21
21
  .toLowerCase()
22
22
  .replace(/^www\./, "");
23
- /**
24
- * A phone as E.164, `null` for a number written without `+` or `00` when the envelope names no `phone_region`, or
25
- * nothing when it is no phone. Only the envelope says which country a national number is from: the store's
26
- * `phone_countries` setting reads `4155550100` as Russian, so it never decides an identifier.
27
- */
28
- export const e164Of = (phone, region) => {
29
- if (/^\s*(\+|00)/.test(phone))
30
- return typedPhone(phone)?.value;
31
- if (typedPhone(phone) === undefined)
32
- return undefined;
33
- if (region === undefined)
34
- return null;
35
- const digits = phone.replace(/\(0\)/, "").replace(/\D/g, "");
36
- return nationalPhone(digits, [region], { anyType: true })?.value;
37
- };
38
23
  /**
39
24
  * A record's identifiers. What does not read as an e-mail, a phone or a `{scheme, value}` of a known scheme is no
40
25
  * identifier and stays in the fields, as v1 kept it; a free-mail domain claimed as an organization's is refused.
@@ -45,7 +30,7 @@ export const identifiersOf = (type, fields, source, externalId, options = {}) =>
45
30
  found.contact = { provider: source.provider, externalId: crmIdentityId(source, externalId) };
46
31
  for (const email of valuesOf(fields.email)) {
47
32
  const address = email.trim().toLowerCase();
48
- if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(address) && !found.emails.includes(address))
33
+ if (isEmailAddress(address) && !found.emails.includes(address))
49
34
  found.emails.push(address);
50
35
  }
51
36
  const region = options.phone_region?.toLowerCase();
@@ -82,21 +67,9 @@ export const identifiersOf = (type, fields, source, externalId, options = {}) =>
82
67
  found.key = fields.key.trim().toUpperCase();
83
68
  return found;
84
69
  };
85
- const PERSON_BY = {
86
- // UNION, not OR: each branch reads its own index.
87
- email: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
88
- "WHERE i.provider = 'email' AND i.external_id = ? UNION " +
89
- "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE i.email = ?",
90
- // A messenger or CRM contact keeps its number raw in identities.phone, with or without the +.
91
- phone: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
92
- "WHERE i.provider = 'phone' AND i.external_id = ? UNION " +
93
- "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE i.phone IN (?, ?)",
94
- contact: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
95
- "WHERE i.provider = ? AND i.external_id = ?",
96
- };
97
70
  /**
98
- * The entities the identifiers point at, each once. The one lookup an import matches by: the Memory workstream's
99
- * shared matcher (D5) takes it over as it is, so it reads the store and nothing else.
71
+ * The entities the identifiers point at, each once. A person is matched by the people matcher's lookup, which
72
+ * `people.scanMatches` reads phones and addresses with too.
100
73
  */
101
74
  export const entitiesByIdentifiers = (database, type, ids) => {
102
75
  const found = new Set();
@@ -104,14 +77,9 @@ export const entitiesByIdentifiers = (database, type, ids) => {
104
77
  for (const row of rows)
105
78
  found.add(Number(row[column]));
106
79
  };
107
- if (type === "person") {
108
- for (const email of ids.emails)
109
- add(database.prepare(PERSON_BY.email).all(email, email), "person_id");
110
- for (const value of ids.phones)
111
- add(database.prepare(PERSON_BY.phone).all(value, value, value.slice(1)), "person_id");
112
- if (ids.contact)
113
- add(database.prepare(PERSON_BY.contact).all(ids.contact.provider, ids.contact.externalId), "person_id");
114
- }
80
+ if (type === "person")
81
+ for (const person of personsByIdentifiers(database, ids))
82
+ found.add(person);
115
83
  if (type === "organization") {
116
84
  const organization = database.prepare("SELECT o.id FROM identities i JOIN organization_identities oi ON oi.identity_id = i.id " +
117
85
  "JOIN organizations o ON o.id = oi.organization_id WHERE o.deleted_at IS NULL AND i.provider = ? " +
@@ -7,7 +7,8 @@ import { seenIdentity } from "./identities.js";
7
7
  import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js";
8
8
  import { tombstone, upsertMessage } from "./messages.js";
9
9
  import { requiredThing } from "./notes.js";
10
- import { e164Of, importedIdentity, linkToPerson } from "./record-matching.js";
10
+ import { e164Of } from "./person-matcher.js";
11
+ import { importedIdentity, linkToPerson } from "./record-matching.js";
11
12
  import { entityOf, given, importedBy, refusal, } from "./record-projection.js";
12
13
  const CALLS_CALENDAR = "calls";
13
14
  /**
@@ -0,0 +1,52 @@
1
+ import { type IngestError } from "../../domain/records.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ import { type ReportedOutcome, type ReportedSync } from "./reported-relations.js";
5
+ import { type Thing } from "./things.js";
6
+ export type RelationshipCounts = Omit<ReportedSync, "issues">;
7
+ /** An import's links are its own writer's: another writer on the same account, a CRM's `crm`, never withdraws them. */
8
+ export declare const importSource: (provider: string) => string;
9
+ export declare const noRelationships: () => RelationshipCounts;
10
+ /**
11
+ * Something a report says about one record's relationship: an `issue` (the store did not take it) or a `notice` (it
12
+ * took it, but not as the source put it: a word off the role list). `key` is the same for the same thing twice.
13
+ */
14
+ export interface RelationshipNote {
15
+ severity: "issue" | "notice";
16
+ code: string;
17
+ message: string;
18
+ record: number | null;
19
+ key: string;
20
+ }
21
+ /** Which entities a report covers: the entities of `records`, those of the records that point at `changed`, and these. */
22
+ export interface ReportedRecords {
23
+ records: number[];
24
+ /** Records whose entity came, went or moved: what points at them is reported again. */
25
+ changed?: number[];
26
+ /** Entities no record of the account may map to any more, a remap's old one: what it reported from them withdraws. */
27
+ entities?: Thing[];
28
+ }
29
+ export interface ReportHooks {
30
+ onNote?: (note: RelationshipNote) => void;
31
+ onOutcome?: (outcome: ReportedOutcome) => void;
32
+ }
33
+ /** Where a note points: the record's place in this run, or the record itself when it came in an earlier batch. */
34
+ export interface NotePlace {
35
+ index?: number;
36
+ key?: string;
37
+ type: string;
38
+ externalId: string;
39
+ }
40
+ /** One note as a receipt entry, for a run and for the owner's `map` and `match` alike. */
41
+ export declare const noteError: (note: RelationshipNote, place: NotePlace | undefined) => IngestError;
42
+ /**
43
+ * The relationships an import's records report, through `relations.syncReported` under the import's account. An
44
+ * entity's set is what every live record of the account mapped to it says, so a second record of the same person, or
45
+ * a delete, never withdraws what another record still reports. An entity the owner rejected, or that is deleted,
46
+ * reports none.
47
+ */
48
+ export declare const recordRelationshipsOver: (context: StoreContext) => {
49
+ report: (key: AccountKey, accountId: number, { records, changed, entities }: ReportedRecords, { onNote, onOutcome }?: ReportHooks) => RelationshipCounts;
50
+ placeOf: (record: number | null) => NotePlace | undefined;
51
+ withdrawFrom: (entity: Thing) => void;
52
+ };