@wirecat/cli-core 0.641.0 → 0.643.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 (287) hide show
  1. package/CHANGELOG.md +218 -0
  2. package/dist/analysis/provider.d.ts +1 -1
  3. package/dist/analysis/provider.js +2 -1
  4. package/dist/attachments/gateway-ocr.js +13 -8
  5. package/dist/attachments/ocr.js +27 -18
  6. package/dist/attachments/picture-reading.d.ts +51 -0
  7. package/dist/attachments/picture-reading.js +207 -0
  8. package/dist/background/backfill.d.ts +4 -2
  9. package/dist/background/backfill.js +3 -3
  10. package/dist/background/schedules.d.ts +28 -2
  11. package/dist/background/schedules.js +73 -20
  12. package/dist/background/units.d.ts +2 -0
  13. package/dist/background/units.js +8 -9
  14. package/dist/calendar/cli/index.js +10 -2
  15. package/dist/calendar/feeds.js +2 -2
  16. package/dist/calendar/mcp/index.d.ts +12 -12
  17. package/dist/calendar/server-search.js +2 -2
  18. package/dist/calendar/source.d.ts +4 -3
  19. package/dist/calendar/sync.js +12 -10
  20. package/dist/calendar/testing/source-contract.js +5 -4
  21. package/dist/calendar/testing/source.js +3 -2
  22. package/dist/cli/ai-model-command.js +6 -3
  23. package/dist/cli/analysis-choice.js +20 -4
  24. package/dist/cli/complete-command.d.ts +23 -0
  25. package/dist/cli/complete-command.js +80 -0
  26. package/dist/cli/context.js +7 -1
  27. package/dist/cli/effects.d.ts +2 -0
  28. package/dist/cli/effects.js +2 -0
  29. package/dist/cli/enrichment-consents-command.js +2 -0
  30. package/dist/cli/envelope.js +6 -1
  31. package/dist/cli/help/first-screen.js +5 -0
  32. package/dist/cli/index.d.ts +4 -2
  33. package/dist/cli/index.js +2 -1
  34. package/dist/cli/list-query.d.ts +3 -1
  35. package/dist/cli/list-query.js +5 -3
  36. package/dist/cli/local-only-command.d.ts +10 -0
  37. package/dist/cli/local-only-command.js +112 -0
  38. package/dist/cli/messenger/backfill-command.js +1 -1
  39. package/dist/cli/messenger/chat-queries.js +2 -1
  40. package/dist/cli/messenger/complete-command.d.ts +4 -7
  41. package/dist/cli/messenger/complete-command.js +31 -98
  42. package/dist/cli/messenger/contacts-command.js +4 -0
  43. package/dist/cli/messenger/conversations-command.js +1 -1
  44. package/dist/cli/messenger/guard-commands.js +1 -1
  45. package/dist/cli/messenger/images-command.js +32 -0
  46. package/dist/cli/messenger/list-result-queries.d.ts +1 -0
  47. package/dist/cli/messenger/list-result-queries.js +2 -1
  48. package/dist/cli/messenger/mentions-command.js +3 -3
  49. package/dist/cli/messenger/message-items.js +1 -0
  50. package/dist/cli/messenger/messages-command.js +7 -6
  51. package/dist/cli/messenger/people-queries.d.ts +2 -2
  52. package/dist/cli/messenger/people-queries.js +4 -4
  53. package/dist/cli/messenger/replies-consents-command.js +12 -6
  54. package/dist/cli/messenger/search-answers.js +2 -2
  55. package/dist/cli/messenger/search-command.js +3 -3
  56. package/dist/cli/messenger/searches-command.js +1 -1
  57. package/dist/cli/messenger/store-maintenance-command.js +4 -0
  58. package/dist/cli/messenger/tasks-analysis-command.js +1 -1
  59. package/dist/cli/messenger/tasks-command.js +2 -2
  60. package/dist/cli/model-catalogue-command.js +4 -0
  61. package/dist/cli/picture-reading-command.d.ts +12 -0
  62. package/dist/cli/picture-reading-command.js +82 -0
  63. package/dist/cli/program.d.ts +6 -0
  64. package/dist/cli/program.js +28 -2
  65. package/dist/cli/schedule/agent-start.d.ts +23 -0
  66. package/dist/cli/schedule/agent-start.js +115 -0
  67. package/dist/cli/schedule/harnesses.d.ts +203 -0
  68. package/dist/cli/schedule/harnesses.js +278 -0
  69. package/dist/cli/schedule/schedule-command.d.ts +9 -5
  70. package/dist/cli/schedule/schedule-command.js +89 -79
  71. package/dist/cli/search-harder-consents-command.js +16 -1
  72. package/dist/cli/shared-command-exports.d.ts +186 -0
  73. package/dist/cli/shared-command-exports.js +2 -0
  74. package/dist/cli/untrusted-marks.d.ts +25 -0
  75. package/dist/cli/untrusted-marks.js +102 -0
  76. package/dist/crm/cli/index.d.ts +1 -0
  77. package/dist/crm/cli/index.js +6 -5
  78. package/dist/crm/cli/store.d.ts +30 -0
  79. package/dist/crm/cli/store.js +63 -0
  80. package/dist/crm/source.d.ts +6 -4
  81. package/dist/crm/sync.js +10 -6
  82. package/dist/crm/testing/source-contract.js +9 -7
  83. package/dist/crm/testing/source.js +6 -2
  84. package/dist/crm/testing/sync-contract.js +4 -4
  85. package/dist/crm/writes.d.ts +5 -2
  86. package/dist/crm/writes.js +1 -1
  87. package/dist/documents.d.ts +2 -1
  88. package/dist/documents.js +2 -1
  89. package/dist/domain/addresses.d.ts +2 -0
  90. package/dist/domain/addresses.js +7 -0
  91. package/dist/domain/attachments.d.ts +2 -0
  92. package/dist/domain/attachments.js +2 -1
  93. package/dist/domain/models.d.ts +2 -0
  94. package/dist/embeddings/remote.d.ts +2 -1
  95. package/dist/embeddings/remote.js +5 -3
  96. package/dist/entities/attachment-results.d.ts +3 -0
  97. package/dist/entities/attachment-results.js +3 -0
  98. package/dist/entities/attachment.d.ts +2 -0
  99. package/dist/entities/attachment.js +8 -1
  100. package/dist/entities/hit.d.ts +1 -0
  101. package/dist/entities/index.d.ts +21 -4
  102. package/dist/entities/index.js +3 -2
  103. package/dist/entities/list-results.d.ts +33 -5
  104. package/dist/entities/list-results.js +33 -5
  105. package/dist/errors/reasons.js +38 -1
  106. package/dist/mail/cli/index.js +7 -6
  107. package/dist/mcp/agent.d.ts +2 -1
  108. package/dist/mcp/agent.js +5 -0
  109. package/dist/mcp/app-server.js +10 -0
  110. package/dist/mcp/surface.d.ts +7 -2
  111. package/dist/mcp/surface.js +49 -10
  112. package/dist/meetings/cli/index.js +6 -1
  113. package/dist/meetings/mcp/index.js +6 -3
  114. package/dist/meetings/participant-search.d.ts +2 -2
  115. package/dist/meetings/project-discovery.d.ts +1 -1
  116. package/dist/meetings/project-evidence-answer.js +2 -2
  117. package/dist/meetings/reads.d.ts +2 -2
  118. package/dist/meetings/reads.js +6 -6
  119. package/dist/meetings/store.d.ts +2 -1
  120. package/dist/meetings/testing/contract.js +6 -6
  121. package/dist/meetings/testing/memory.js +7 -2
  122. package/dist/models/ai.d.ts +17 -4
  123. package/dist/models/ai.js +22 -14
  124. package/dist/models/anthropic.js +15 -9
  125. package/dist/models/endpoint.d.ts +5 -0
  126. package/dist/models/endpoint.js +13 -0
  127. package/dist/models/index.d.ts +4 -0
  128. package/dist/models/index.js +14 -4
  129. package/dist/models/local-only.d.ts +17 -0
  130. package/dist/models/local-only.js +42 -0
  131. package/dist/models/openai.js +24 -11
  132. package/dist/models/purpose.d.ts +24 -0
  133. package/dist/models/purpose.js +26 -0
  134. package/dist/models/types.d.ts +8 -0
  135. package/dist/models/types.js +11 -1
  136. package/dist/ports/app.d.ts +17 -1
  137. package/dist/ports/app.js +63 -3
  138. package/dist/replies/rendering.js +10 -10
  139. package/dist/search/lucene/plain.js +45 -3
  140. package/dist/search/lucene/registry.d.ts +15 -4
  141. package/dist/search/lucene/registry.js +70 -12
  142. package/dist/search/lucene/types.d.ts +2 -0
  143. package/dist/search/lucene/types.js +12 -0
  144. package/dist/sends/upload.d.ts +8 -1
  145. package/dist/sends/upload.js +35 -14
  146. package/dist/services/account-groups.d.ts +11 -0
  147. package/dist/services/account-groups.js +29 -0
  148. package/dist/services/agenda.js +1 -0
  149. package/dist/services/attachments.d.ts +18 -4
  150. package/dist/services/attachments.js +66 -15
  151. package/dist/services/conversations.d.ts +2 -4
  152. package/dist/services/conversations.js +1 -1
  153. package/dist/services/deal-context.js +5 -5
  154. package/dist/services/documents/ingestion.js +3 -3
  155. package/dist/services/documents/knowledge.d.ts +6 -6
  156. package/dist/services/documents/knowledge.js +1 -2
  157. package/dist/services/embeddings-maintenance.js +4 -1
  158. package/dist/services/enrichment.d.ts +1 -1
  159. package/dist/services/enrichment.js +27 -0
  160. package/dist/services/events-search.d.ts +3 -3
  161. package/dist/services/events-search.js +7 -7
  162. package/dist/services/index.d.ts +1 -1
  163. package/dist/services/index.js +1 -1
  164. package/dist/services/meeting-model.js +1 -1
  165. package/dist/services/meeting-project-discovery.js +1 -1
  166. package/dist/services/message-resolution.js +10 -3
  167. package/dist/services/messages-search.js +6 -4
  168. package/dist/services/metadata.d.ts +1 -1
  169. package/dist/services/notes-search.d.ts +3 -3
  170. package/dist/services/notes-search.js +3 -3
  171. package/dist/services/organization-context.js +12 -9
  172. package/dist/services/people.d.ts +2 -0
  173. package/dist/services/people.js +4 -2
  174. package/dist/services/pictures.d.ts +9 -0
  175. package/dist/services/pictures.js +34 -28
  176. package/dist/services/project-status/index.js +1 -1
  177. package/dist/services/project-status/signals/payments.js +4 -2
  178. package/dist/services/project-status/signals/promises.js +5 -2
  179. package/dist/services/proposals/kinds/action.js +1 -1
  180. package/dist/services/proposals/kinds/fact.js +1 -1
  181. package/dist/services/proposals/kinds/findings.d.ts +2 -1
  182. package/dist/services/proposals/kinds/findings.js +12 -5
  183. package/dist/services/proposals/kinds/identity-link.js +1 -1
  184. package/dist/services/proposals/kinds/identity-split.js +1 -1
  185. package/dist/services/proposals/kinds/key-document.js +1 -1
  186. package/dist/services/proposals/kinds/mail-findings.d.ts +1 -1
  187. package/dist/services/proposals/kinds/mail-findings.js +11 -5
  188. package/dist/services/proposals/kinds/meeting-findings.js +10 -4
  189. package/dist/services/proposals/kinds/memory.js +1 -1
  190. package/dist/services/proposals/kinds/organization.js +1 -1
  191. package/dist/services/proposals/kinds/relationship-update.js +1 -1
  192. package/dist/services/proposals/kinds/relationship.js +1 -1
  193. package/dist/services/proposals/kinds/shared.d.ts +3 -2
  194. package/dist/services/proposals/kinds/shared.js +4 -4
  195. package/dist/services/proposals/kinds/source-review.js +1 -1
  196. package/dist/services/proposals/kinds/task-close.js +2 -2
  197. package/dist/services/proposals/registry.js +1 -1
  198. package/dist/services/proposals/types.d.ts +2 -1
  199. package/dist/services/search-all-business.js +3 -4
  200. package/dist/services/search-all.js +13 -14
  201. package/dist/services/search-harder.d.ts +11 -1
  202. package/dist/services/search-harder.js +38 -5
  203. package/dist/services/searches.d.ts +2 -4
  204. package/dist/services/searches.js +1 -4
  205. package/dist/services/stored-project-gathering.js +6 -1
  206. package/dist/services/tags.d.ts +2 -4
  207. package/dist/services/tags.js +1 -1
  208. package/dist/services/tasks.d.ts +1 -1
  209. package/dist/services/tasks.js +4 -3
  210. package/dist/speech/openai.js +2 -0
  211. package/dist/speech/transcribe.d.ts +5 -2
  212. package/dist/speech/transcribe.js +14 -5
  213. package/dist/store/account-store.d.ts +2 -1
  214. package/dist/store/account-store.js +3 -1
  215. package/dist/store/accounts.d.ts +2 -0
  216. package/dist/store/accounts.js +8 -0
  217. package/dist/store/chats.d.ts +5 -0
  218. package/dist/store/chats.js +4 -0
  219. package/dist/store/evidence-findings.d.ts +9 -0
  220. package/dist/store/exports.d.ts +1 -1
  221. package/dist/store/exports.js +1 -1
  222. package/dist/store/identity-links.d.ts +3 -1
  223. package/dist/store/mail-findings.d.ts +9 -0
  224. package/dist/store/meeting-findings.d.ts +9 -0
  225. package/dist/store/searches.d.ts +3 -2
  226. package/dist/store/sqlite/accounts.js +37 -0
  227. package/dist/store/sqlite/agent-actions.d.ts +2 -1
  228. package/dist/store/sqlite/agent-actions.js +10 -4
  229. package/dist/store/sqlite/business-contracts.d.ts +3 -1
  230. package/dist/store/sqlite/business-contracts.js +7 -3
  231. package/dist/store/sqlite/business-search.d.ts +2 -1
  232. package/dist/store/sqlite/business-search.js +6 -4
  233. package/dist/store/sqlite/deals.d.ts +6 -4
  234. package/dist/store/sqlite/deals.js +12 -7
  235. package/dist/store/sqlite/evidence-findings.js +78 -9
  236. package/dist/store/sqlite/facts.d.ts +2 -1
  237. package/dist/store/sqlite/facts.js +6 -2
  238. package/dist/store/sqlite/finance.d.ts +4 -2
  239. package/dist/store/sqlite/finance.js +13 -6
  240. package/dist/store/sqlite/findings-core.d.ts +56 -2
  241. package/dist/store/sqlite/findings-core.js +109 -22
  242. package/dist/store/sqlite/identities.d.ts +4 -0
  243. package/dist/store/sqlite/identities.js +12 -3
  244. package/dist/store/sqlite/identity-proposals.js +34 -4
  245. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  246. package/dist/store/sqlite/lucene-fields.js +28 -2
  247. package/dist/store/sqlite/lucene.js +21 -10
  248. package/dist/store/sqlite/mail-findings.js +60 -22
  249. package/dist/store/sqlite/meeting-findings.js +53 -7
  250. package/dist/store/sqlite/meeting-participant-search.js +4 -5
  251. package/dist/store/sqlite/meetings.js +7 -3
  252. package/dist/store/sqlite/memories.d.ts +4 -2
  253. package/dist/store/sqlite/memories.js +13 -6
  254. package/dist/store/sqlite/money-transactions.d.ts +3 -1
  255. package/dist/store/sqlite/money-transactions.js +7 -3
  256. package/dist/store/sqlite/name-traces.d.ts +3 -3
  257. package/dist/store/sqlite/name-traces.js +29 -2
  258. package/dist/store/sqlite/orders.d.ts +3 -1
  259. package/dist/store/sqlite/orders.js +5 -2
  260. package/dist/store/sqlite/people-list.js +67 -22
  261. package/dist/store/sqlite/person-match-scan.d.ts +3 -1
  262. package/dist/store/sqlite/person-match-scan.js +97 -7
  263. package/dist/store/sqlite/products.d.ts +3 -1
  264. package/dist/store/sqlite/products.js +5 -2
  265. package/dist/store/sqlite/proposed-actions.d.ts +2 -1
  266. package/dist/store/sqlite/proposed-actions.js +7 -3
  267. package/dist/store/sqlite/query-filter.d.ts +4 -0
  268. package/dist/store/sqlite/query-filter.js +14 -0
  269. package/dist/store/sqlite/reads.d.ts +1 -0
  270. package/dist/store/sqlite/reads.js +14 -0
  271. package/dist/store/sqlite/records.d.ts +3 -1
  272. package/dist/store/sqlite/records.js +7 -5
  273. package/dist/store/sqlite/rows-page.d.ts +3 -0
  274. package/dist/store/sqlite/rows-page.js +4 -0
  275. package/dist/store/sqlite/searches.d.ts +2 -1
  276. package/dist/store/sqlite/searches.js +3 -1
  277. package/dist/store/sqlite/subscriptions.d.ts +5 -2
  278. package/dist/store/sqlite/subscriptions.js +13 -6
  279. package/dist/store/sqlite/task-board.js +27 -0
  280. package/dist/store/sqlite/task-find.d.ts +15 -0
  281. package/dist/store/sqlite/task-find.js +1 -0
  282. package/dist/store/sqlite/wallets.d.ts +3 -1
  283. package/dist/store/sqlite/wallets.js +7 -3
  284. package/dist/store/sqlite/work-tasks.d.ts +3 -11
  285. package/dist/store/sqlite/work-tasks.js +8 -4
  286. package/package.json +2 -2
  287. package/parity.json +24 -0
@@ -1,12 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { contextEvidenceFingerprint } from "../../context/evidence.js";
3
- import { findingFingerprint, findingHash } from "../../meetings/index.js";
3
+ import { findingFingerprint, findingHash, } from "../../meetings/index.js";
4
4
  import { assertMayDecide } from "../decisions.js";
5
5
  import { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "../evidence-findings.js";
6
6
  import { contextRecordOf } from "./context-evidence.js";
7
7
  import { quoteKept } from "./evidence-signature.js";
8
8
  import { sourcesOfReferences } from "./evidence-sources.js";
9
- import { findingsAgent, findingsCoreOver } from "./findings-core.js";
9
+ import { editedFinding, FINDING_EDITS, findingsAgent, findingsCoreOver, findingToEdit, pendingOf, } from "./findings-core.js";
10
10
  import { authorActor } from "./memories.js";
11
11
  import { proposalOperationsOver } from "./proposed-actions.js";
12
12
  import { write } from "./transaction.js";
@@ -54,10 +54,12 @@ export const evidenceFindingsStoreOver = (context) => {
54
54
  decidedAt: proposal.decidedAt,
55
55
  previous: proposal.result
56
56
  ? proposal.result.items
57
- : input.findings.flatMap((finding) => {
58
- const held = core.previous(null, findingFingerprint(finding));
57
+ : pendingOf(input, input.decided).findings.flatMap((finding) => {
58
+ const held = core.previous(null, findingFingerprint(finding), proposal.id);
59
59
  return held ? [{ ...held, id: finding.id, reused: true }] : [];
60
60
  }),
61
+ decided: proposal.result ? [] : (input.decided ?? []),
62
+ edited: input.edited ?? [],
61
63
  receipt: proposal.result,
62
64
  };
63
65
  };
@@ -91,6 +93,20 @@ export const evidenceFindingsStoreOver = (context) => {
91
93
  };
92
94
  };
93
95
  const snapshot = (input) => core.snapshot(input, cite());
96
+ /**
97
+ * The whole-batch hash the next review of an old batch compares, over the findings still waiting. Evidence that
98
+ * changed under a waiting finding keeps the old hash, so accepting that finding stays refused as stale.
99
+ */
100
+ const snapshotOr = (waiting, held) => {
101
+ try {
102
+ return snapshot(waiting);
103
+ }
104
+ catch (error) {
105
+ if (error.details?.reason === "evidence-findings.stale")
106
+ return held;
107
+ throw error;
108
+ }
109
+ };
94
110
  const decider = (by) => {
95
111
  if (by === "owner")
96
112
  return { author: "owner", decision: { by: "owner" } };
@@ -197,11 +213,12 @@ export const evidenceFindingsStoreOver = (context) => {
197
213
  ownerOnly: batch.ownerOnly,
198
214
  }, decision.by, context.decisions);
199
215
  if (batch.receipt) {
200
- if (JSON.stringify(batch.receipt.accepted) !== JSON.stringify(accepted))
216
+ if (!core.sameDecision(batch.receipt, accepted))
201
217
  return invalid("this findings batch was already reviewed with a different decision");
202
218
  return batch;
203
219
  }
204
220
  const input = proposal.payload;
221
+ const waiting = pendingOf(batch.input, input.decided);
205
222
  // Rejecting creates nothing, so a batch whose evidence changed can still be closed. Accepting needs only the
206
223
  // accepted findings' own evidence and assignee unchanged. The project is left out: every task a sibling batch
207
224
  // creates moves its row, and the project still has to exist, which citing checks. A batch staged before parts
@@ -209,11 +226,11 @@ export const evidenceFindingsStoreOver = (context) => {
209
226
  if (accepted.length) {
210
227
  const parts = input.snapshotParts;
211
228
  if (!parts) {
212
- if (snapshot(batch.input) !== input.snapshotHash)
229
+ if (snapshot(waiting) !== input.snapshotHash)
213
230
  return stale();
214
231
  }
215
232
  else {
216
- const chosen = { ...batch.input, findings: batch.input.findings.filter((f) => accepted.includes(f.id)) };
233
+ const chosen = { ...batch.input, findings: waiting.findings.filter((f) => accepted.includes(f.id)) };
217
234
  const now = core.snapshotParts(chosen, cite());
218
235
  if (Object.entries(now).some(([key, hash]) => !key.startsWith("project:") && parts[key] !== hash))
219
236
  return stale();
@@ -225,13 +242,65 @@ export const evidenceFindingsStoreOver = (context) => {
225
242
  bot: proposal.proposedBy.name,
226
243
  ...(input.agentModel === null ? {} : { model: input.agentModel }),
227
244
  };
228
- const items = core.outcomes(null, batch.input, accepted, agent, decision.by);
245
+ const by = decision.by;
246
+ const { items, pending } = core.settle({
247
+ batch: id,
248
+ account: null,
249
+ findings: batch.input.findings,
250
+ decided: input.decided ?? [],
251
+ accepted,
252
+ fingerprintOf: findingFingerprint,
253
+ make: (finding) => core.create(finding, agent, by),
254
+ });
255
+ const named = core.named(input.accepted, accepted);
256
+ if (pending.length) {
257
+ core.keepWaiting(id, {
258
+ ...input,
259
+ decided: items,
260
+ accepted: named,
261
+ snapshotHash: snapshotOr({ ...batch.input, findings: pending }, input.snapshotHash),
262
+ });
263
+ return view(load(id));
264
+ }
229
265
  return view(proposals.approve(id, {
230
266
  previewFingerprint: batch.fingerprint,
231
- accepted,
267
+ accepted: named,
232
268
  items,
233
269
  decision: decidedBy,
234
270
  }, author));
235
271
  }),
272
+ edit: async (id, finding, changes, options) => write(database, () => {
273
+ const proposal = load(id);
274
+ const batch = view(proposal);
275
+ const original = findingToEdit(batch, finding, options, stale);
276
+ const input = proposal.payload;
277
+ const parts = input.snapshotParts;
278
+ const alone = (one) => ({ ...batch.input, findings: [one] });
279
+ if (parts) {
280
+ const now = core.snapshotParts(alone(original), cite());
281
+ if (Object.entries(now).some(([key, hash]) => !key.startsWith("project:") && parts[key] !== hash))
282
+ return stale();
283
+ }
284
+ else if (snapshot(pendingOf(batch.input, input.decided)) !== input.snapshotHash)
285
+ return stale();
286
+ const edited = editedFinding(original, changes, FINDING_EDITS, "evidence finding");
287
+ const checked = validateEvidenceFindings({
288
+ ...batch.input,
289
+ findings: batch.input.findings.map((one) => (one.id === finding ? edited : one)),
290
+ });
291
+ const fingerprints = checked.findings.map(findingFingerprint);
292
+ if (new Set(fingerprints).size !== fingerprints.length)
293
+ return invalid("the edit makes two findings the same");
294
+ // The agent's inputHash stays: its rerun of the same key still finds this batch, now as the owner left it.
295
+ const now = checked.findings.find((one) => one.id === finding);
296
+ core.keepWaiting(id, {
297
+ ...input,
298
+ findings: checked.findings,
299
+ snapshotHash: snapshotOr(pendingOf(checked, input.decided), input.snapshotHash),
300
+ ...(parts ? { snapshotParts: { ...parts, ...core.snapshotParts(alone(now), cite()) } } : {}),
301
+ edited: [...new Set([...(input.edited ?? []), finding])],
302
+ });
303
+ return view(load(id));
304
+ }),
236
305
  };
237
306
  };
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type FACT_STATUSES, FACT_TYPES, MEMORY_SCOPES } from "../../domain/knowledge.js";
2
3
  import { type Decider } from "../decisions.js";
3
4
  import type { SourceReviewMarker } from "../source-review.js";
@@ -71,7 +72,7 @@ export interface FactsStore {
71
72
  limit?: number;
72
73
  /** Rows to skip, for the next page in the same order, ties by id. */
73
74
  offset?: number;
74
- }): Promise<Fact[]>;
75
+ }): Promise<ListResult<Fact>>;
75
76
  /** The owner, or an agent for the owner, accepts a proposed fact; the fact it supersedes stops holding. */
76
77
  accept(reference: string, by: Decider, reason?: string): Promise<Fact>;
77
78
  /** An accepted decision no longer holds and nothing replaced it. */
@@ -8,6 +8,7 @@ import { linkKind } from "./link-kinds.js";
8
8
  import { authorActor, authorOf, dropLinksOf, erase, evidenceOf, keepHighestId, linkEvidence, nextId, projectOf, subjectOf, } from "./memories.js";
9
9
  import { idsOf } from "./merged-persons.js";
10
10
  import { requiredThing } from "./notes.js";
11
+ import { pageOfRows } from "./rows-page.js";
11
12
  import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
12
13
  import { write } from "./transaction.js";
13
14
  const NAMED = "SELECT f.*, b.name AS author_name, b.kind AS author_kind FROM facts f LEFT JOIN bots b ON f.author_type = 'bot' AND b.id = f.author_id";
@@ -134,16 +135,19 @@ export const factOperationsOver = (context) => {
134
135
  },
135
136
  get: (reference) => factOf(rowOf(reference)),
136
137
  list: (options = {}) => {
138
+ const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
139
+ const offset = Math.max(options.offset ?? 0, 0);
137
140
  const project = options.project === undefined ? undefined : requiredThing(database, options.project, "the project");
138
141
  const subject = options.subject === undefined ? undefined : requiredThing(database, options.subject);
139
142
  const by = proposedBySql("f.author_type", "f.author_id", options.proposedBy);
140
143
  const order = options.order === "created" ? "f.created_at" : "coalesce(f.occurred_at, f.created_at)";
141
- return database
144
+ const rows = database
142
145
  .prepare(`${NAMED} WHERE f.deleted_at IS NULL AND (? IS NULL OR f.type = ?) AND (? IS NULL OR f.project_id = ?) ` +
143
146
  "AND (? IS NULL OR (f.subject_type = ? AND f.subject_id IN (SELECT value FROM json_each(?)))) AND (? IS NULL OR f.status = ?) " +
144
147
  `AND ${by.sql} ORDER BY ${order} DESC, f.id DESC LIMIT ? OFFSET ?`)
145
- .all(options.type ?? null, options.type ?? null, project?.id ?? null, project?.id ?? null, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, options.status ?? null, options.status ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500), Math.max(options.offset ?? 0, 0))
148
+ .all(options.type ?? null, options.type ?? null, project?.id ?? null, project?.id ?? null, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, options.status ?? null, options.status ?? null, ...by.params, limit + 1, offset)
146
149
  .map(factOf);
150
+ return pageOfRows(rows, limit, offset);
147
151
  },
148
152
  accept: (reference, by, reason) => {
149
153
  const row = rowOf(reference);
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type FinanceReview, type InvoiceDirection, type InvoiceStatus, type MoneyDirection } from "../../domain/finance.js";
2
3
  import { type Money } from "../../domain/money.js";
3
4
  import type { Decider } from "../decisions.js";
@@ -104,6 +105,7 @@ interface ListFilter {
104
105
  proposedBy?: ProposedByFilter;
105
106
  /** 1–500, 100 by default; newest written first. */
106
107
  limit?: number;
108
+ offset?: number;
107
109
  }
108
110
  export interface OpenTotal extends Money {
109
111
  invoices: number;
@@ -119,7 +121,7 @@ export interface FinanceStore {
119
121
  counterparty?: string;
120
122
  /** The number printed on it, exactly. */
121
123
  number?: string;
122
- }): Promise<Invoice[]>;
124
+ }): Promise<ListResult<Invoice>>;
123
125
  /**
124
126
  * A line at the end, and the total follows. The owner changes any invoice's lines but a void one's, a bot only those
125
127
  * of an invoice it proposed that is still proposed; the total never falls below what confirmed payments settled.
@@ -141,7 +143,7 @@ export interface FinanceStore {
141
143
  payments(filter?: ListFilter & {
142
144
  direction?: MoneyDirection;
143
145
  party?: string;
144
- }): Promise<Payment[]>;
146
+ }): Promise<ListResult<Payment>>;
145
147
  /**
146
148
  * Settles part of an invoice with part of a payment, in one currency, never beyond either. The owner allocates any
147
149
  * payment; a bot only one it proposed that is still proposed.
@@ -7,6 +7,7 @@ import { MAX_LINES, moneyLinesOver } from "./money-lines.js";
7
7
  import { requiredThing } from "./notes.js";
8
8
  import { netPaidSql, refundRulesOver } from "./refunds.js";
9
9
  import { iso, isoDate, limitOf, oneOf, prefixesText, refuse, reviewedRowsOver, text, } from "./reviewed.js";
10
+ import { pageOfRows } from "./rows-page.js";
10
11
  import { write } from "./transaction.js";
11
12
  /** The types `decide` settles money for; other proposal types get their own route. */
12
13
  const FINANCE_TYPES = ["invoice", "payment"];
@@ -311,19 +312,22 @@ export const financeOperationsOver = (context) => {
311
312
  return relined(row, (id) => lines.deleteLine("invoice", id, position));
312
313
  },
313
314
  invoices: (filter = {}) => {
315
+ const limit = limitOf(filter.limit);
316
+ const offset = Math.max(filter.offset ?? 0, 0);
314
317
  const project = filter.project === undefined ? null : projectId(database, filter.project);
315
318
  const counterparty = partyThing(filter.counterparty, "the counterparty");
316
319
  const by = proposedBySql("i.author_type", "i.author_id", filter.proposedBy);
317
320
  const status = filter.status === undefined ? null : oneOf(filter.status, INVOICE_STATUSES, "a status");
318
321
  const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
319
- return database
322
+ const rows = database
320
323
  .prepare(`${INVOICES} WHERE i.deleted_at IS NULL AND (? IS NULL OR i.direction = ?) AND (? IS NULL OR i.status = ?) ` +
321
324
  "AND (? IS NULL OR i.review = ?) AND (? IS NULL OR i.project_id = ?) " +
322
325
  "AND (? IS NULL OR (i.counterparty_type = ? AND i.counterparty_id = ?)) AND (? IS NULL OR i.number = ?) " +
323
326
  `${filter.open ? "AND i.status IN ('issued', 'partly_paid') " : ""}AND ${by.sql} ` +
324
- "ORDER BY i.created_at DESC, i.id DESC LIMIT ?")
325
- .all(filter.direction ?? null, filter.direction ?? null, status, status, review, review, project, project, counterparty?.type ?? null, counterparty?.type ?? null, counterparty?.id ?? null, filter.number ?? null, filter.number ?? null, ...by.params, limitOf(filter.limit))
327
+ "ORDER BY i.created_at DESC, i.id DESC LIMIT ? OFFSET ?")
328
+ .all(filter.direction ?? null, filter.direction ?? null, status, status, review, review, project, project, counterparty?.type ?? null, counterparty?.type ?? null, counterparty?.id ?? null, filter.number ?? null, filter.number ?? null, ...by.params, limit + 1, offset)
326
329
  .map(invoiceOf);
330
+ return pageOfRows(rows, limit, offset);
327
331
  },
328
332
  issueInvoice: (reference, by) => {
329
333
  ownerOnly(by, "issues an invoice");
@@ -389,16 +393,19 @@ export const financeOperationsOver = (context) => {
389
393
  },
390
394
  payment: (reference) => paymentDetail(reference),
391
395
  payments: (filter = {}) => {
396
+ const limit = limitOf(filter.limit);
397
+ const offset = Math.max(filter.offset ?? 0, 0);
392
398
  const project = filter.project === undefined ? null : projectId(database, filter.project);
393
399
  const party = partyThing(filter.party, "the party");
394
400
  const by = proposedBySql("p.author_type", "p.author_id", filter.proposedBy);
395
401
  const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
396
- return database
402
+ const rows = database
397
403
  .prepare(`${PAYMENTS} WHERE p.deleted_at IS NULL AND (? IS NULL OR p.direction = ?) AND (? IS NULL OR p.review = ?) ` +
398
404
  "AND (? IS NULL OR p.project_id = ?) AND (? IS NULL OR (p.payer_type = ? AND p.payer_id = ?) " +
399
- `OR (p.payee_type = ? AND p.payee_id = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
400
- .all(filter.direction ?? null, filter.direction ?? null, review, review, project, project, party?.type ?? null, party?.type ?? null, party?.id ?? null, party?.type ?? null, party?.id ?? null, ...by.params, limitOf(filter.limit))
405
+ `OR (p.payee_type = ? AND p.payee_id = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ? OFFSET ?`)
406
+ .all(filter.direction ?? null, filter.direction ?? null, review, review, project, project, party?.type ?? null, party?.type ?? null, party?.id ?? null, party?.type ?? null, party?.id ?? null, ...by.params, limit + 1, offset)
401
407
  .map(paymentOf);
408
+ return pageOfRows(rows, limit, offset);
402
409
  },
403
410
  allocate: ({ payment, invoice, amount, by }) => {
404
411
  const row = rowOf(payment, "payment");
@@ -6,6 +6,40 @@ export interface FindingsAgent {
6
6
  model?: string;
7
7
  }
8
8
  export declare const findingsAgent: (agent: FindingsAgent) => FindingsAgent;
9
+ /**
10
+ * What the owner may change in a finding before it is decided: its words and the fields that only say what the agent
11
+ * read. Evidence never changes, and neither does a meeting or evidence finding's project, which its evidence vouches
12
+ * for.
13
+ */
14
+ export declare const FINDING_EDITS: Readonly<Record<string, readonly string[]>>;
15
+ /** The finding with the owner's changes; `null` clears an optional field. The kind's own validation runs after. */
16
+ export declare const editedFinding: <F extends {
17
+ id: string;
18
+ kind: string;
19
+ }>(finding: F, changes: Record<string, unknown>, editable: Readonly<Record<string, readonly string[]>>, noun: string) => F;
20
+ /**
21
+ * The finding an owner's edit changes: only the owner edits, only a batch still waiting, at the fingerprint the owner
22
+ * read, and only a finding this batch has not decided yet.
23
+ */
24
+ export declare const findingToEdit: <F extends {
25
+ id: string;
26
+ }>(batch: {
27
+ status: string;
28
+ fingerprint: string;
29
+ input: {
30
+ findings: readonly F[];
31
+ };
32
+ decided: readonly FindingOutcome[];
33
+ }, finding: string, options: {
34
+ fingerprint: string;
35
+ by: Decider;
36
+ }, stale: () => never) => F;
37
+ /** The findings a review has not decided yet. */
38
+ export declare const pendingOf: <I extends {
39
+ findings: readonly {
40
+ id: string;
41
+ }[];
42
+ }>(input: I, decided: readonly FindingOutcome[] | undefined) => I;
9
43
  /**
10
44
  * What meeting and evidence findings share: the project and assignee snapshot, earlier decisions on an unchanged
11
45
  * candidate, creating the accepted facts and tasks, and the receipt items. Each kind checks its own evidence,
@@ -14,7 +48,27 @@ export declare const findingsAgent: (agent: FindingsAgent) => FindingsAgent;
14
48
  export declare const findingsCoreOver: (context: StoreContext, kind: string) => {
15
49
  snapshot: (input: FindingsInput, cite: (evidence: FindingEvidence, finding: Finding, projectId: string | null, seen: Map<string, unknown>) => void) => string;
16
50
  snapshotParts: (input: FindingsInput, cite: (evidence: FindingEvidence, finding: Finding, projectId: string | null, seen: Map<string, unknown>) => void) => Record<string, string>;
17
- previous: (account: number | null, fingerprint: string) => FindingOutcome | undefined;
18
- outcomes: (account: number | null, input: FindingsInput, accepted: string[], agent: FindingsAgent, decidedBy: Decider) => FindingOutcome[];
51
+ previous: (account: number | null, fingerprint: string, except?: string) => FindingOutcome | undefined;
52
+ settle: <F extends {
53
+ id: string;
54
+ }>(options: {
55
+ batch: string;
56
+ account: number | null;
57
+ findings: readonly F[];
58
+ decided: readonly FindingOutcome[];
59
+ accepted: readonly string[];
60
+ fingerprintOf: (finding: F) => string;
61
+ make: (finding: F) => string;
62
+ }) => {
63
+ items: FindingOutcome[];
64
+ pending: F[];
65
+ };
66
+ keepWaiting: (id: string, payload: object) => {
67
+ changes: number;
68
+ };
69
+ named: (earlier: readonly string[] | undefined, now: readonly string[]) => string[];
70
+ sameDecision: (receipt: {
71
+ accepted: string[];
72
+ }, accepted: readonly string[]) => boolean;
19
73
  create: (finding: Finding, agent: FindingsAgent, decidedBy: Decider) => string;
20
74
  };
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { findingFingerprint, findingHash, } from "../../meetings/index.js";
2
+ import { findingFields, findingHash, } from "../../meetings/index.js";
3
3
  import { factOperationsOver } from "./facts.js";
4
4
  import { linkEvidence } from "./memories.js";
5
5
  import { requiredThing } from "./notes.js";
@@ -19,6 +19,60 @@ export const findingsAgent = (agent) => {
19
19
  return invalid("findings must name an agent author independently of their payload");
20
20
  return { bot: agent.bot, ...(agent.model === undefined ? {} : { model: agent.model }) };
21
21
  };
22
+ /**
23
+ * What the owner may change in a finding before it is decided: its words and the fields that only say what the agent
24
+ * read. Evidence never changes, and neither does a meeting or evidence finding's project, which its evidence vouches
25
+ * for.
26
+ */
27
+ export const FINDING_EDITS = {
28
+ fact: ["statement", "type", "subject"],
29
+ task: ["title", "type", "reason", "commitment", "dueAt", "dueEvidence", "assignee", "assigneeEvidence"],
30
+ payment: ["statement"],
31
+ };
32
+ /** Each optional field a cleared field takes with it, so a cleared due date leaves no orphaned support. */
33
+ const CLEARS = { dueAt: "dueEvidence", assignee: "assigneeEvidence" };
34
+ /** The finding with the owner's changes; `null` clears an optional field. The kind's own validation runs after. */
35
+ export const editedFinding = (finding, changes, editable, noun) => {
36
+ if (!changes || typeof changes !== "object" || Array.isArray(changes) || Object.keys(changes).length === 0)
37
+ return invalid("an edit changes at least one field of the finding");
38
+ findingFields(changes, [...(editable[finding.kind] ?? [])], noun, finding);
39
+ const edited = { ...finding };
40
+ for (const [key, value] of Object.entries(changes)) {
41
+ if (value !== null) {
42
+ edited[key] = value;
43
+ continue;
44
+ }
45
+ delete edited[key];
46
+ const also = CLEARS[key];
47
+ if (also)
48
+ delete edited[also];
49
+ }
50
+ return edited;
51
+ };
52
+ /**
53
+ * The finding an owner's edit changes: only the owner edits, only a batch still waiting, at the fingerprint the owner
54
+ * read, and only a finding this batch has not decided yet.
55
+ */
56
+ export const findingToEdit = (batch, finding, options, stale) => {
57
+ if (options?.by !== "owner")
58
+ throw new CliError("permission_error", "only the owner edits a finding before it is decided", {
59
+ reason: "proposal.owner-only",
60
+ });
61
+ if (batch.status !== "proposed")
62
+ throw new CliError("validation_error", "this findings batch was already reviewed; its findings stay as decided", {
63
+ reason: "proposal.wrong-state",
64
+ });
65
+ if (typeof options.fingerprint !== "string" || options.fingerprint !== batch.fingerprint)
66
+ return stale();
67
+ const found = batch.input.findings.find((one) => one.id === finding);
68
+ if (!found)
69
+ throw new CliError("not_found", `no finding ${finding} in this batch`);
70
+ if (batch.decided.some((one) => one.id === finding))
71
+ throw new CliError("validation_error", `finding ${finding} was already decided`, { reason: "proposal.wrong-state" });
72
+ return found;
73
+ };
74
+ /** The findings a review has not decided yet. */
75
+ export const pendingOf = (input, decided) => ({ ...input, findings: input.findings.filter((one) => !decided?.some((done) => done.id === one.id)) });
22
76
  /**
23
77
  * What meeting and evidence findings share: the project and assignee snapshot, earlier decisions on an unchanged
24
78
  * candidate, creating the accepted facts and tasks, and the receipt items. Each kind checks its own evidence,
@@ -64,10 +118,13 @@ export const findingsCoreOver = (context, kind) => {
64
118
  const snapshot = (...args) => findingHash([...cited(...args)].sort(([a], [b]) => a.localeCompare(b)));
65
119
  /** The same snapshot, one hash per project, person and cited reference, so part of a batch can be checked alone. */
66
120
  const snapshotParts = (...args) => Object.fromEntries([...cited(...args)].map(([key, value]) => [key, findingHash(value)]));
67
- const previous = (account, fingerprint) => {
121
+ // A batch still partly pending keeps its decisions in the payload, so an unchanged finding another batch carries
122
+ // is never created twice.
123
+ const previous = (account, fingerprint, except) => {
68
124
  const row = database
69
- .prepare("SELECT substr(j.value,1,4096) AS item FROM proposed_actions p,json_each(p.result,'$.items') j WHERE p.account_id IS ? AND p.kind=? AND p.status='approved' AND json_extract(j.value,'$.fingerprint')=? ORDER BY p.id LIMIT 1")
70
- .get(account, kind, fingerprint);
125
+ .prepare("SELECT item FROM (SELECT p.id, substr(j.value,1,4096) AS item FROM proposed_actions p,json_each(p.result,'$.items') j WHERE p.account_id IS ? AND p.kind=? AND p.status='approved' AND json_extract(j.value,'$.fingerprint')=? " +
126
+ "UNION ALL SELECT p.id, substr(j.value,1,4096) AS item FROM proposed_actions p,json_each(p.payload,'$.decided') j WHERE p.account_id IS ? AND p.kind=? AND p.status='proposed' AND p.id IS NOT ? AND json_extract(j.value,'$.fingerprint')=?) ORDER BY id LIMIT 1")
127
+ .get(account, kind, fingerprint, account, kind, except === undefined ? null : Number(except), fingerprint);
71
128
  return row ? JSON.parse(String(row.item)) : undefined;
72
129
  };
73
130
  const create = (finding, agent, decidedBy) => {
@@ -106,23 +163,53 @@ export const findingsCoreOver = (context, kind) => {
106
163
  tasks.assign(task.id, { to: finding.assignee, role: "assignee" }, agent);
107
164
  return task.ref;
108
165
  };
109
- /** Reuses an earlier decision on an unchanged candidate; refuses to accept one that was rejected. */
110
- const outcomes = (account, input, accepted, agent, decidedBy) => input.findings.map((finding) => {
111
- const fingerprint = findingFingerprint(finding);
112
- const prior = previous(account, fingerprint);
113
- if (prior) {
114
- if (accepted.includes(finding.id) && prior.status === "rejected")
115
- return invalid("this unchanged finding was already rejected; changed evidence needs a new candidate");
116
- return { ...prior, id: finding.id, reused: true };
166
+ /**
167
+ * Decides what a review settles. A confirm settles the findings it names and any unchanged candidate decided
168
+ * earlier; the rest wait for the owner. A reject (no names) settles everything still pending. A finding this batch
169
+ * already decided keeps its outcome, so nothing is created twice.
170
+ */
171
+ const settle = (options) => {
172
+ const { accepted } = options;
173
+ const items = [];
174
+ const pending = [];
175
+ for (const finding of options.findings) {
176
+ const named = accepted.includes(finding.id);
177
+ const done = options.decided.find((one) => one.id === finding.id);
178
+ if (done) {
179
+ if (named && done.status === "rejected")
180
+ return invalid("this finding was already rejected");
181
+ items.push(done);
182
+ continue;
183
+ }
184
+ const fingerprint = options.fingerprintOf(finding);
185
+ const prior = previous(options.account, fingerprint, options.batch);
186
+ if (prior) {
187
+ if (named && prior.status === "rejected")
188
+ return invalid("this unchanged finding was already rejected; changed evidence needs a new candidate");
189
+ items.push({ ...prior, id: finding.id, reused: true });
190
+ continue;
191
+ }
192
+ if (accepted.length && !named) {
193
+ pending.push(finding);
194
+ continue;
195
+ }
196
+ items.push({
197
+ id: finding.id,
198
+ fingerprint,
199
+ status: named ? "accepted" : "rejected",
200
+ reference: named ? options.make(finding) : null,
201
+ reused: false,
202
+ });
117
203
  }
118
- const status = accepted.includes(finding.id) ? "accepted" : "rejected";
119
- return {
120
- id: finding.id,
121
- fingerprint,
122
- status,
123
- reference: status === "accepted" ? create(finding, agent, decidedBy) : null,
124
- reused: false,
125
- };
126
- });
127
- return { snapshot, snapshotParts, previous, outcomes, create };
204
+ return { items, pending };
205
+ };
206
+ /** A partly reviewed batch keeps waiting: its payload carries what was decided and who was named so far. */
207
+ const keepWaiting = (id, payload) => database
208
+ .prepare("UPDATE proposed_actions SET payload=?, updated_at=? WHERE id=? AND status='proposed'")
209
+ .run(JSON.stringify(payload), context.now(), Number(id));
210
+ /** The receipt's `accepted`: every finding a review of this batch named, sorted. */
211
+ const named = (earlier, now) => [...new Set([...(earlier ?? []), ...now])].sort();
212
+ /** A review of a batch already closed is answered again only when it asks for nothing new. */
213
+ const sameDecision = (receipt, accepted) => accepted.length ? accepted.every((one) => receipt.accepted.includes(one)) : receipt.accepted.length === 0;
214
+ return { snapshot, snapshotParts, previous, settle, keepWaiting, named, sameDecision, create };
128
215
  };
@@ -30,6 +30,10 @@ export interface ContactFilter {
30
30
  query?: string;
31
31
  /** Three characters or more of one of the owner's private notes about them, anywhere, in any letter case. */
32
32
  notes?: string;
33
+ /** A part of their address, in any letter case. */
34
+ email?: string;
35
+ /** A part of their phone, digits only compared. */
36
+ phone?: string;
33
37
  }
34
38
  export declare const contacts: ({ orm }: StoreContext, accountKey: number, key: AccountKey, { order, limit, offset, ...filter }: {
35
39
  order: "recent" | "name";
@@ -227,9 +227,16 @@ export const people = ({ orm, database }, provider, { account, accounts: native
227
227
  const byId = new Map(everyone.map((person) => [person.id, person]));
228
228
  return { provider, get: (id) => byId.get(id), all: () => everyone };
229
229
  };
230
- const contactsWhere = (accountKey, key, { query, notes }) => {
230
+ const DIGITS = (column) => `replace(replace(replace(replace(replace(coalesce(${column}, ''), '+', ''), ' ', ''), '-', ''), '(', ''), ')', '')`;
231
+ const contactsWhere = (accountKey, key, { query, notes, email, phone }) => {
232
+ const digits = phone?.replace(/\D/gu, "");
233
+ if (phone !== undefined && !digits)
234
+ throw new CliError("validation_error", `phone: takes digits, got "${phone}" — e.g. phone:+34 or phone:600`, {
235
+ reason: "query.unknown-value",
236
+ });
231
237
  if (query !== undefined && query.trim().length < 3) {
232
- throw new CliError("validation_error", `a contact search takes at least 3 characters, got "${query}"`);
238
+ throw new CliError("validation_error", `a contact search takes at least 3 characters, got "${query}" — write more of the name, or leave it out ` +
239
+ "and read the list by name (--order name)", { reason: "query.short-text" });
233
240
  }
234
241
  const noted = notes === undefined ? undefined : holdingText("note", "n.id", notes);
235
242
  return and(eq(accountIdentities.accountId, accountKey), ne(identities.externalId, key.account), sql `EXISTS (SELECT 1 FROM ${chatMembers} JOIN ${chats} ON ${chats.id} = ${chatMembers.chatId}
@@ -238,7 +245,9 @@ const contactsWhere = (accountKey, key, { query, notes }) => {
238
245
  ? undefined
239
246
  : sql `(${identities.id} IN (SELECT rowid FROM identities_fts WHERE identities_fts MATCH ${`"${query.trim().replaceAll('"', '""')}"`}) OR EXISTS (SELECT 1 FROM aliases ca WHERE ca.aliasable_type='identity' AND ca.display=1 AND ca.account_id=${accountKey} AND ca.aliasable_id=${identities.id} AND instr(ca.name_folded, ${fold(query.trim())}) > 0))`, notes === undefined
240
247
  ? undefined
241
- : sql `EXISTS (SELECT 1 FROM notes n WHERE n.notable_type='identity' AND n.notable_id=${identities.id} AND n.deleted_at IS NULL${noted ? sql ` AND ${bound(noted)}` : sql ``})`);
248
+ : sql `EXISTS (SELECT 1 FROM notes n WHERE n.notable_type='identity' AND n.notable_id=${identities.id} AND n.deleted_at IS NULL${noted ? sql ` AND ${bound(noted)}` : sql ``})`, email === undefined
249
+ ? undefined
250
+ : sql `instr(lower(coalesce(${identities.email}, '')), ${email.trim().toLowerCase()}) > 0`, digits === undefined ? undefined : sql `instr(${sql.raw(DIGITS("identities.phone"))}, ${digits}) > 0`);
242
251
  };
243
252
  export const contacts = ({ orm }, accountKey, key, { order, limit, offset = 0, ...filter }) => {
244
253
  const byName = [
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { isEmailAddress, isNoReplyAddress } from "../../domain/addresses.js";
2
3
  import { FREE_MAIL } from "../../mail/score.js";
3
4
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
4
5
  import { IDENTITY_LINK_KIND, } from "../identity-links.js";
@@ -160,6 +161,31 @@ const settleMentions = ({ database, now }, payload, to) => {
160
161
  };
161
162
  const organizationExists = ({ database }, id) => Number.isSafeInteger(id) &&
162
163
  database.prepare("SELECT 1 FROM organizations WHERE id = ? AND deleted_at IS NULL").get(id) !== undefined;
164
+ /** The addresses the match's two people hold now, a free mailbox's and a no-reply one left out. */
165
+ const addressesOfPair = ({ database }, payload) => {
166
+ const persons = payload.persons.map((uid) => currentPerson(database, Number(uid)));
167
+ const rows = database
168
+ .prepare("SELECT DISTINCT lower(trim(coalesce(i.email, CASE WHEN i.provider = 'email' THEN i.external_id END))) AS address " +
169
+ "FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id IN (?, ?) ORDER BY 1")
170
+ .all(...persons);
171
+ return rows
172
+ .map(({ address }) => (typeof address === "string" ? address : ""))
173
+ .filter((address) => isEmailAddress(address) && !isNoReplyAddress(address))
174
+ .filter((address) => !FREE_MAIL.has(address.split("@")[1] ?? ""));
175
+ };
176
+ /**
177
+ * A match found another way, by name say, says nothing of which address is the company's, or whether any is: only an
178
+ * address the owner names, one the two people hold at a company's domain, is taken.
179
+ */
180
+ const companyAddressOf = (context, id, payload, asked) => {
181
+ const held = addressesOfPair(context, payload);
182
+ if (asked !== undefined && held.includes(asked))
183
+ return asked;
184
+ const choices = held.length > 0 ? `: ${held.join(", ")}` : "; neither holds an address at a company's domain";
185
+ throw new CliError("validation_error", asked === undefined
186
+ ? `${id} is not about a shared mailbox; name which of the two people's addresses is the company's${choices}`
187
+ : `${asked} is not an address of these two people at a company's domain${choices}`, { reason: "identity.not-shared", candidates: held });
188
+ };
163
189
  /**
164
190
  * NEED-2528: the shared mailbox is a company's, not one of the two people. The address goes to the organization and
165
191
  * the proposal is turned down, so the pair is not proposed again on it (the rejected evidence), and nobody is joined.
@@ -170,11 +196,15 @@ const toCompany = (context, proposal, company, author, noted) => {
170
196
  throw new CliError("validation_error", `${proposal.id} is already ${proposal.status}`, {
171
197
  reason: "proposal.wrong-state",
172
198
  });
173
- const address = payload.mailbox;
174
- if (payload.shared === undefined || address === undefined)
175
- throw new CliError("validation_error", `${proposal.id} is not about a shared mailbox; confirm or reject it`, {
199
+ const asked = company.mailbox
200
+ ?.trim()
201
+ .toLowerCase()
202
+ .replace(/^email:/u, "");
203
+ if (payload.mailbox !== undefined && asked !== undefined && asked !== payload.mailbox)
204
+ throw new CliError("validation_error", `${proposal.id} is about the shared mailbox ${payload.mailbox}, not ${asked}`, {
176
205
  reason: "identity.not-shared",
177
206
  });
207
+ const address = payload.mailbox ?? companyAddressOf(context, proposal.id, payload, asked);
178
208
  const name = company.name?.trim() || undefined;
179
209
  const domain = address.split("@")[1] ?? "";
180
210
  let organization;
@@ -205,7 +235,7 @@ const toCompany = (context, proposal, company, author, noted) => {
205
235
  .all(IDENTITY_LINK_KIND, Number(proposal.id), address)
206
236
  .map((row) => String(row.id))
207
237
  : [];
208
- const result = { dismissed: true, organization: `organization:${organization}`, ...noted };
238
+ const result = { dismissed: true, organization: `organization:${organization}`, mailbox: address, ...noted };
209
239
  for (const other of others) {
210
240
  const closed = operations.reject(other, author, { ...result, with: proposal.id });
211
241
  settleMentions(context, closed.payload, "found");
@@ -85,6 +85,8 @@ type FieldCompiler = (node: ResolvedPredicate, scope: FieldScope) => Compiled;
85
85
  export declare const stemMatch: (stemmer: Stemmer, node: ResolvedPredicate) => string | undefined;
86
86
  /** What `kind:` matches for a chat aliased `c`: private, saved, bot, service, group, channel or unknown. */
87
87
  export declare const PEER_KIND = "CASE WHEN json_extract(c.metadata,'$.peerKind') IN ('private','saved','bot','service','group','channel','unknown') THEN json_extract(c.metadata,'$.peerKind') WHEN c.kind='dialog' AND json_extract(c.metadata,'$.isBot')=1 THEN 'bot' WHEN c.kind='dialog' THEN 'private' ELSE c.kind END";
88
+ /** `field:*` of a field in `PRESENCE`: the message or mail has a value there. */
89
+ export declare const present: FieldCompiler;
88
90
  /** One compiler per field of `QUERY_FIELDS`, by its name: a leaf compiles by a lookup, never a branch. */
89
91
  export declare const FIELD_COMPILERS: Readonly<Record<string, FieldCompiler>>;
90
92
  export {};