@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
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatLocator, parseLocator } from "../domain/locator.js";
3
3
  import { validateFindings } from "../meetings/index.js";
4
+ import { QUOTE_LIMIT } from "./sqlite/evidence-signature.js";
4
5
  import { entryAmount } from "./sqlite/payment-entries.js";
5
6
  export const EVIDENCE_FINDINGS_KIND = "evidence_findings";
6
7
  const reference = (raw) => {
@@ -21,6 +22,7 @@ export const validateEvidenceFindings = (input) => {
21
22
  reference,
22
23
  anySubject: true,
23
24
  payments: true,
25
+ quotes: QUOTE_LIMIT,
24
26
  });
25
27
  // Refused at staging rather than when the owner accepts, which would fail the whole batch.
26
28
  for (const finding of valid.findings)
@@ -1,7 +1,7 @@
1
1
  export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
2
2
  export type { CounterField, CounterObservations, CounterState } from "../domain/counters.js";
3
3
  export type { RetentionOptions } from "../domain/retention.js";
4
- export type { AccountAccounts, AccountsStore } from "./accounts.js";
4
+ export type { AccountAccounts, AccountGroupChange, AccountsStore } from "./accounts.js";
5
5
  export type { AccountAttachments, AttachmentsStore } from "./attachments.js";
6
6
  export type { ChatsStore, LeftChat, LeftChats } from "./chats.js";
7
7
  export type { ConversationsStore } from "./conversations.js";
@@ -18,6 +18,7 @@ export { accountGroupsOf } from "./sqlite/account-groups.js";
18
18
  export type { AdminStoreRequest, AdminStoreResult } from "./sqlite/admin-statistics.js";
19
19
  export { type AttachmentTextEntry, type AttachmentView, attachmentColumns, type FileAttachment, resetAttachmentWords, type TextOrigin, } from "./sqlite/attachment-texts.js";
20
20
  export { pendingNormalization } from "./sqlite/backfill.js";
21
+ export type { BaseScope, BaseSet, BaseStagesStore, StageMapping } from "./sqlite/base-stages.js";
21
22
  export { BUSINESS_FIND_MAX, type BusinessHit, type BusinessSearch, type BusinessSearchStore, type BusinessSource, } from "./sqlite/business-search.js";
22
23
  export type { ChatRekey, ChatRekeys } from "./sqlite/chat-rekey.js";
23
24
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
@@ -0,0 +1,92 @@
1
+ import type { Decider, Proposer } from "./decisions.js";
2
+ import type { Author } from "./sqlite/memories.js";
3
+ import type { IdentityRef } from "./types.js";
4
+ export declare const IDENTITY_LINK_KIND = "identity_link";
5
+ /**
6
+ * Why two people may be one: an agent said so, they share a phone or an address with others, or a meeting guest typed
7
+ * an address another person has.
8
+ */
9
+ export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email"];
10
+ export type IdentityLinkSignal = (typeof IDENTITY_LINK_SIGNALS)[number];
11
+ /** An `identity_link` proposal's payload. */
12
+ export interface IdentityLinkPayload {
13
+ /** `provider:id` of the identity that would move. */
14
+ identity: string;
15
+ /** `provider:id` of an identity of the person it would join; `null` for a person known by name only. */
16
+ with: string | null;
17
+ /** The person `identity` is on and the one it would join, as uids when it was proposed. */
18
+ persons: [string, string];
19
+ /** Each person's identities when it was proposed, so a confirm after either changed is refused. */
20
+ sides: [string, string];
21
+ /** `person` joins the two people; `identity` moves only `identity`, leaving the rest of its person. */
22
+ joins: "person" | "identity";
23
+ signal: IdentityLinkSignal;
24
+ score: number | null;
25
+ /** Every person the signal points at, the two included, when it points at more than two. */
26
+ candidates?: string[];
27
+ evidence: string[];
28
+ }
29
+ export interface IdentityLinkInput {
30
+ identity: IdentityRef;
31
+ with: IdentityRef;
32
+ signal: IdentityLinkSignal;
33
+ by: Author;
34
+ reason?: string;
35
+ score?: number;
36
+ evidence?: string[];
37
+ }
38
+ export interface IdentityLinkDecision {
39
+ confirm: boolean;
40
+ /** `"owner"` only on a path that established the owner decides; an agent is refused whatever the policy says. */
41
+ by: Decider;
42
+ reason?: string;
43
+ }
44
+ /** One `identity_link`, naming the people as they are now, not as they were when it was proposed. */
45
+ export interface IdentityLinkRow {
46
+ id: string;
47
+ status: "proposed" | "confirmed" | "rejected";
48
+ /** `person:<uid>` of the person `identity` is on, then of the one it would join. */
49
+ persons: [string, string];
50
+ identity: string;
51
+ with: string | null;
52
+ joins: IdentityLinkPayload["joins"];
53
+ signal: IdentityLinkSignal;
54
+ score: number | null;
55
+ candidates: string[];
56
+ reason: string | null;
57
+ evidence: string[];
58
+ proposedBy: Proposer;
59
+ createdAt: string;
60
+ }
61
+ export interface IdentityLinkFilter {
62
+ /** Only the proposals naming this person, or anyone merged into them, as they are now. */
63
+ person?: string;
64
+ /** `proposed` unless named. */
65
+ status?: IdentityLinkRow["status"] | "all";
66
+ limit: number;
67
+ offset: number;
68
+ }
69
+ /** What one pass of the people matcher did. */
70
+ export interface MatchScan {
71
+ /** Every identity was read, not only those changed since the last pass. */
72
+ full: boolean;
73
+ /** People joined without asking: the same personal address, or a phone exactly two people have. */
74
+ merged: {
75
+ into: string;
76
+ from: string;
77
+ signal: "same-email" | "same-phone";
78
+ }[];
79
+ /** Proposals opened, or open ones met again. */
80
+ proposed: {
81
+ id: string;
82
+ persons: [string, string];
83
+ signal: IdentityLinkSignal;
84
+ opened: boolean;
85
+ }[];
86
+ /** Pairs left apart, with why: the owner separated or rejected them, or too many people share the value. */
87
+ skipped: {
88
+ persons: string[];
89
+ signal: string;
90
+ reason: string;
91
+ }[];
92
+ }
@@ -0,0 +1,6 @@
1
+ export const IDENTITY_LINK_KIND = "identity_link";
2
+ /**
3
+ * Why two people may be one: an agent said so, they share a phone or an address with others, or a meeting guest typed
4
+ * an address another person has.
5
+ */
6
+ export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email"];
@@ -10,18 +10,19 @@ export type { FindingEvidence, FindingOutcome, MeetingFactFinding, MeetingFindin
10
10
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, type Payment, paymentTitle, validatePayment } from "../meetings/index.js";
11
11
  export { CLOSED_STATES, isClosedState, PRIORITY_LABELS, type PriorityLabel, priorityLabel, priorityOf, priorityOption, TASK_STATES, type TaskState, } from "../tasks/index.js";
12
12
  export type { AccountMail, AccountMeetings, AccountStore } from "./account-store.js";
13
- export { type DamageExplanation, explainDamage } from "./damage.js";
13
+ export { type DamageCause, type DamageFindings, type RecoveryStep, type StoreDamageReport, storeDamageReport, } from "./damage.js";
14
14
  export { CALLBACK_PREFIX, callbackDataOf, DECISION_ACTIONS, DECISION_TTL_MS, type DecisionAction, isDecisionToken, parseCallbackData, } from "./decision-requests.js";
15
15
  export { assertMayDecide, DEFAULT_DECISION_POLICY, type Decider, type DecisionPolicy, isOwnerOnlyKind, mayDecide, type Proposer, type Refusal, } from "./decisions.js";
16
16
  export type { DocumentTransferOptions, DocumentTransferPreview, DocumentTransferReceipt, } from "./document-transfer/index.js";
17
17
  export { applyDocumentTransfer, previewDocumentTransfer } from "./document-transfer/index.js";
18
18
  export type { CacheDatabase, CacheStatement, OpenDatabase, SqlValue } from "./driver.js";
19
19
  export { PRAGMAS } from "./driver.js";
20
- export { EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
20
+ export { type CitableRecord, EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
21
21
  export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
22
+ export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type MatchScan, } from "./identity-links.js";
22
23
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
23
24
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
24
- export { clearDamageMark, type DamageMark, damageMarkPath, type HealthMark, healthMarkPath, markStoreDamaged, readDamageMark, readHealthMark, recordDeepCheck, } from "./marks.js";
25
+ export { clearDamageMark, type DamageMark, damageMarkPath, type HealthMark, healthMarkPath, type JournalMark, journalMarkPath, markStoreDamaged, readDamageMark, readHealthMark, readJournalMark, recordDeepCheck, } from "./marks.js";
25
26
  export type { MeetingFindingsBatch, MeetingFindingsStore } from "./meeting-findings.js";
26
27
  export { MIGRATIONS, type Migration, migrate } from "./migrations.js";
27
28
  export { openCache } from "./open.js";
@@ -37,6 +38,8 @@ export { ADDED_KINDS, type AddedSource, type AddedSourceContent, type AddedSourc
37
38
  export type { AgentAction, AgentActionInput, AgentActionsStore } from "./sqlite/agent-actions.js";
38
39
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
39
40
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
41
+ export type { BaseColumn, BaseScope, BaseSet, BaseStagesStore, MappingFilter, StageMapping, StageName, } from "./sqlite/base-stages.js";
42
+ export { baseSettingKey } from "./sqlite/base-suggest.js";
40
43
  export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js";
41
44
  export type { Contract, ContractFields, ContractFilter, ContractInput, ContractsStore, ContractUpdate, } from "./sqlite/business-contracts.js";
42
45
  export type { BusinessHit, BusinessSearch, BusinessSearchStore, BusinessSource } from "./sqlite/business-search.js";
@@ -46,11 +49,12 @@ export { CATALOG_QUERY } from "./sqlite/catalog.js";
46
49
  export type { ChatMetadata } from "./sqlite/chats.js";
47
50
  export { type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
48
51
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, crmSettingKey, } from "./sqlite/crm-settings.js";
49
- export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, } from "./sqlite/deals.js";
52
+ export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
50
53
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
51
54
  export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
52
55
  export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
53
56
  export type { EvidenceInput, EvidenceMetadata } from "./sqlite/evidence-signature.js";
57
+ export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
54
58
  export type { EvidenceSource } from "./sqlite/evidence-sources.js";
55
59
  export type { Fact, FactInput, FactsStore } from "./sqlite/facts.js";
56
60
  export type { FileListQuery, FilesStore, StoredFile } from "./sqlite/files.js";
@@ -71,11 +75,13 @@ export type { NoteIndexState } from "./sqlite/note-index.js";
71
75
  export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, type NoteQuery, type NoteSearch, } from "./sqlite/note-search.js";
72
76
  export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
73
77
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
78
+ export type { OrganizationFilter } from "./sqlite/organization-categories.js";
74
79
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
75
80
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
76
81
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
77
82
  export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
78
83
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
84
+ export type { RelationshipCounts } from "./sqlite/record-relationships.js";
79
85
  export { type FlaggedRecord, type IncomingRelation, type MappedRecord, type MatchRun, type RecordKey, type RecordStore, type RecordsRun, type RunItem, type RunOptions, type SourceRecord, type SourceRecordRelation, type Unmatched, waitingPointer, } from "./sqlite/records.js";
80
86
  export type { RelationFilter, RelationList, RelationListItem } from "./sqlite/relation-list.js";
81
87
  export type { LinkDecision, RelationUpdate } from "./sqlite/relation-proposals.js";
@@ -105,4 +111,4 @@ export type { TagPreflight, VocabularyAlias, VocabularyAliasReceipt, VocabularyA
105
111
  export type { Wallet, WalletFilter, WalletInput, WalletsStore, WalletUpdate } from "./sqlite/wallets.js";
106
112
  export type { BoardCounts, BoardOptions, EditedTask, MovedSubtask, NewWorkTask, RevisionCheck, TaskAssignment, TaskDetails, TaskEvent, TaskFields, TaskMove, TaskMoved, TaskRole, TaskType, WorkTaskType, } from "./sqlite/work-tasks.js";
107
113
  export { TASK_EVENT_KINDS, TASK_ROLES } from "./sqlite/work-tasks.js";
108
- export { type AccountAccounts, type AccountAttachments, type AccountCounters, type AccountKey, type AccountMentions, type AccountMessageFilter, type AccountMessages, type AccountPeople, type AccountsStore, type AccountVectors, type AttachmentsStore, type AttachmentTextEntry, type AttachmentView, type ChatStats, type ChatsStore, type ConversationsStore, type CountersStore, type DeletionScope, type Delta, type FileAttachment, type IdentityRef, type IngestedVia, type LinkedIdentity, type LinkOptions, MENTION_QUERY, MENTION_STATUSES, type MentionsStore, type MessageFilter, type MessageStore, type MessagesStore, OTHER_SOURCES, openStore, type PeopleStore, type PersonFacts, type PersonRecord, type QueriesStore, type Range, type RankedEvidence, type RankedStoreFound, type RankedStoreRow, type RankingEvidenceItem, type RankingEvidenceRequest, type RankingRequest, type RosterStore, type SearchCommand, type SearchesStore, type SearchIndexStore, type SearchRecord, type StoredAccount, type StoredChatFilter, type StoredHit, type StoredSearch, type StoredTag, type StoreOptions, type SyncStore, type TagFilter, type TagsStore, type TagTarget, type TaskAnalysisMark, type TaskAnalysisMarkWrite, type TaskTagTarget, type TextOrigin, type VectorsStore, } from "./store.js";
114
+ export { type AccountAccounts, type AccountAttachments, type AccountCounters, type AccountGroupChange, type AccountKey, type AccountMentions, type AccountMessageFilter, type AccountMessages, type AccountPeople, type AccountsStore, type AccountVectors, type AttachmentsStore, type AttachmentTextEntry, type AttachmentView, type ChatStats, type ChatsStore, type ConversationsStore, type CountersStore, type DeletionScope, type Delta, type FileAttachment, type IdentityRef, type IngestedVia, type LinkedIdentity, type LinkOptions, MENTION_QUERY, MENTION_STATUSES, type MentionsStore, type MessageFilter, type MessageStore, type MessagesStore, OTHER_SOURCES, openStore, type PeopleStore, type PersonFacts, type PersonRecord, type QueriesStore, type Range, type RankedEvidence, type RankedStoreFound, type RankedStoreRow, type RankingEvidenceItem, type RankingEvidenceRequest, type RankingRequest, type RosterStore, type SearchCommand, type SearchesStore, type SearchIndexStore, type SearchRecord, type StoredAccount, type StoredChatFilter, type StoredHit, type StoredSearch, type StoredTag, type StoreOptions, type SyncStore, type TagFilter, type TagsStore, type TagTarget, type TaskAnalysisMark, type TaskAnalysisMarkWrite, type TaskTagTarget, type TextOrigin, type VectorsStore, } from "./store.js";
@@ -4,16 +4,17 @@ export { createTagRedirectIndex } from "../domain/tag-redirects.js";
4
4
  export { note } from "../entities/note.js";
5
5
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
6
6
  export { CLOSED_STATES, isClosedState, PRIORITY_LABELS, priorityLabel, priorityOf, priorityOption, TASK_STATES, } from "../tasks/index.js";
7
- export { explainDamage } from "./damage.js";
7
+ export { storeDamageReport, } from "./damage.js";
8
8
  export { CALLBACK_PREFIX, callbackDataOf, DECISION_ACTIONS, DECISION_TTL_MS, isDecisionToken, parseCallbackData, } from "./decision-requests.js";
9
9
  export { assertMayDecide, DEFAULT_DECISION_POLICY, isOwnerOnlyKind, mayDecide, } from "./decisions.js";
10
10
  export { applyDocumentTransfer, previewDocumentTransfer } from "./document-transfer/index.js";
11
11
  export { PRAGMAS } from "./driver.js";
12
12
  export { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "./evidence-findings.js";
13
13
  export { QUICK_HEALTH_CHECKS, storeHealth, } from "./health.js";
14
+ export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, } from "./identity-links.js";
14
15
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
15
16
  export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
16
- export { clearDamageMark, damageMarkPath, healthMarkPath, markStoreDamaged, readDamageMark, readHealthMark, recordDeepCheck, } from "./marks.js";
17
+ export { clearDamageMark, damageMarkPath, healthMarkPath, journalMarkPath, markStoreDamaged, readDamageMark, readHealthMark, readJournalMark, recordDeepCheck, } from "./marks.js";
17
18
  export { MIGRATIONS, migrate } from "./migrations.js";
18
19
  export { openCache } from "./open.js";
19
20
  export { storePath } from "./path.js";
@@ -26,11 +27,13 @@ export { SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, } from "./source-review.js";
26
27
  export { ADDED_KINDS, addedSourceKeyOf, } from "./sqlite/added-sources.js";
27
28
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
28
29
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
30
+ export { baseSettingKey } from "./sqlite/base-suggest.js";
29
31
  export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
30
32
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
31
33
  export { crmIdentityId } from "./sqlite/crm.js";
32
34
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
33
35
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
36
+ export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
34
37
  export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
35
38
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
36
39
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
@@ -0,0 +1,10 @@
1
+ import type { CacheDatabase } from "./driver.js";
2
+ /** Before the open. SQLite creates `-wal` before `-shm` and deletes it after, so it never leaves `-shm` alone itself. */
3
+ export declare const noteShmWithoutWal: (store: string, command: string) => void;
4
+ export declare const watchJournal: (database: CacheDatabase, store: string, command: string) => void;
5
+ /**
6
+ * Called before each outermost commit. A connection keeps writing into a `-wal` that was unlinked under it while the
7
+ * next process starts a fresh one, and the two journals then overwrite each other's pages: refusing the commit is
8
+ * the only point at which this process can still keep out of it.
9
+ */
10
+ export declare const checkJournal: (database: CacheDatabase) => void;
@@ -0,0 +1,33 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { markJournalLost } from "./marks.js";
4
+ const watched = new WeakMap();
5
+ const walInode = (store) => statSync(`${store}-wal`, { throwIfNoEntry: false })?.ino;
6
+ /** Before the open. SQLite creates `-wal` before `-shm` and deletes it after, so it never leaves `-shm` alone itself. */
7
+ export const noteShmWithoutWal = (store, command) => {
8
+ if (existsSync(`${store}-shm`) && !existsSync(`${store}-wal`))
9
+ markJournalLost(store, { seen: "shm-without-wal", command });
10
+ };
11
+ export const watchJournal = (database, store, command) => {
12
+ watched.set(database, { store, command, inode: walInode(store) });
13
+ };
14
+ /**
15
+ * Called before each outermost commit. A connection keeps writing into a `-wal` that was unlinked under it while the
16
+ * next process starts a fresh one, and the two journals then overwrite each other's pages: refusing the commit is
17
+ * the only point at which this process can still keep out of it.
18
+ */
19
+ export const checkJournal = (database) => {
20
+ const watch = watched.get(database);
21
+ if (!watch)
22
+ return;
23
+ const inode = walInode(watch.store);
24
+ if (watch.inode === undefined) {
25
+ watch.inode = inode;
26
+ return;
27
+ }
28
+ if (inode === watch.inode)
29
+ return;
30
+ markJournalLost(watch.store, { seen: inode === undefined ? "missing" : "replaced", command: watch.command });
31
+ throw new CliError("conflict", "the store's journal file was deleted or replaced by another program while this command had the store open, " +
32
+ "so nothing more is written; `store recover` says what to do", { reason: "store.journal-replaced" });
33
+ };
@@ -5,6 +5,7 @@ import type { StoreHealth } from "./health.js";
5
5
  */
6
6
  export declare const damageMarkPath: (store: string) => string;
7
7
  export declare const healthMarkPath: (store: string) => string;
8
+ export declare const journalMarkPath: (store: string) => string;
8
9
  /** A run saw SQLite say the store is damaged. Every writable open refuses while it names the file in place. */
9
10
  export interface DamageMark {
10
11
  at: string;
@@ -25,6 +26,15 @@ export interface HealthMark {
25
26
  cli_version?: string;
26
27
  last_ok_at: string | null;
27
28
  }
29
+ /**
30
+ * The store's `-wal` file went away or was swapped while a run held the store open, or a `-shm` stood without it at
31
+ * open: another program deleted or replaced the journal. Evidence for the damage report, not a refusal.
32
+ */
33
+ export interface JournalMark {
34
+ at: string;
35
+ command: string;
36
+ seen: "missing" | "replaced" | "shm-without-wal";
37
+ }
28
38
  /**
29
39
  * Leaves the damage mark when `error` is SQLite saying the store is damaged; the first sighting is kept. Never
30
40
  * throws: the failure being reported matters more than the mark.
@@ -41,10 +51,18 @@ export declare const readDamageMark: (store: string) => DamageMark | null;
41
51
  export declare const clearDamageMark: (store: string) => void;
42
52
  /** Thrown by a writable open of a store a run found damaged, so timers fail fast instead of writing into it. */
43
53
  export declare const refuseDamagedStore: (store: string, cli?: string) => void;
54
+ /** Keeps the first sighting; never throws. */
55
+ export declare const markJournalLost: (store: string, { seen, command, now }: {
56
+ seen: JournalMark["seen"];
57
+ command: string;
58
+ now?: () => number;
59
+ }) => void;
60
+ export declare const readJournalMark: (store: string) => JournalMark | null;
44
61
  export declare const readHealthMark: (store: string) => HealthMark | null;
45
62
  /**
46
63
  * Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
47
- * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
64
+ * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed. A pass
65
+ * also removes the journal mark: whatever the lost journal held is gone or was never needed.
48
66
  */
49
67
  export declare const recordDeepCheck: (store: string, health: Pick<StoreHealth, "ok" | "problems">, { cli, version, schema, now, }: {
50
68
  cli: string;
@@ -8,6 +8,7 @@ import { refuseOwnerStoreInTests } from "./path.js";
8
8
  */
9
9
  export const damageMarkPath = (store) => `${store}.damaged.json`;
10
10
  export const healthMarkPath = (store) => `${store}.health.json`;
11
+ export const journalMarkPath = (store) => `${store}.journal.json`;
11
12
  const inodeOf = (store) => statSync(store, { throwIfNoEntry: false })?.ino;
12
13
  const readJson = (path) => {
13
14
  try {
@@ -84,6 +85,24 @@ export const refuseDamagedStore = (store, cli) => {
84
85
  throw new CliError("configuration_error", `the store was found damaged at ${mark.at} by \`${mark.command}\` (${mark.error}), so nothing writes to it until ` +
85
86
  `it is recovered; \`${cli ?? "<cli>"} store recover\` says what is damaged and what to do`, { reason: "store.damaged" });
86
87
  };
88
+ /** Keeps the first sighting; never throws. */
89
+ export const markJournalLost = (store, { seen, command, now = Date.now }) => {
90
+ if (ownerStoreInTests(store))
91
+ return;
92
+ const mark = { at: new Date(now()).toISOString(), command, seen };
93
+ try {
94
+ writeFileSync(journalMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { flag: "wx", mode: 0o600 });
95
+ }
96
+ catch { }
97
+ };
98
+ export const readJournalMark = (store) => {
99
+ try {
100
+ return readJson(journalMarkPath(store));
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ };
87
106
  export const readHealthMark = (store) => {
88
107
  try {
89
108
  return readJson(healthMarkPath(store));
@@ -94,7 +113,8 @@ export const readHealthMark = (store) => {
94
113
  };
95
114
  /**
96
115
  * Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
97
- * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
116
+ * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed. A pass
117
+ * also removes the journal mark: whatever the lost journal held is gone or was never needed.
98
118
  */
99
119
  export const recordDeepCheck = (store, health, { cli, version, schema, now = Date.now, }) => {
100
120
  const previous = readHealthMark(store);
@@ -117,5 +137,7 @@ export const recordDeepCheck = (store, health, { cli, version, schema, now = Dat
117
137
  catch { }
118
138
  if (cleared)
119
139
  clearDamageMark(store);
140
+ if (health.ok)
141
+ rmSync(journalMarkPath(store), { force: true });
120
142
  return { previous, cleared };
121
143
  };
@@ -27,7 +27,7 @@ export interface Migration {
27
27
  export declare const MIGRATIONS: Migration[];
28
28
  /**
29
29
  * Brings the file up to this version, or opens a newer one it can still write to, or refuses.
30
- * Inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
30
+ * A file that needs work is migrated inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
31
31
  * that fails names `store reset` when the app has one: without it the owner is stuck until a build that can migrate
32
32
  * the file. An app without that command (drive) passes no `command`, and the advice names none.
33
33
  */
@@ -1,7 +1,8 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { lockedOutNotice, recordClient, refusalAdvice, storeClients } from "./sqlite/clients.js";
2
+ import { clientRecorded, lockedOutNotice, recordClient, refusalAdvice, storeClients } from "./sqlite/clients.js";
3
3
  import { generatedMigrations } from "./sqlite/manifest.js";
4
4
  import { discardRollbackCopy, recordRollbackCopy, takeRollbackCopy, } from "./sqlite/rollback-copy.js";
5
+ import { beginImmediate, rollBack } from "./sqlite/transaction.js";
5
6
  /**
6
7
  * Every migration is generated by drizzle-kit and numbered in `sqlite/manifest.ts`. Version 1 creates the whole
7
8
  * schema. **A migration that has reached anyone's file is never edited.** After it: forward-only and additive —
@@ -33,6 +34,30 @@ const fileState = (database) => {
33
34
  .get();
34
35
  return { version: Number(row?.version ?? 0), minCompatible: Number(row?.min_compatible ?? 0) };
35
36
  };
37
+ const refuseForeignOrNewer = (database, file, { ours, ownTable, command }) => {
38
+ if (file.version > 0 && ownTable !== null && !hasTable(database, ownTable)) {
39
+ throw new CliError("configuration_error", `the message store was written by another, incompatible tool (schema ${file.version} by its own numbering, ` +
40
+ "with no meetings table) — this tool will not open or change it; move it aside to start a new store");
41
+ }
42
+ if (file.version > ours && file.minCompatible > ours) {
43
+ throw new CliError("configuration_error", `the message store was written by a newer version (schema ${file.version}, needs at least ` +
44
+ `${file.minCompatible}; this one speaks ${ours}) — ${refusalAdvice(storeClients(database), command, file.version)}`);
45
+ }
46
+ };
47
+ /**
48
+ * Every writable open runs `migrate`, and most find the file current. Taking the write lock just to learn that queues
49
+ * each open behind the sync writers, so a current file is checked without it.
50
+ */
51
+ const current = (database, ours, client, now) => {
52
+ if (!hasTable(database, "schema_migrations"))
53
+ return undefined;
54
+ const file = fileState(database);
55
+ if (file.version < ours)
56
+ return undefined;
57
+ if (client && !clientRecorded(database, { ...client, speaks: ours }, now()))
58
+ return undefined;
59
+ return file;
60
+ };
36
61
  /** The tables every pending migration that raises `minCompatible` names; none for a new file or a foreign one. */
37
62
  const copyBeforeBreaking = (database, migrations, { ownTable, now }, options) => {
38
63
  if (!hasTable(database, "schema_migrations"))
@@ -55,14 +80,19 @@ const copyBeforeBreaking = (database, migrations, { ownTable, now }, options) =>
55
80
  };
56
81
  /**
57
82
  * Brings the file up to this version, or opens a newer one it can still write to, or refuses.
58
- * Inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
83
+ * A file that needs work is migrated inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
59
84
  * that fails names `store reset` when the app has one: without it the owner is stuck until a build that can migrate
60
85
  * the file. An app without that command (drive) passes no `command`, and the advice names none.
61
86
  */
62
87
  export const migrate = (database, { migrations = MIGRATIONS, now = Date.now, command, version, ownTable = OWN_TABLE, rollback, } = {}) => {
63
88
  const ours = latest(migrations);
89
+ const settled = current(database, ours, command && version ? { command, version } : undefined, now);
90
+ if (settled) {
91
+ refuseForeignOrNewer(database, settled, { ours, ownTable, command });
92
+ return undefined;
93
+ }
64
94
  let copy = rollback ? copyBeforeBreaking(database, migrations, { ownTable, now }, rollback) : undefined;
65
- database.exec("BEGIN IMMEDIATE");
95
+ beginImmediate(database);
66
96
  try {
67
97
  database.exec(HISTORY);
68
98
  const file = fileState(database);
@@ -71,14 +101,7 @@ export const migrate = (database, { migrations = MIGRATIONS, now = Date.now, com
71
101
  discardRollbackCopy(copy);
72
102
  copy = undefined;
73
103
  }
74
- if (file.version > 0 && ownTable !== null && !hasTable(database, ownTable)) {
75
- throw new CliError("configuration_error", `the message store was written by another, incompatible tool (schema ${file.version} by its own numbering, ` +
76
- "with no meetings table) — this tool will not open or change it; move it aside to start a new store");
77
- }
78
- if (file.version > ours && file.minCompatible > ours) {
79
- throw new CliError("configuration_error", `the message store was written by a newer version (schema ${file.version}, needs at least ` +
80
- `${file.minCompatible}; this one speaks ${ours}) — ${refusalAdvice(storeClients(database), command, file.version)}`);
81
- }
104
+ refuseForeignOrNewer(database, file, { ours, ownTable, command });
82
105
  const raisedTo = migrations
83
106
  .filter((migration) => migration.version > file.version)
84
107
  .reduce((highest, { minCompatible }) => Math.max(highest, minCompatible), file.minCompatible);
@@ -107,7 +130,7 @@ export const migrate = (database, { migrations = MIGRATIONS, now = Date.now, com
107
130
  return notice;
108
131
  }
109
132
  catch (error) {
110
- database.exec("ROLLBACK");
133
+ rollBack(database);
111
134
  if (error instanceof CliError)
112
135
  throw error;
113
136
  const cause = error instanceof Error ? error.message : String(error);
@@ -1,10 +1,12 @@
1
1
  import type { Contact, Id, Page, PersonAlias, Provider } from "../domain/models.js";
2
2
  import type { PeopleLookup } from "../resolve.js";
3
+ import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
3
4
  import type { ContactFilter } from "./sqlite/identities.js";
4
5
  import type { StoreContext } from "./sqlite/open.js";
5
6
  import type { PersonMerge } from "./sqlite/person-merges.js";
6
7
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
7
8
  import type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
9
+ import type { ProposedAction } from "./sqlite/proposed-actions.js";
8
10
  import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord } from "./types.js";
9
11
  export interface AccountPeople {
10
12
  savePeople(key: AccountKey, people: PersonFacts[]): Promise<void>;
@@ -64,6 +66,26 @@ export interface PeopleStore extends AccountPeople {
64
66
  undoMerge(to: string, from: string, by: string): Promise<PersonRecord>;
65
67
  /** The owner's split: the chosen identities become one new person, which this gives. */
66
68
  split(uid: string, identities: IdentityRef[], by: string): Promise<PersonRecord>;
69
+ /**
70
+ * Proposes that two identities' people are one, as an `identity_link` only the owner decides. Refused over the
71
+ * owner's separation or rejection; an open proposal for the same two people is given back instead of a second.
72
+ */
73
+ proposeLink(input: IdentityLinkInput): Promise<ProposedAction>;
74
+ /** The owner's decision on an `identity_link`; confirm is refused with `identity.stale` when either person changed. */
75
+ decideLink(id: string, decision: IdentityLinkDecision): Promise<ProposedAction>;
76
+ /**
77
+ * One pass of the people matcher: the same address joins people in every scope, a phone exactly two people have
78
+ * joins them, a phone more people share, a role address such as `info@` and a meeting guest's typed address become
79
+ * proposals. Never over the owner's separation; a pair the owner rejected is proposed again only on new evidence.
80
+ */
81
+ scanMatches(options?: {
82
+ full?: boolean;
83
+ }): Promise<MatchScan>;
84
+ /** The `identity_link` proposals, newest first, naming the people as they are now; `proposed` unless `status` says. */
85
+ linkProposals(filter: IdentityLinkFilter): Promise<{
86
+ items: IdentityLinkRow[];
87
+ hasMore: boolean;
88
+ }>;
67
89
  /** The identity, and everyone linked with it, is the owner. */
68
90
  linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
69
91
  /** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
@@ -2,8 +2,10 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { keysOver } from "./keys.js";
3
3
  import { ownerPerson } from "./sqlite/actors.js";
4
4
  import * as identities from "./sqlite/identities.js";
5
+ import * as identityProposals from "./sqlite/identity-proposals.js";
5
6
  import { linkToOwner } from "./sqlite/own-identities.js";
6
7
  import * as personLinks from "./sqlite/person-links.js";
8
+ import { RULE, scanMatches } from "./sqlite/person-match-scan.js";
7
9
  import * as personMerges from "./sqlite/person-merges.js";
8
10
  import { personPreparation } from "./sqlite/person-preparation.js";
9
11
  import { personSeenInAccounts } from "./sqlite/person-scope.js";
@@ -18,7 +20,15 @@ export const accountPeopleOver = (context) => {
18
20
  for (const person of people) {
19
21
  identityPk(accountKey, key.provider, person.id, person.name, person);
20
22
  if (person.email)
21
- personLinks.joinByAddress(context, { provider: key.provider, id: person.id }, person.email, key.provider);
23
+ personLinks.noteAddress(context, { provider: key.provider, id: person.id }, person.email);
24
+ }
25
+ // Every address of the batch is noted before any joins, so one shared by the whole batch is seen as shared.
26
+ for (const person of people) {
27
+ if (!person.email)
28
+ continue;
29
+ const held = personLinks.joinByAddress(context, { provider: key.provider, id: person.id }, person.email, key.provider);
30
+ if (held)
31
+ identityProposals.openIdentityLink(context, { ...held, joins: "person", signal: "email", by: RULE });
22
32
  }
23
33
  }),
24
34
  contacts: async (key, options) => {
@@ -95,6 +105,10 @@ export const peopleStoreOver = (context, keyed) => {
95
105
  merges: async (uid) => personMerges.merges(context, uid),
96
106
  undoMerge: async (to, from, by) => write(database, () => personMerges.undoMerge(context, to, from, by)),
97
107
  split: async (uid, chosen, by) => write(database, () => personMerges.split(context, uid, chosen, by)),
108
+ proposeLink: async (input) => identityProposals.proposeIdentityLink(context, input),
109
+ decideLink: async (id, decision) => identityProposals.decideIdentityLink(context, id, decision),
110
+ scanMatches: async (options) => scanMatches(context, options),
111
+ linkProposals: async (filter) => identityProposals.identityLinkRows(context, filter),
98
112
  linkToOwner: async (identity) => linkToOwner(context, identity),
99
113
  };
100
114
  };
@@ -1,5 +1,6 @@
1
1
  import type { CacheDatabase } from "./driver.js";
2
2
  import { type InvalidJson, type StoreHealth } from "./health.js";
3
+ import { type Refetch } from "./refill.js";
3
4
  /** `contentless_delete`, which every word index uses, came in SQLite 3.43. */
4
5
  export declare const SQLITE3_MINIMUM: readonly [3, 43, 0];
5
6
  export declare const sqlite3Program: (program?: string) => {
@@ -21,6 +22,23 @@ export declare const storeHolders: (path: string) => {
21
22
  }[] | undefined;
22
23
  /** Rows per table that holds data; `null` where the table cannot be counted. Search shadow tables are left out. */
23
24
  export declare const tableRows: (database: CacheDatabase) => Record<string, number | null>;
25
+ export interface IndexedButGone {
26
+ rows: number;
27
+ index: string;
28
+ }
29
+ /**
30
+ * Per table, the most entries one index of the damaged file holds that its table no longer has: rows, or a later
31
+ * change to them, that were lost before the recovery read the file. A stale page written over a table leaves its
32
+ * indexes as they were; one written over the index too leaves no trace, so this is a lower bound. Partial and
33
+ * expression indexes are left out: a plain scan cannot read them alone.
34
+ */
35
+ export declare const indexedButGone: (database: CacheDatabase) => Record<string, IndexedButGone>;
36
+ /**
37
+ * Puts back each row `.recover` found on a page no table claims into the one data table whose columns its values fit:
38
+ * a stale page copied over a table cuts committed rows off it, still readable. A row that fits no table, or more
39
+ * than one, stays out and is counted with the rest; a row whose key the table already holds leaves the table's row.
40
+ */
41
+ export declare const placeLostRows: (database: CacheDatabase) => Record<string, number>;
24
42
  /**
25
43
  * Copies every row SQLite can still read into a new file with the `sqlite3` program's `.recover`: node:sqlite has
26
44
  * no recovery API. The damaged file is opened read-only. Rows that fit no table go to a table the rebuild counts
@@ -68,6 +86,13 @@ export interface LostRows {
68
86
  before: number | null;
69
87
  read: number;
70
88
  kept: number;
89
+ /**
90
+ * Rows known to be gone after the recovery: an index of the damaged file lists them and its table did not hold
91
+ * them, less the rows put back from pages no table claimed. Rows lost without a trace are not in it.
92
+ */
93
+ goneAtLeast: number;
94
+ /** The index that showed them. */
95
+ seenIn: string | null;
71
96
  }
72
97
  export interface Recovery {
73
98
  path: string;
@@ -78,6 +103,13 @@ export interface Recovery {
78
103
  * `.recover` found, `kept` what fit the table; rows on pages it could not read at all are in none of them.
79
104
  */
80
105
  lost: LostRows[];
106
+ /** Per table, rows found on pages no table claimed and put back. */
107
+ placed: Record<string, number>;
108
+ /**
109
+ * The last deep check that passed before this recovery. A damaged file cannot show every row it lost, so whatever
110
+ * was written since may be gone without a count.
111
+ */
112
+ lastKnownGood: string | null;
81
113
  dangling: DanglingRows[];
82
114
  /** Values that were not valid JSON: set to NULL, or the row dropped where `required`. */
83
115
  invalidJson: InvalidJson[];
@@ -85,6 +117,8 @@ export interface Recovery {
85
117
  account: string;
86
118
  emails: number;
87
119
  }[];
120
+ /** What was marked not fetched, from a day before `lastKnownGood` on, so the next ordinary sync fetches it again. */
121
+ refetch: Refetch;
88
122
  rebuilt: DerivedRebuild;
89
123
  copyErrors: string[];
90
124
  health: StoreHealth;