@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
@@ -26,7 +26,8 @@ export interface StoredMention {
26
26
  /** What was written, read back from the message: never copied into the mention. */
27
27
  written: string;
28
28
  }
29
- export declare const MENTION_STATUSES: readonly ["found", "linked", "dismissed"];
29
+ /** `proposed`: an agent's link of the value to a person waits for the owner as an `identity_link` proposal. */
30
+ export declare const MENTION_STATUSES: readonly ["found", "linked", "proposed", "dismissed"];
30
31
  export type MentionStatus = (typeof MENTION_STATUSES)[number];
31
32
  /** The fields of `mentions list`; a bare word is a `value`. */
32
33
  export declare const MENTION_QUERY: import("@wirecat/cli-base/query").QueryRegistry;
@@ -91,6 +92,8 @@ export interface MentionDecision {
91
92
  target: string | null;
92
93
  /** Every stored mention of this value that now carries the decision. */
93
94
  mentions: number;
95
+ /** An agent's link of the identity to a person waits for the owner as this `identity_link` proposal. */
96
+ proposal?: string;
94
97
  }
95
98
  /** A mention found and allowed to its caller; `chat` is `null` for a text outside a chat. */
96
99
  export interface LocatedMention {
@@ -3,14 +3,16 @@ import { defineQuery } from "@wirecat/cli-base/query";
3
3
  import { MENTION_KINDS, siteOf } from "../../domain/mentions.js";
4
4
  import { findNames, nameIndex } from "../../domain/person-names.js";
5
5
  import { createStemmer } from "../../search/stem.js";
6
+ import { linkOrPropose } from "./identity-proposals.js";
6
7
  import { mentionText } from "./lucene-fields.js";
7
8
  import { knownPeople, participants, SOURCE_TYPES, SOURCES, sourceOf, telegramLink, writer, } from "./mention-drain.js";
8
- import { linkIdentityToPerson, personByUid } from "./person-links.js";
9
+ import { personByUid } from "./person-links.js";
9
10
  import { valueMatch } from "./phone-countries.js";
10
11
  import { placeOf } from "./place-key.js";
11
12
  import { queryFilter } from "./query-filter.js";
12
13
  import { writeBatch } from "./transaction.js";
13
- export const MENTION_STATUSES = ["found", "linked", "dismissed"];
14
+ /** `proposed`: an agent's link of the value to a person waits for the owner as an `identity_link` proposal. */
15
+ export const MENTION_STATUSES = ["found", "linked", "proposed", "dismissed"];
14
16
  /** The fields of `mentions list`; a bare word is a `value`. */
15
17
  export const MENTION_QUERY = defineQuery({
16
18
  entity: "mention",
@@ -237,13 +239,16 @@ export const confirmMention = (context, mention, owner, by) => {
237
239
  const identity = Number(database
238
240
  .prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?")
239
241
  .get(mention.kind, mention.value)?.id);
240
- if ("person" in owner)
241
- linkIdentityToPerson(context, identity, owner.person, { method: "mention", by: by.by });
242
- else
243
- database
244
- .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
245
- "VALUES (?, ?, 'mention', ?, ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING")
246
- .run(identity, owner.organization, by.by, now, now);
242
+ if ("person" in owner) {
243
+ const proposal = linkOrPropose(context, identity, owner.person, { method: "mention", by: by.by });
244
+ const status = proposal === undefined ? "linked" : "proposed";
245
+ const decided = decide(database, mention, status, { type: "identity", id: identity }, by, now);
246
+ return proposal === undefined ? decided : { ...decided, proposal };
247
+ }
248
+ database
249
+ .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
250
+ "VALUES (?, ?, 'mention', ?, ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING")
251
+ .run(identity, owner.organization, by.by, now, now);
247
252
  return decide(database, mention, "linked", { type: "identity", id: identity }, by, now);
248
253
  }
249
254
  if (mention.kind === "document") {
@@ -1216,5 +1216,13 @@ export const GENERATED = [
1216
1216
  "CREATE TABLE `templates_history` (\n\t`id` integer PRIMARY KEY,\n\t`key` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`language` text NOT NULL,\n\t`body` text NOT NULL,\n\t`saved_at` integer NOT NULL,\n\t`saved_by` text NOT NULL,\n\t`replaced_at` integer NOT NULL\n);",
1217
1217
  "CREATE INDEX `templates_history_by_key_channel_language_id` ON `templates_history` (`key`,`channel`,`language`,`id`);"
1218
1218
  ]
1219
+ },
1220
+ {
1221
+ "name": "20261108190101_version-60-base-stages",
1222
+ "statements": [
1223
+ "ALTER TABLE `pipeline_stages` ADD `base_stage_id` integer REFERENCES pipeline_stages(id);",
1224
+ "ALTER TABLE `pipeline_stages` ADD `base_confirmed` integer DEFAULT 0 NOT NULL;",
1225
+ "CREATE INDEX `pipeline_stages_by_base_stage_id` ON `pipeline_stages` (`base_stage_id`);"
1226
+ ]
1219
1227
  }
1220
1228
  ];
@@ -273,15 +273,17 @@ export const drainCorpus = (database, corpus, stemmerFor, { batch = 200, until =
273
273
  if (isQueryOnly(database))
274
274
  return 0;
275
275
  // Pieces written before they carried their account get it, once: purge and vector search filter by it.
276
- if (corpus.type === "email" || corpus.type === "document")
277
- database
276
+ if ((corpus.type === "email" || corpus.type === "document") &&
277
+ database.prepare("SELECT 1 FROM chunks WHERE chunkable_type = ? AND account_id IS NULL LIMIT 1").get(corpus.type))
278
+ write(database, () => database
278
279
  .prepare(`UPDATE chunks SET account_id = (SELECT account_id FROM ${corpus.table} WHERE id = chunks.chunkable_id)
279
- WHERE chunkable_type = ? AND account_id IS NULL`)
280
- .run(corpus.type);
280
+ WHERE chunkable_type = ? AND account_id IS NULL`)
281
+ .run(corpus.type));
281
282
  // The first schema seeded no row for mail; a data row, so no migration.
282
- database
283
- .prepare("INSERT OR IGNORE INTO search_index_state (name, watermark, filled_through, terms_through, normalizer_version) VALUES (?, 0, 0, 0, 1)")
284
- .run(corpus.index);
283
+ if (!database.prepare("SELECT 1 FROM search_index_state WHERE name = ?").get(corpus.index))
284
+ write(database, () => database
285
+ .prepare("INSERT OR IGNORE INTO search_index_state (name, watermark, filled_through, terms_through, normalizer_version) VALUES (?, 0, 0, 0, 1)")
286
+ .run(corpus.index));
285
287
  const state = corpusIndexState(database, corpus);
286
288
  if (state.wanted === null)
287
289
  return 0;
@@ -6,6 +6,7 @@ import type { AddedSources } from "./added-sources.js";
6
6
  import { type DocumentMetadata } from "./document-metadata.js";
7
7
  import { type ImportedDocuments } from "./imported-documents.js";
8
8
  import { LINK_KINDS, LINK_ORIGINS, type LINK_SOURCES } from "./link-kinds.js";
9
+ export { linkOf, thingRef } from "./link-row.js";
9
10
  import type { NoteSearch } from "./note-search.js";
10
11
  import type { StoreContext } from "./open.js";
11
12
  import { type Label } from "./tags.js";
@@ -80,7 +81,7 @@ export interface LinkListFilter {
80
81
  origin?: Link["origin"];
81
82
  confirmed?: boolean;
82
83
  }
83
- export interface LinkInput extends Pick<RelationshipColumns, "position" | "startsAt" | "endsAt"> {
84
+ export interface LinkInput extends Omit<RelationshipColumns, "accountId" | "deletedAt" | "overrides"> {
84
85
  from: string;
85
86
  to?: string;
86
87
  targetText?: string;
@@ -204,8 +205,6 @@ export declare const documentOf: (row: Row) => Note;
204
205
  export declare const noteOf: (row: Row) => Note;
205
206
  /** A document or note row by its typed reference, or `undefined`. */
206
207
  export declare const noteRowOf: (database: CacheDatabase, reference: string) => Note | undefined;
207
- export declare const thingRef: (database: CacheDatabase, type: unknown, id: unknown) => string | null;
208
- export declare const linkOf: (database: CacheDatabase, row: Row) => Link;
209
208
  /** The row a reference names, refused when the store holds none. */
210
209
  export declare const requiredThing: (database: CacheDatabase, reference: string, what?: string) => Thing;
211
210
  /**
@@ -15,12 +15,14 @@ import { PREFERRED_FILE, syncFile } from "./files.js";
15
15
  import { importedDocumentWhere } from "./imported-documents.js";
16
16
  import { LINK_KINDS, LINK_ORIGINS, linkKind } from "./link-kinds.js";
17
17
  import { reviewLink } from "./link-reviews.js";
18
+ import { linkOf } from "./link-row.js";
19
+ export { linkOf, thingRef } from "./link-row.js";
18
20
  import { currentPerson, idsOf } from "./merged-persons.js";
19
21
  import { dateFileNotes } from "./note-dates.js";
20
22
  import { holdingText } from "./note-index.js";
21
23
  import { addTags, ensureTag, labelsOf } from "./tags.js";
22
24
  import { oneOf, textOf } from "./text-input.js";
23
- import { referenceOfThing, storedThing, thingOf } from "./things.js";
25
+ import { thingOf } from "./things.js";
24
26
  import { write } from "./transaction.js";
25
27
  export const NOTE_FORMATS = ["obsidian", "markdown"];
26
28
  export { LINK_ORIGINS } from "./link-kinds.js";
@@ -71,33 +73,6 @@ export const noteRowOf = (database, reference) => {
71
73
  return noteOf(database.prepare("SELECT * FROM notes WHERE id = ?").get(thing.id));
72
74
  return undefined;
73
75
  };
74
- export const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
75
- export const linkOf = (database, row) => {
76
- const metadata = row.metadata == null
77
- ? {}
78
- : JSON.parse(String(row.metadata));
79
- return {
80
- id: String(row.id),
81
- from: thingRef(database, row.from_type, row.from_id),
82
- to: thingRef(database, row.to_type, row.to_id),
83
- kind: row.kind,
84
- anchor: row.anchor == null ? null : String(row.anchor),
85
- origin: row.source,
86
- targetText: row.target_text == null ? null : String(row.target_text),
87
- role: row.role == null ? null : String(row.role),
88
- purpose: row.purpose == null ? null : String(row.purpose),
89
- evidence: row.evidence == null ? null : String(row.evidence),
90
- provenance: metadata.provenance ?? null,
91
- confirmed: Number(row.confirmed) === 1,
92
- createdAt: iso(row.created_at),
93
- ...(row.account_id == null ? {} : { accountId: Number(row.account_id) }),
94
- ...(row.starts_at == null ? {} : { startsAt: Number(row.starts_at) }),
95
- ...(row.ends_at == null ? {} : { endsAt: Number(row.ends_at) }),
96
- ...(row.deleted_at == null ? {} : { deletedAt: Number(row.deleted_at) }),
97
- ...(typeof metadata.position === "string" ? { position: metadata.position } : {}),
98
- ...(typeof metadata.overrides === "number" ? { overrides: metadata.overrides } : {}),
99
- };
100
- };
101
76
  /** The row a reference names, refused when the store holds none. */
102
77
  export const requiredThing = (database, reference, what = "the target") => {
103
78
  const thing = thingOf(database, reference);
@@ -199,7 +174,9 @@ export const insertLink = (context, input) => {
199
174
  const position = input.position === undefined ? undefined : textOf(input.position, "a position", 200);
200
175
  if (input.startsAt !== undefined && input.endsAt !== undefined && input.endsAt <= input.startsAt)
201
176
  throw new CliError("validation_error", "a relationship ends after it starts");
202
- const metadata = provenance === undefined && position === undefined ? null : JSON.stringify({ provenance, position });
177
+ const roleNote = input.roleNote === undefined ? undefined : textOf(input.roleNote, "a role note", 200);
178
+ const fields = { provenance, position, roleNote, engagement: input.engagement };
179
+ const metadata = Object.values(fields).every((value) => value === undefined) ? null : JSON.stringify(fields);
203
180
  const row = database
204
181
  .prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, anchor, source, target_text, target_folded, role, evidence, " +
205
182
  "metadata, confirmed, created_at, author, updated_at, purpose, starts_at, ends_at) " +
@@ -2,6 +2,7 @@ import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync }
2
2
  import { dirname } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  import { DEFAULT_DECISION_POLICY } from "../decisions.js";
5
+ import { noteShmWithoutWal, watchJournal } from "../journal.js";
5
6
  import { refuseDamagedStore } from "../marks.js";
6
7
  import { migrate } from "../migrations.js";
7
8
  import { storeCapable } from "../open.js";
@@ -83,11 +84,13 @@ export const openStoreContext = async (options = {}) => {
83
84
  else {
84
85
  createWritable(file);
85
86
  refuseDamagedStore(file, command);
87
+ noteShmWithoutWal(file, command ?? "unknown");
86
88
  }
87
89
  const opened = readOnly ? await openReadable(file, options) : await openSqlite(file, { readOnly });
88
90
  const database = opened.database;
89
91
  try {
90
92
  if (!readOnly) {
93
+ watchJournal(database, file, command ?? "unknown");
91
94
  const notice = migrate(database, {
92
95
  now,
93
96
  command,
@@ -1,6 +1,7 @@
1
1
  import { PRAGMAS } from "../driver.js";
2
2
  import { refuseOwnerStoreInTests } from "../path.js";
3
3
  import { quietSqliteWarning } from "../sqlite-warning.js";
4
+ import { countWrites, shareCounts } from "../write-events.js";
4
5
  /**
5
6
  * One SQLite connection, seen two ways: the `CacheDatabase` seam the hand-written SQL and the
6
7
  * migration runner use, and Drizzle. Each Drizzle driver imports its runtime at the top of its
@@ -25,7 +26,11 @@ const openUnderNode = async (path, readOnly) => {
25
26
  const { cacheOverNodeSqlite, nodeClient } = await import("../drivers/node-sqlite.js");
26
27
  const client = await nodeClient(path, { readOnly });
27
28
  try {
28
- return { database: cacheOverNodeSqlite(client), orm: drizzle({ client }) };
29
+ if (!readOnly)
30
+ countWrites(client, ["prepare"], () => client.isTransaction);
31
+ const database = cacheOverNodeSqlite(client);
32
+ shareCounts(client, database);
33
+ return { database, orm: drizzle({ client }) };
29
34
  }
30
35
  catch (error) {
31
36
  client.close();
@@ -37,7 +42,11 @@ const openUnderBun = async (path, readOnly) => {
37
42
  const { drizzle } = (await import("./drizzle/bun.js"));
38
43
  const client = await bunClient(path, readOnly ? { readonly: true, create: false } : undefined);
39
44
  try {
40
- return { database: cacheOverBunSqlite(client), orm: drizzle({ client }) };
45
+ if (!readOnly)
46
+ countWrites(client, ["prepare", "query"], () => client.inTransaction);
47
+ const database = cacheOverBunSqlite(client);
48
+ shareCounts(client, database);
49
+ return { database, orm: drizzle({ client }) };
41
50
  }
42
51
  catch (error) {
43
52
  client.close();
@@ -69,6 +69,8 @@ export interface OrderFilter {
69
69
  status?: OrderStatus;
70
70
  purpose?: OrderPurpose;
71
71
  customer?: string;
72
+ /** `person:` or `organization:` the order is from. */
73
+ supplier?: string;
72
74
  /** The shop's name in any letter case; with `number`, how a later mail finds its order. */
73
75
  supplierName?: string;
74
76
  number?: string;
@@ -18,12 +18,16 @@ export const orderOperationsOver = (context) => {
18
18
  const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
19
19
  const moneyLines = moneyLinesOver(context);
20
20
  const orderOf = (row) => {
21
+ const customer = partyOf(row.customer_type, row.customer_id);
22
+ const direction = row.direction;
21
23
  const currency = row.currency == null ? null : String(row.currency);
22
24
  const total = row.total == null || currency === null ? null : Number(row.total);
23
25
  const fields = {
24
26
  id: Number(row.id),
25
27
  number: row.number == null ? null : String(row.number),
26
28
  supplierName: String(row.supplier_name),
29
+ direction,
30
+ customerName: customer?.name ?? null,
27
31
  total,
28
32
  currency,
29
33
  status: row.status,
@@ -33,7 +37,7 @@ export const orderOperationsOver = (context) => {
33
37
  id: String(row.id),
34
38
  ref: `order:${row.id}`,
35
39
  title: orderTitle(fields),
36
- customer: partyOf(row.customer_type, row.customer_id),
40
+ customer,
37
41
  purpose: row.purpose,
38
42
  supplier: partyOf(row.supplier_type, row.supplier_id),
39
43
  supplierName: fields.supplierName,
@@ -46,7 +50,7 @@ export const orderOperationsOver = (context) => {
46
50
  invoice: row.invoice_id == null ? null : `invoice:${row.invoice_id}`,
47
51
  payment: row.payment_id == null ? null : `payment:${row.payment_id}`,
48
52
  sourceUrl: row.source_url == null ? null : String(row.source_url),
49
- direction: row.direction,
53
+ direction,
50
54
  contract: row.contract_id == null ? null : `contract:${row.contract_id}`,
51
55
  deal: row.deal_id == null ? null : `deal:${row.deal_id}`,
52
56
  ...reviewedOf(row, "order"),
@@ -159,6 +163,7 @@ export const orderOperationsOver = (context) => {
159
163
  list: (filter = {}) => {
160
164
  const project = filter.project === undefined ? null : projectId(database, filter.project);
161
165
  const customer = partyThing(filter.customer, "the customer");
166
+ const supplier = partyThing(filter.supplier, "the supplier");
162
167
  const by = proposedBySql("o.author_type", "o.author_id", filter.proposedBy);
163
168
  const status = filter.status === undefined ? null : statusOf(filter.status);
164
169
  const purpose = filter.purpose === undefined ? null : oneOf(filter.purpose, ORDER_PURPOSES, "a purpose");
@@ -170,8 +175,9 @@ export const orderOperationsOver = (context) => {
170
175
  .prepare(`${ORDERS} WHERE o.deleted_at IS NULL AND (? IS NULL OR o.status = ?) AND (? IS NULL OR o.purpose = ?) ` +
171
176
  "AND (? IS NULL OR o.review = ?) AND (? IS NULL OR o.project_id = ?) AND (? IS NULL OR o.number = ?) " +
172
177
  "AND (? IS NULL OR (o.customer_type = ? AND o.customer_id = ?)) " +
178
+ "AND (? IS NULL OR (o.supplier_type = ? AND o.supplier_id = ?)) " +
173
179
  `AND ${by.sql} ORDER BY o.created_at DESC, o.id DESC`)
174
- .all(status, status, purpose, purpose, review, review, project, project, number, number, customer?.type ?? null, customer?.type ?? null, customer?.id ?? null, ...by.params);
180
+ .all(status, status, purpose, purpose, review, review, project, project, number, number, customer?.type ?? null, customer?.type ?? null, customer?.id ?? null, supplier?.type ?? null, supplier?.type ?? null, supplier?.id ?? null, ...by.params);
175
181
  return rows
176
182
  .filter((row) => shop === null || fold(String(row.supplier_name)) === shop)
177
183
  .slice(0, limit)
@@ -0,0 +1,18 @@
1
+ import { type Category } from "../../domain/categories.js";
2
+ import type { AccountKey } from "../types.js";
3
+ /** Which organizations `organizations` answers: those of one category, read from relationships in `accounts` only. */
4
+ export interface OrganizationFilter {
5
+ category?: Category;
6
+ /** Relationships a source account reported count only from these; the owner's always count. Every one when absent. */
7
+ accounts?: AccountKey[];
8
+ }
9
+ /**
10
+ * The category as SQL over `organizations o`, derived from usable relationships at `now` (NEED-2377), as
11
+ * `organizationCategories` derives it: `client` is `customer-of` an own organization, `supplier` one an own
12
+ * organization is `customer-of`, `partner` `partner-of` one, `employer` one the owner's person is `member-of` as
13
+ * employee, contractor or founder.
14
+ */
15
+ export declare const categorySql: ({ category, accounts }: OrganizationFilter, now: number) => {
16
+ sql: string;
17
+ params: string[];
18
+ } | undefined;
@@ -0,0 +1,34 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { CATEGORIES } from "../../domain/categories.js";
3
+ import { usableLinkSql } from "../../domain/relations.js";
4
+ import { linkKind } from "./link-kinds.js";
5
+ const OWN = "(SELECT id FROM organizations WHERE deleted_at IS NULL AND json_extract(metadata, '$.own') = 1)";
6
+ const EMPLOYED = "('employee', 'contractor', 'founder')";
7
+ /**
8
+ * The category as SQL over `organizations o`, derived from usable relationships at `now` (NEED-2377), as
9
+ * `organizationCategories` derives it: `client` is `customer-of` an own organization, `supplier` one an own
10
+ * organization is `customer-of`, `partner` `partner-of` one, `employer` one the owner's person is `member-of` as
11
+ * employee, contractor or founder.
12
+ */
13
+ export const categorySql = ({ category, accounts }, now) => {
14
+ if (category === undefined)
15
+ return undefined;
16
+ if (!CATEGORIES.includes(category))
17
+ throw new CliError("validation_error", `a category is one of ${CATEGORIES.join(", ")}`);
18
+ const keys = accounts?.map(({ provider, account }) => `${provider}:${account}`) ?? [];
19
+ const reporter = accounts === undefined
20
+ ? ""
21
+ : ` AND (l.account_id IS NULL OR l.account_id IN (SELECT id FROM accounts WHERE provider || ':' || external_id ` +
22
+ `IN (${keys.map(() => "?").join(", ") || "NULL"})))`;
23
+ const usable = `${usableLinkSql("l", now)}${reporter}`;
24
+ const org = (end) => `l.${end}_type = 'organization'`;
25
+ const where = {
26
+ client: `l.kind = ${linkKind("customer-of")} AND ${org("from")} AND l.from_id = o.id AND ${org("to")} AND l.to_id IN ${OWN}`,
27
+ supplier: `l.kind = ${linkKind("customer-of")} AND ${org("from")} AND l.from_id IN ${OWN} AND ${org("to")} AND l.to_id = o.id`,
28
+ partner: `l.kind = ${linkKind("partner-of")} AND ${org("from")} AND ${org("to")} AND ` +
29
+ `((l.from_id = o.id AND l.to_id IN ${OWN}) OR (l.to_id = o.id AND l.from_id IN ${OWN}))`,
30
+ employer: `l.kind = ${linkKind("member-of")} AND l.from_type = 'person' AND l.from_id IN (SELECT id FROM persons WHERE ` +
31
+ `owner = 1) AND ${org("to")} AND l.to_id = o.id AND l.role IN ${EMPLOYED}`,
32
+ }[category];
33
+ return { sql: `EXISTS (SELECT 1 FROM links l WHERE ${where} AND ${usable})`, params: keys };
34
+ };
@@ -1,10 +1,12 @@
1
1
  import { type QueryAst } from "@wirecat/cli-base/query";
2
2
  import type { Organization } from "./knowledge.js";
3
3
  import type { StoreContext } from "./open.js";
4
+ import { type OrganizationFilter } from "./organization-categories.js";
4
5
  type Row = Record<string, unknown>;
5
6
  export declare const organizationOf: (row: Row) => Organization;
6
7
  export interface OrganizationsStore {
7
- organizations(query?: QueryAst): Promise<Organization[]>;
8
+ /** At most 500, by name; with `filter.category`, only that category's, chosen in SQL. */
9
+ organizations(query?: QueryAst, filter?: OrganizationFilter): Promise<Organization[]>;
8
10
  /** Renames an organization given as `organization:<id>` or by its id; its kind and scope stay. */
9
11
  updateOrganization(organization: string, input: {
10
12
  name: string;
@@ -17,6 +19,8 @@ export interface OrganizationsStore {
17
19
  ref: string;
18
20
  own: boolean;
19
21
  }>;
22
+ /** The owner's own companies: the owner's mark, else a CRM's own-company flag (`metadata.own`). */
23
+ ownOrganizations(): Promise<Organization[]>;
20
24
  }
21
25
  export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
22
26
  export {};
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { evaluate, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { ORGANIZATIONS_QUERY } from "../knowledge-query.js";
4
+ import { categorySql } from "./organization-categories.js";
4
5
  import { queryFilter } from "./query-filter.js";
5
6
  import { thingOf } from "./things.js";
6
7
  import { write } from "./transaction.js";
@@ -13,10 +14,14 @@ export const organizationOf = (row) => ({
13
14
  createdAt: new Date(Number(row.created_at)).toISOString(),
14
15
  });
15
16
  export const organizationsStoreOver = ({ database, now }) => ({
16
- organizations: async (query) => {
17
+ organizations: async (query, filter = {}) => {
18
+ const category = categorySql(filter, now());
19
+ const inCategory = category ? ` AND ${category.sql}` : "";
17
20
  // `lower()` folds ASCII only and an organization has no folded copy, so a name filter runs on the rows.
18
21
  if (query && walkQuery(query.root).some((node) => node.field === "name"))
19
- return database.prepare("SELECT * FROM organizations WHERE deleted_at IS NULL ORDER BY name, id").all()
22
+ return database
23
+ .prepare(`SELECT * FROM organizations o WHERE deleted_at IS NULL${inCategory} ORDER BY name, id`)
24
+ .all(...(category?.params ?? []))
20
25
  .map(organizationOf)
21
26
  .filter((one) => evaluate(query, ORGANIZATIONS_QUERY.fields, { ...one, created_at: one.createdAt }))
22
27
  .slice(0, 500);
@@ -28,10 +33,15 @@ export const organizationsStoreOver = ({ database, now }) => ({
28
33
  created_at: { type: "time", sql: "created_at" },
29
34
  });
30
35
  return database
31
- .prepare(`SELECT * FROM organizations WHERE deleted_at IS NULL${where ? ` AND (${where.sql})` : ""} ORDER BY name, id LIMIT 500`)
32
- .all(...(where?.params ?? []))
36
+ .prepare(`SELECT * FROM organizations o WHERE deleted_at IS NULL${where ? ` AND (${where.sql})` : ""}${inCategory} ` +
37
+ "ORDER BY name, id LIMIT 500")
38
+ .all(...(where?.params ?? []), ...(category?.params ?? []))
33
39
  .map(organizationOf);
34
40
  },
41
+ ownOrganizations: async () => database
42
+ .prepare("SELECT * FROM organizations WHERE deleted_at IS NULL AND json_extract(metadata, '$.own') = 1 ORDER BY name, id")
43
+ .all()
44
+ .map(organizationOf),
35
45
  updateOrganization: async (organization, { name }) => write(database, () => {
36
46
  const title = name.trim();
37
47
  if (!title || title.length > 200)
@@ -24,14 +24,29 @@ export declare const linkIdentityToPerson: (context: StoreContext, identityPk: n
24
24
  * name: a caller links only what someone decided belongs together, and says how in `method`.
25
25
  */
26
26
  export declare const linkIdentities: (context: StoreContext, person: IdentityRef, other: IdentityRef, options: LinkOptions) => PersonRecord;
27
- /** Moves every identity of `from` to `to`, as `linkIdentities` does once it has found both people. */
28
- export declare const mergePerson: (context: StoreContext, from: number, to: number, options: LinkOptions) => void;
27
+ /** The person `mergePerson(one, other)` keeps: `other`, unless `one` is the owner's. */
28
+ export declare const survivorOf: (context: StoreContext, one: number, other: number) => number;
29
+ /**
30
+ * Moves every identity of `from` to `to`, as `linkIdentities` does once it has found both people, and gives the
31
+ * person that stays. The owner's person always stays: merging it away would leave the owner with no identity.
32
+ * Proposals naming either person are brought up to date.
33
+ */
34
+ export declare const mergePerson: (context: StoreContext, one: number, other: number, options: LinkOptions) => number;
35
+ /** Keeps the address an identity's source gave it, so a later contact with it counts this one. */
36
+ export declare const noteAddress: (context: StoreContext, ref: IdentityRef, address: string) => void;
29
37
  /**
30
38
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
31
39
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
32
- * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
40
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart. A role address such
41
+ * as `info@` joins no one; the scan proposes its people instead. A pair the owner rejected is not joined either: it is
42
+ * given back, so the caller proposes it when the evidence is new to the owner.
33
43
  */
34
- export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => void;
44
+ export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => {
45
+ identity: number;
46
+ with: number;
47
+ from: number;
48
+ to: number;
49
+ } | undefined;
35
50
  /** Gives the identity a person of its own again; the ones left keep theirs. */
36
51
  export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options: LinkOptions) => PersonRecord;
37
52
  /** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */
@@ -1,6 +1,8 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { isEmailAddress, isRoleAddress } from "../../domain/addresses.js";
2
3
  import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
3
4
  import { identityOf } from "./identities.js";
5
+ import { rejectedEvidence, settleLinks } from "./identity-link-rows.js";
4
6
  import { currentPerson } from "./merged-persons.js";
5
7
  import { resolvePersonLinks } from "./person-resolution.js";
6
8
  import { identitySeparated, separated } from "./person-separation.js";
@@ -140,16 +142,24 @@ export const linkIdentityToPerson = (context, identityPk, target, options) => {
140
142
  export const linkIdentities = (context, person, other, options) => {
141
143
  const target = required(context, person);
142
144
  const moving = required(context, other);
143
- mergePerson(context, moving.personPk, target.personPk, options);
144
- const record = recordOf(context, target.personPk);
145
+ const record = recordOf(context, mergePerson(context, moving.personPk, target.personPk, options));
145
146
  // Two identities that were two people named alike are one now, so a name that was ambiguous may not be.
146
147
  resolvePersonLinks(context.database, record.identities.flatMap(({ name, username }) => [name, username]));
147
148
  return record;
148
149
  };
149
- /** Moves every identity of `from` to `to`, as `linkIdentities` does once it has found both people. */
150
- export const mergePerson = (context, from, to, options) => {
151
- if (from === to)
152
- return;
150
+ const isOwner = ({ database }, person) => Number(database.prepare("SELECT owner FROM persons WHERE id = ?").get(person)?.owner) === 1;
151
+ /** The person `mergePerson(one, other)` keeps: `other`, unless `one` is the owner's. */
152
+ export const survivorOf = (context, one, other) => isOwner(context, one) && !isOwner(context, other) ? one : other;
153
+ /**
154
+ * Moves every identity of `from` to `to`, as `linkIdentities` does once it has found both people, and gives the
155
+ * person that stays. The owner's person always stays: merging it away would leave the owner with no identity.
156
+ * Proposals naming either person are brought up to date.
157
+ */
158
+ export const mergePerson = (context, one, other, options) => {
159
+ if (one === other)
160
+ return other;
161
+ const to = survivorOf(context, one, other);
162
+ const from = to === other ? one : other;
153
163
  const together = context.orm
154
164
  .select({ identityPk: identityLinks.identityId })
155
165
  .from(identityLinks)
@@ -157,18 +167,41 @@ export const mergePerson = (context, from, to, options) => {
157
167
  .all();
158
168
  for (const { identityPk } of together)
159
169
  move(context, identityPk, from, to, options);
170
+ settleLinks(context.database, [from, to]);
171
+ return to;
172
+ };
173
+ /**
174
+ * NEED-2446 (safe option until the owner rules): an address that two or more other people hold is a shared one, an
175
+ * `office@` or `info@`, and joins no one at import; the scan proposes such people instead.
176
+ */
177
+ const sharedAddress = ({ database }, key, person) => database
178
+ .prepare("SELECT count(DISTINCT l.person_id) AS n FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
179
+ "WHERE i.email = ? AND i.provider NOT IN ('email', 'org-email') AND l.person_id <> ?")
180
+ .get(key, person)?.n >= 2;
181
+ /** Keeps the address an identity's source gave it, so a later contact with it counts this one. */
182
+ export const noteAddress = (context, ref, address) => {
183
+ const key = address.trim().toLowerCase();
184
+ if (!isEmailAddress(key) || ref.provider === "email")
185
+ return;
186
+ context.database
187
+ .prepare("UPDATE identities SET email = ? WHERE id = ? AND email IS NOT ?")
188
+ .run(key, required(context, ref).pk, key);
160
189
  };
161
190
  /**
162
191
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
163
192
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
164
- * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
193
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart. A role address such
194
+ * as `info@` joins no one; the scan proposes its people instead. A pair the owner rejected is not joined either: it is
195
+ * given back, so the caller proposes it when the evidence is new to the owner.
165
196
  */
166
197
  export const joinByAddress = (context, ref, address, by) => {
167
198
  const key = address.trim().toLowerCase();
168
- if (!/^[^\s@]+@[^\s@]+$/.test(key) || ref.provider === "email")
199
+ if (!isEmailAddress(key) || ref.provider === "email")
169
200
  return;
170
201
  const found = required(context, ref);
171
- context.database.prepare("UPDATE identities SET email = ? WHERE id = ? AND email IS NOT ?").run(key, found.pk, key);
202
+ noteAddress(context, ref, key);
203
+ if (isRoleAddress(key))
204
+ return;
172
205
  // The mail contact of the address, found by the address column every contact with one carries (store version 32).
173
206
  const mail = context.database
174
207
  .prepare("SELECT external_id FROM identities WHERE provider = 'email' AND email = ? LIMIT 1")
@@ -178,8 +211,13 @@ export const joinByAddress = (context, ref, address, by) => {
178
211
  const contact = required(context, { provider: "email", id: mail ? String(mail.external_id) : key });
179
212
  if (contact.personPk === found.personPk || separated(context, found.personPk, contact.personPk))
180
213
  return;
181
- mergePerson(context, found.personPk, contact.personPk, { method: "same-email", by });
182
- resolvePersonLinks(context.database, recordOf(context, contact.personPk).identities.flatMap(({ name, username }) => [name, username]));
214
+ if (sharedAddress(context, key, found.personPk))
215
+ return;
216
+ if (rejectedEvidence(context.database, found.personPk, contact.personPk) !== undefined)
217
+ return { identity: found.pk, with: contact.pk, from: found.personPk, to: contact.personPk };
218
+ const kept = mergePerson(context, found.personPk, contact.personPk, { method: "same-email", by });
219
+ resolvePersonLinks(context.database, recordOf(context, kept).identities.flatMap(({ name, username }) => [name, username]));
220
+ return undefined;
183
221
  };
184
222
  /** Gives the identity a person of its own again; the ones left keep theirs. */
185
223
  export const unlinkIdentity = (context, ref, options) => {
@@ -0,0 +1,13 @@
1
+ import type { MatchScan } from "../identity-links.js";
2
+ import type { Author } from "./memories.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export declare const RULE: Author;
5
+ /**
6
+ * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
7
+ * each group it changes, so other writers are never kept waiting for the whole pass. After the first pass, only the
8
+ * values of identities changed since the last one are looked at, unless `full`. The owner's separations and
9
+ * rejections hold throughout.
10
+ */
11
+ export declare const scanMatches: (context: StoreContext, { full }?: {
12
+ full?: boolean;
13
+ }) => MatchScan;