@wirecat/cli-core 0.642.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 (258) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/dist/attachments/ocr.js +27 -18
  3. package/dist/attachments/picture-reading.d.ts +51 -0
  4. package/dist/attachments/picture-reading.js +207 -0
  5. package/dist/background/backfill.d.ts +4 -2
  6. package/dist/background/backfill.js +3 -3
  7. package/dist/background/schedules.d.ts +23 -1
  8. package/dist/background/schedules.js +45 -17
  9. package/dist/background/units.d.ts +2 -0
  10. package/dist/background/units.js +8 -9
  11. package/dist/calendar/cli/index.js +10 -2
  12. package/dist/calendar/feeds.js +2 -2
  13. package/dist/calendar/server-search.js +2 -2
  14. package/dist/calendar/source.d.ts +4 -3
  15. package/dist/calendar/sync.js +12 -10
  16. package/dist/calendar/testing/source-contract.js +5 -4
  17. package/dist/calendar/testing/source.js +3 -2
  18. package/dist/cli/complete-command.d.ts +23 -0
  19. package/dist/cli/complete-command.js +80 -0
  20. package/dist/cli/context.js +7 -1
  21. package/dist/cli/effects.d.ts +2 -0
  22. package/dist/cli/effects.js +2 -0
  23. package/dist/cli/envelope.js +6 -1
  24. package/dist/cli/help/first-screen.js +5 -0
  25. package/dist/cli/index.d.ts +4 -2
  26. package/dist/cli/index.js +2 -1
  27. package/dist/cli/list-query.d.ts +3 -1
  28. package/dist/cli/list-query.js +5 -3
  29. package/dist/cli/local-only-command.js +9 -0
  30. package/dist/cli/messenger/backfill-command.js +1 -1
  31. package/dist/cli/messenger/chat-queries.js +2 -1
  32. package/dist/cli/messenger/complete-command.d.ts +4 -7
  33. package/dist/cli/messenger/complete-command.js +31 -98
  34. package/dist/cli/messenger/contacts-command.js +4 -0
  35. package/dist/cli/messenger/guard-commands.js +1 -1
  36. package/dist/cli/messenger/images-command.js +32 -0
  37. package/dist/cli/messenger/list-result-queries.d.ts +1 -0
  38. package/dist/cli/messenger/list-result-queries.js +2 -1
  39. package/dist/cli/messenger/mentions-command.js +3 -3
  40. package/dist/cli/messenger/message-items.js +1 -0
  41. package/dist/cli/messenger/messages-command.js +7 -6
  42. package/dist/cli/messenger/people-queries.d.ts +2 -2
  43. package/dist/cli/messenger/people-queries.js +4 -4
  44. package/dist/cli/messenger/search-answers.js +2 -2
  45. package/dist/cli/messenger/search-command.js +3 -3
  46. package/dist/cli/messenger/searches-command.js +1 -1
  47. package/dist/cli/messenger/store-maintenance-command.js +4 -0
  48. package/dist/cli/messenger/tasks-analysis-command.js +1 -1
  49. package/dist/cli/messenger/tasks-command.js +2 -2
  50. package/dist/cli/model-catalogue-command.js +2 -0
  51. package/dist/cli/picture-reading-command.d.ts +12 -0
  52. package/dist/cli/picture-reading-command.js +82 -0
  53. package/dist/cli/program.d.ts +6 -0
  54. package/dist/cli/program.js +28 -2
  55. package/dist/cli/schedule/agent-start.d.ts +23 -0
  56. package/dist/cli/schedule/agent-start.js +115 -0
  57. package/dist/cli/schedule/harnesses.d.ts +203 -0
  58. package/dist/cli/schedule/harnesses.js +278 -0
  59. package/dist/cli/schedule/schedule-command.d.ts +9 -5
  60. package/dist/cli/schedule/schedule-command.js +89 -79
  61. package/dist/cli/shared-command-exports.d.ts +186 -0
  62. package/dist/cli/shared-command-exports.js +2 -0
  63. package/dist/cli/untrusted-marks.d.ts +25 -0
  64. package/dist/cli/untrusted-marks.js +102 -0
  65. package/dist/crm/cli/index.d.ts +1 -0
  66. package/dist/crm/cli/index.js +6 -5
  67. package/dist/crm/cli/store.d.ts +30 -0
  68. package/dist/crm/cli/store.js +63 -0
  69. package/dist/crm/source.d.ts +6 -4
  70. package/dist/crm/sync.js +10 -6
  71. package/dist/crm/testing/source-contract.js +9 -7
  72. package/dist/crm/testing/source.js +6 -2
  73. package/dist/crm/testing/sync-contract.js +4 -4
  74. package/dist/crm/writes.d.ts +5 -2
  75. package/dist/crm/writes.js +1 -1
  76. package/dist/documents.d.ts +1 -0
  77. package/dist/documents.js +1 -0
  78. package/dist/domain/addresses.d.ts +2 -0
  79. package/dist/domain/addresses.js +7 -0
  80. package/dist/domain/attachments.d.ts +2 -0
  81. package/dist/domain/attachments.js +2 -1
  82. package/dist/domain/models.d.ts +2 -0
  83. package/dist/entities/attachment-results.d.ts +3 -0
  84. package/dist/entities/attachment-results.js +3 -0
  85. package/dist/entities/attachment.d.ts +2 -0
  86. package/dist/entities/attachment.js +8 -1
  87. package/dist/entities/hit.d.ts +1 -0
  88. package/dist/entities/index.d.ts +21 -4
  89. package/dist/entities/index.js +3 -2
  90. package/dist/entities/list-results.d.ts +33 -5
  91. package/dist/entities/list-results.js +33 -5
  92. package/dist/errors/reasons.js +30 -1
  93. package/dist/mail/cli/index.js +7 -6
  94. package/dist/mcp/agent.d.ts +2 -1
  95. package/dist/mcp/agent.js +5 -0
  96. package/dist/mcp/app-server.js +10 -0
  97. package/dist/mcp/surface.d.ts +7 -2
  98. package/dist/mcp/surface.js +49 -10
  99. package/dist/meetings/cli/index.js +6 -1
  100. package/dist/meetings/mcp/index.d.ts +15 -15
  101. package/dist/meetings/mcp/index.js +6 -3
  102. package/dist/meetings/participant-search.d.ts +2 -2
  103. package/dist/meetings/project-discovery.d.ts +1 -1
  104. package/dist/meetings/project-evidence-answer.js +2 -2
  105. package/dist/meetings/reads.d.ts +2 -2
  106. package/dist/meetings/reads.js +6 -6
  107. package/dist/meetings/store.d.ts +2 -1
  108. package/dist/meetings/testing/contract.js +6 -6
  109. package/dist/meetings/testing/memory.js +7 -2
  110. package/dist/models/ai.d.ts +1 -1
  111. package/dist/models/ai.js +3 -1
  112. package/dist/models/anthropic.js +15 -9
  113. package/dist/models/index.js +5 -3
  114. package/dist/models/openai.js +24 -11
  115. package/dist/models/types.d.ts +8 -0
  116. package/dist/models/types.js +11 -1
  117. package/dist/ports/app.d.ts +17 -1
  118. package/dist/ports/app.js +63 -3
  119. package/dist/search/lucene/plain.js +45 -3
  120. package/dist/search/lucene/registry.d.ts +15 -4
  121. package/dist/search/lucene/registry.js +70 -12
  122. package/dist/search/lucene/types.d.ts +2 -0
  123. package/dist/search/lucene/types.js +12 -0
  124. package/dist/sends/upload.d.ts +8 -1
  125. package/dist/sends/upload.js +35 -14
  126. package/dist/services/account-groups.d.ts +11 -0
  127. package/dist/services/account-groups.js +29 -0
  128. package/dist/services/agenda.js +1 -0
  129. package/dist/services/attachments.d.ts +18 -4
  130. package/dist/services/attachments.js +66 -15
  131. package/dist/services/conversations.d.ts +2 -4
  132. package/dist/services/conversations.js +1 -1
  133. package/dist/services/deal-context.js +5 -5
  134. package/dist/services/documents/ingestion.js +3 -3
  135. package/dist/services/documents/knowledge.d.ts +6 -6
  136. package/dist/services/documents/knowledge.js +1 -2
  137. package/dist/services/events-search.d.ts +3 -3
  138. package/dist/services/events-search.js +7 -7
  139. package/dist/services/index.d.ts +1 -1
  140. package/dist/services/index.js +1 -1
  141. package/dist/services/meeting-project-discovery.js +1 -1
  142. package/dist/services/message-resolution.js +10 -3
  143. package/dist/services/messages-search.js +6 -4
  144. package/dist/services/metadata.d.ts +1 -1
  145. package/dist/services/notes-search.d.ts +3 -3
  146. package/dist/services/notes-search.js +3 -3
  147. package/dist/services/organization-context.js +12 -9
  148. package/dist/services/people.d.ts +2 -0
  149. package/dist/services/people.js +4 -2
  150. package/dist/services/pictures.d.ts +9 -0
  151. package/dist/services/pictures.js +34 -28
  152. package/dist/services/project-status/index.js +1 -1
  153. package/dist/services/project-status/signals/payments.js +4 -2
  154. package/dist/services/project-status/signals/promises.js +5 -2
  155. package/dist/services/proposals/kinds/action.js +1 -1
  156. package/dist/services/proposals/kinds/fact.js +1 -1
  157. package/dist/services/proposals/kinds/findings.d.ts +2 -1
  158. package/dist/services/proposals/kinds/findings.js +12 -5
  159. package/dist/services/proposals/kinds/identity-link.js +1 -1
  160. package/dist/services/proposals/kinds/identity-split.js +1 -1
  161. package/dist/services/proposals/kinds/key-document.js +1 -1
  162. package/dist/services/proposals/kinds/mail-findings.d.ts +1 -1
  163. package/dist/services/proposals/kinds/mail-findings.js +11 -5
  164. package/dist/services/proposals/kinds/meeting-findings.js +10 -4
  165. package/dist/services/proposals/kinds/memory.js +1 -1
  166. package/dist/services/proposals/kinds/organization.js +1 -1
  167. package/dist/services/proposals/kinds/relationship-update.js +1 -1
  168. package/dist/services/proposals/kinds/relationship.js +1 -1
  169. package/dist/services/proposals/kinds/shared.d.ts +3 -2
  170. package/dist/services/proposals/kinds/shared.js +4 -4
  171. package/dist/services/proposals/kinds/source-review.js +1 -1
  172. package/dist/services/proposals/kinds/task-close.js +2 -2
  173. package/dist/services/proposals/registry.js +1 -1
  174. package/dist/services/proposals/types.d.ts +2 -1
  175. package/dist/services/search-all-business.js +3 -4
  176. package/dist/services/search-all.js +13 -14
  177. package/dist/services/searches.d.ts +2 -4
  178. package/dist/services/searches.js +1 -4
  179. package/dist/services/stored-project-gathering.js +6 -1
  180. package/dist/services/tags.d.ts +2 -4
  181. package/dist/services/tags.js +1 -1
  182. package/dist/services/tasks.d.ts +1 -1
  183. package/dist/services/tasks.js +4 -3
  184. package/dist/store/account-store.d.ts +2 -1
  185. package/dist/store/account-store.js +3 -1
  186. package/dist/store/accounts.d.ts +2 -0
  187. package/dist/store/accounts.js +8 -0
  188. package/dist/store/chats.d.ts +5 -0
  189. package/dist/store/chats.js +4 -0
  190. package/dist/store/evidence-findings.d.ts +9 -0
  191. package/dist/store/exports.d.ts +1 -1
  192. package/dist/store/exports.js +1 -1
  193. package/dist/store/identity-links.d.ts +3 -1
  194. package/dist/store/mail-findings.d.ts +9 -0
  195. package/dist/store/meeting-findings.d.ts +9 -0
  196. package/dist/store/searches.d.ts +3 -2
  197. package/dist/store/sqlite/accounts.js +37 -0
  198. package/dist/store/sqlite/agent-actions.d.ts +2 -1
  199. package/dist/store/sqlite/agent-actions.js +10 -4
  200. package/dist/store/sqlite/business-contracts.d.ts +3 -1
  201. package/dist/store/sqlite/business-contracts.js +7 -3
  202. package/dist/store/sqlite/business-search.d.ts +2 -1
  203. package/dist/store/sqlite/business-search.js +6 -4
  204. package/dist/store/sqlite/deals.d.ts +6 -4
  205. package/dist/store/sqlite/deals.js +12 -7
  206. package/dist/store/sqlite/evidence-findings.js +78 -9
  207. package/dist/store/sqlite/facts.d.ts +2 -1
  208. package/dist/store/sqlite/facts.js +6 -2
  209. package/dist/store/sqlite/finance.d.ts +4 -2
  210. package/dist/store/sqlite/finance.js +13 -6
  211. package/dist/store/sqlite/findings-core.d.ts +56 -2
  212. package/dist/store/sqlite/findings-core.js +109 -22
  213. package/dist/store/sqlite/identities.d.ts +4 -0
  214. package/dist/store/sqlite/identities.js +12 -3
  215. package/dist/store/sqlite/identity-proposals.js +34 -4
  216. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  217. package/dist/store/sqlite/lucene-fields.js +28 -2
  218. package/dist/store/sqlite/lucene.js +21 -10
  219. package/dist/store/sqlite/mail-findings.js +60 -22
  220. package/dist/store/sqlite/meeting-findings.js +53 -7
  221. package/dist/store/sqlite/meeting-participant-search.js +4 -5
  222. package/dist/store/sqlite/meetings.js +7 -3
  223. package/dist/store/sqlite/memories.d.ts +4 -2
  224. package/dist/store/sqlite/memories.js +13 -6
  225. package/dist/store/sqlite/money-transactions.d.ts +3 -1
  226. package/dist/store/sqlite/money-transactions.js +7 -3
  227. package/dist/store/sqlite/name-traces.d.ts +3 -3
  228. package/dist/store/sqlite/name-traces.js +29 -2
  229. package/dist/store/sqlite/orders.d.ts +3 -1
  230. package/dist/store/sqlite/orders.js +5 -2
  231. package/dist/store/sqlite/people-list.js +67 -22
  232. package/dist/store/sqlite/person-match-scan.d.ts +3 -1
  233. package/dist/store/sqlite/person-match-scan.js +97 -7
  234. package/dist/store/sqlite/products.d.ts +3 -1
  235. package/dist/store/sqlite/products.js +5 -2
  236. package/dist/store/sqlite/proposed-actions.d.ts +2 -1
  237. package/dist/store/sqlite/proposed-actions.js +7 -3
  238. package/dist/store/sqlite/query-filter.d.ts +4 -0
  239. package/dist/store/sqlite/query-filter.js +14 -0
  240. package/dist/store/sqlite/reads.d.ts +1 -0
  241. package/dist/store/sqlite/reads.js +14 -0
  242. package/dist/store/sqlite/records.d.ts +3 -1
  243. package/dist/store/sqlite/records.js +7 -5
  244. package/dist/store/sqlite/rows-page.d.ts +3 -0
  245. package/dist/store/sqlite/rows-page.js +4 -0
  246. package/dist/store/sqlite/searches.d.ts +2 -1
  247. package/dist/store/sqlite/searches.js +3 -1
  248. package/dist/store/sqlite/subscriptions.d.ts +5 -2
  249. package/dist/store/sqlite/subscriptions.js +13 -6
  250. package/dist/store/sqlite/task-board.js +27 -0
  251. package/dist/store/sqlite/task-find.d.ts +15 -0
  252. package/dist/store/sqlite/task-find.js +1 -0
  253. package/dist/store/sqlite/wallets.d.ts +3 -1
  254. package/dist/store/sqlite/wallets.js +7 -3
  255. package/dist/store/sqlite/work-tasks.d.ts +3 -11
  256. package/dist/store/sqlite/work-tasks.js +8 -4
  257. package/package.json +2 -2
  258. package/parity.json +24 -0
@@ -478,7 +478,7 @@ const recipient = (node, { mail }) => {
478
478
  : bound("0"));
479
479
  };
480
480
  // What a page says about itself, and whether a note is written or a file, exist for notes only.
481
- const notesOnly = () => always(bound("0"));
481
+ const notesOnly = (node) => searchError("query.unsupported-field", node.span, `${node.field}: is a notes field — search notes reads it${node.field === "author" ? "; who wrote a message is from:" : ""}`);
482
482
  const mailbox = (node, scope) => {
483
483
  const { value, operator } = node;
484
484
  if (!scope.mail)
@@ -546,6 +546,32 @@ const subject = (node, scope) => {
546
546
  };
547
547
  };
548
548
  const headingOf = (text) => normalize(text.slice(0, Math.max(0, text.indexOf("\n\n"))));
549
+ // One concept, one name: a message's title is its chat's, a mail's is its subject.
550
+ const title = (node, scope) => {
551
+ if (scope.mail)
552
+ return subject(node, scope);
553
+ const wanted = fold(node.value);
554
+ const parts = node.operator === "phrase" ? [wanted] : (wanted.match(/[\p{L}\p{N}]+/gu) ?? []);
555
+ if (!parts.length)
556
+ return always(bound("0"));
557
+ return always(combine(parts.map((part) => bound("instr(c.title_folded, ?) > 0", part)), "AND"));
558
+ };
559
+ const SUBJECT_PRESENT = "substr(m.text, 1, 2) <> char(10, 10)";
560
+ /** `field:*` of a field in `PRESENCE`: the message or mail has a value there. */
561
+ export const present = (node, scope) => {
562
+ const { field } = node;
563
+ if (field === "topic")
564
+ return messengerOnly(() => always(bound("m.thread_external_id IS NOT NULL")))(node, scope);
565
+ if (field === "participants_count")
566
+ return messengerOnly(() => always(bound("c.participants_count IS NOT NULL")))(node, scope);
567
+ if (field === "from")
568
+ return always(bound("m.sender_identity_id IS NOT NULL"));
569
+ if (!scope.mail)
570
+ return always(bound(field === "title" ? "coalesce(c.title, '') <> ''" : "0"));
571
+ if (field === "title" || field === "subject")
572
+ return always(bound(SUBJECT_PRESENT));
573
+ return always(bound("m.id IN (SELECT r.email_id FROM email_recipients r WHERE r.role = ?)", field));
574
+ };
549
575
  /** One compiler per field of `QUERY_FIELDS`, by its name: a leaf compiles by a lookup, never a branch. */
550
576
  export const FIELD_COMPILERS = {
551
577
  text: words,
@@ -576,7 +602,7 @@ export const FIELD_COMPILERS = {
576
602
  to: recipient,
577
603
  cc: recipient,
578
604
  bcc: recipient,
579
- title: notesOnly,
605
+ title,
580
606
  site: notesOnly,
581
607
  lang: notesOnly,
582
608
  author: notesOnly,
@@ -1,11 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { compileAutomaton } from "../../search/lucene/automaton.js";
3
+ import { isPresence, PRESENCE } from "../../search/lucene/registry.js";
3
4
  import { isStemmed } from "../../search/lucene/resolved.js";
4
- import { exhausted, outOfTime, QUERY_LIMITS, searchError } from "../../search/lucene/types.js";
5
+ import { exhausted, outOfTime, QUERY_LIMITS, searchError, tooWideTerm } from "../../search/lucene/types.js";
5
6
  import { TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js";
6
7
  import { emailHitsByPk } from "./emails.js";
7
8
  import { placeHits } from "./hit-places.js";
8
- import { combine, FIELD_COMPILERS, ftsMatch, quoted, SPEECH, } from "./lucene-fields.js";
9
+ import { combine, FIELD_COMPILERS, ftsMatch, present, quoted, SPEECH, } from "./lucene-fields.js";
9
10
  import { GROUPS } from "./lucene-groups.js";
10
11
  import { hitsByPk } from "./search.js";
11
12
  import { read } from "./transaction.js";
@@ -146,7 +147,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
146
147
  },
147
148
  };
148
149
  const createLeaf = (node) => {
149
- const compiler = FIELD_COMPILERS[node.field];
150
+ const compiler = isPresence(node) && PRESENCE.has(node.field) ? present : FIELD_COMPILERS[node.field];
150
151
  if (!compiler)
151
152
  return searchError("query.unsupported-field", node.span);
152
153
  const compiled = compiler(node, fields);
@@ -409,6 +410,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
409
410
  evaluate,
410
411
  };
411
412
  };
413
+ const testedTerms = (leaves) => leaves.flatMap(({ node, test }) => (test ? [node.value] : []));
412
414
  /** The matcher and its consumer run synchronously in one read snapshot; exact keys stay in SQL. */
413
415
  export const withQuerySelection = (context, execution, consume) => {
414
416
  const { database } = context;
@@ -429,9 +431,9 @@ export const withQuerySelection = (context, execution, consume) => {
429
431
  .all(...ranked.params, ...where.params, QUERY_LIMITS.candidates + 1);
430
432
  check();
431
433
  if (candidates.length > QUERY_LIMITS.candidates)
432
- exhausted("candidate rows");
434
+ tooWideTerm(testedTerms(leaves), "candidate rows");
433
435
  if (candidates.reduce((sum, row) => sum + Number(row.bytes), 0) > QUERY_LIMITS.bodyBytes)
434
- exhausted("body bytes");
436
+ tooWideTerm(testedTerms(leaves), "body bytes");
435
437
  const matched = [];
436
438
  for (let offset = 0; offset < candidates.length; offset += 500) {
437
439
  check();
@@ -527,10 +529,13 @@ const runCompiled = async (context, execution, by) => {
527
529
  .all(...ranked.params, ...where.params, QUERY_LIMITS.candidates + 1);
528
530
  await new Promise((resolve) => setImmediate(resolve));
529
531
  check();
530
- if (candidates.length > QUERY_LIMITS.candidates)
531
- exhausted("candidate rows");
532
- if (candidates.reduce((sum, row) => sum + Number(row.bytes), 0) > QUERY_LIMITS.bodyBytes)
533
- exhausted("body bytes");
532
+ // A page stops at its last hit, so only what it reads counts; a count or a group reads every candidate.
533
+ const tooWide = (budget) => tooWideTerm(testedTerms(leaves), budget);
534
+ if (by && candidates.length > QUERY_LIMITS.candidates)
535
+ tooWide("candidate rows");
536
+ if (by && candidates.reduce((sum, row) => sum + Number(row.bytes), 0) > QUERY_LIMITS.bodyBytes)
537
+ tooWide("body bytes");
538
+ let bytesRead = 0;
534
539
  const found = [];
535
540
  const scores = new Map(candidates.map((row) => [Number(row.id), row.relevance == null ? null : -Number(row.relevance)]));
536
541
  const exactness = new Map(candidates.map((row) => [Number(row.id), Number(row.exact) === 1]));
@@ -538,7 +543,11 @@ const runCompiled = async (context, execution, by) => {
538
543
  if (offset > 0)
539
544
  await new Promise((resolve) => setImmediate(resolve));
540
545
  check();
541
- const pks = candidates.slice(offset, offset + 500).map(({ id }) => Number(id));
546
+ const chunk = candidates.slice(offset, offset + 500);
547
+ bytesRead += chunk.reduce((sum, row) => sum + Number(row.bytes), 0);
548
+ if (bytesRead > QUERY_LIMITS.bodyBytes)
549
+ tooWide("body bytes");
550
+ const pks = chunk.map(({ id }) => Number(id));
542
551
  const rows = database
543
552
  .prepare(`SELECT m.id AS id,m.text AS body${projection ? `,${projection}` : ""},(SELECT json_group_array(att.kind) FROM attachments att WHERE att.attachable_type='${corpus.item}' AND att.attachable_id=m.id) AS attachment_kinds ${joinedFrom} WHERE m.id IN (${pks.map(() => "?").join(",")})`)
544
553
  .all(...projectionParams, ...pks);
@@ -555,6 +564,8 @@ const runCompiled = async (context, execution, by) => {
555
564
  if (!by && found.length > execution.limit)
556
565
  break;
557
566
  }
567
+ if (found.length <= execution.limit && candidates.length > QUERY_LIMITS.candidates)
568
+ tooWide("candidate rows");
558
569
  if (by === "pks")
559
570
  return found;
560
571
  if (by)
@@ -8,7 +8,7 @@ import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
8
8
  import { fold } from "../normalize.js";
9
9
  import { organizationOfAddress } from "./address-organization.js";
10
10
  import { financeOperationsOver } from "./finance.js";
11
- import { findingsAgent, findingsCoreOver } from "./findings-core.js";
11
+ import { editedFinding, findingsAgent, findingsCoreOver, findingToEdit, pendingOf } from "./findings-core.js";
12
12
  import { authorActor, linkEvidence, memoriesStoreOver } from "./memories.js";
13
13
  import { insertLink, requiredThing } from "./notes.js";
14
14
  import { orderOfShop, orderOperationsOver } from "./orders.js";
@@ -19,6 +19,22 @@ import { inboxProject } from "./tasks.js";
19
19
  import { taskRowOf } from "./things.js";
20
20
  import { write } from "./transaction.js";
21
21
  import { workTaskOperationsOver } from "./work-tasks.js";
22
+ /**
23
+ * What the owner may change in a mail finding before deciding it: its words, and the fields that only say what the
24
+ * agent read. Money, orders and the identities a link or contact names keep what the mail said; evidence never changes.
25
+ */
26
+ const MAIL_EDITS = {
27
+ task: ["title", "type", "reason", "commitment", "project", "dueAt", "dueEvidence", "assignee", "assigneeEvidence"],
28
+ fact: ["statement", "type", "reason", "subject", "project"],
29
+ memory: ["body", "memoryKind", "scope", "reason", "subject", "project"],
30
+ task_update: ["reason", "detail", "dueAt"],
31
+ link: ["reason"],
32
+ new_contact: ["name", "reason"],
33
+ invoice: ["reason"],
34
+ payment: ["reason"],
35
+ order: ["reason"],
36
+ order_update: ["reason"],
37
+ };
22
38
  const stale = () => {
23
39
  throw new CliError("validation_error", "mail findings cite mail that changed since it was read; stage a new batch", {
24
40
  reason: "mail-findings.stale",
@@ -82,10 +98,12 @@ export const mailFindingsStoreOver = (context) => {
82
98
  decidedAt: proposal.decidedAt,
83
99
  previous: proposal.result
84
100
  ? proposal.result.items
85
- : input.findings.flatMap((finding) => {
86
- const held = core.previous(accountOf(proposal), mailFindingFingerprint(finding));
101
+ : pendingOf(input, input.decided).findings.flatMap((finding) => {
102
+ const held = core.previous(accountOf(proposal), mailFindingFingerprint(finding), proposal.id);
87
103
  return held ? [{ ...held, id: finding.id, reused: true }] : [];
88
104
  }),
105
+ decided: proposal.result ? [] : (input.decided ?? []),
106
+ edited: input.edited ?? [],
89
107
  receipt: proposal.result,
90
108
  };
91
109
  };
@@ -498,7 +516,7 @@ export const mailFindingsStoreOver = (context) => {
498
516
  assertMayDecide({ id, kind: MAIL_FINDINGS_KIND, proposedBy: proposals.proposer(id) }, decision.by, context.decisions);
499
517
  const accepted = [...decision.accept].sort();
500
518
  if (batch.receipt) {
501
- if (JSON.stringify(batch.receipt.accepted) !== JSON.stringify(accepted))
519
+ if (!core.sameDecision(batch.receipt, accepted))
502
520
  return invalid("this findings batch was already reviewed with a different decision");
503
521
  return batch;
504
522
  }
@@ -506,7 +524,7 @@ export const mailFindingsStoreOver = (context) => {
506
524
  const account = accountOf(proposal);
507
525
  // Rejecting creates nothing, so a batch whose mail changed can still be closed; accepting needs the
508
526
  // accepted findings' own mail unchanged.
509
- const chosen = batch.input.findings.filter((finding) => accepted.includes(finding.id));
527
+ const chosen = pendingOf(batch.input, input.decided).findings.filter((finding) => accepted.includes(finding.id));
510
528
  if (chosen.length)
511
529
  cite(chosen, account, true);
512
530
  if (proposal.proposedBy.type !== "bot" || !proposal.proposedBy.name)
@@ -515,24 +533,44 @@ export const mailFindingsStoreOver = (context) => {
515
533
  bot: proposal.proposedBy.name,
516
534
  ...(input.agentModel === null ? {} : { model: input.agentModel }),
517
535
  };
518
- const items = batch.input.findings.map((finding) => {
519
- const fingerprint = mailFindingFingerprint(finding);
520
- const prior = core.previous(account, fingerprint);
521
- if (prior) {
522
- if (accepted.includes(finding.id) && prior.status === "rejected")
523
- return invalid("this unchanged finding was already rejected; changed evidence needs a new candidate");
524
- return { ...prior, id: finding.id, reused: true };
525
- }
526
- const status = accepted.includes(finding.id) ? "accepted" : "rejected";
527
- return {
528
- id: finding.id,
529
- fingerprint,
530
- status,
531
- reference: status === "accepted" ? create(finding, batch.account, agent) : null,
532
- reused: false,
533
- };
536
+ const { items, pending } = core.settle({
537
+ batch: id,
538
+ account,
539
+ findings: batch.input.findings,
540
+ decided: input.decided ?? [],
541
+ accepted,
542
+ fingerprintOf: mailFindingFingerprint,
543
+ make: (finding) => create(finding, batch.account, agent),
544
+ });
545
+ const named = core.named(input.accepted, accepted);
546
+ if (pending.length) {
547
+ core.keepWaiting(id, { ...input, decided: items, accepted: named });
548
+ return view(load(id));
549
+ }
550
+ return view(proposals.approve(id, { previewFingerprint: batch.fingerprint, accepted: named, items }, "owner"));
551
+ }),
552
+ edit: async (id, finding, changes, options) => write(database, () => {
553
+ const proposal = load(id);
554
+ const batch = view(proposal);
555
+ const original = findingToEdit(batch, finding, options, stale);
556
+ const input = proposal.payload;
557
+ const edited = editedFinding(original, changes, MAIL_EDITS, "mail finding");
558
+ const checked = validateMailFindings({
559
+ ...batch.input,
560
+ findings: batch.input.findings.map((one) => (one.id === finding ? edited : one)),
561
+ });
562
+ const now = checked.findings.find((one) => one.id === finding);
563
+ targets(now, cite([now], accountOf(proposal), true));
564
+ const fingerprints = checked.findings.map(mailFindingFingerprint);
565
+ if (new Set(fingerprints).size !== fingerprints.length)
566
+ return invalid("the edit makes two findings the same");
567
+ // The agent's inputHash stays: its rerun of the same key still finds this batch, now as the owner left it.
568
+ core.keepWaiting(id, {
569
+ ...input,
570
+ findings: checked.findings,
571
+ edited: [...new Set([...(input.edited ?? []), finding])],
534
572
  });
535
- return view(proposals.approve(id, { previewFingerprint: batch.fingerprint, accepted, items }, "owner"));
573
+ return view(load(id));
536
574
  }),
537
575
  };
538
576
  };
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { findingHash, MEETING_FINDINGS_KIND, meetingCueFingerprint, meetingFindingFingerprint, parseMeetingReference, validateMeetingFindings, } from "../../meetings/index.js";
3
3
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
4
- import { findingsCoreOver } from "./findings-core.js";
4
+ import { editedFinding, FINDING_EDITS, findingsCoreOver, findingToEdit, pendingOf } from "./findings-core.js";
5
5
  import { authorActor } from "./memories.js";
6
6
  import { proposalOperationsOver } from "./proposed-actions.js";
7
7
  import { write } from "./transaction.js";
@@ -57,10 +57,12 @@ export const meetingFindingsStoreOver = (context) => {
57
57
  decidedAt: proposal.decidedAt,
58
58
  previous: proposal.result
59
59
  ? proposal.result.items
60
- : input.findings.flatMap((finding) => {
61
- const held = previous(accountId(proposal.account), meetingFindingFingerprint(finding));
60
+ : pendingOf(input, input.decided).findings.flatMap((finding) => {
61
+ const held = previous(accountId(proposal.account), meetingFindingFingerprint(finding), proposal.id);
62
62
  return held ? [{ ...held, id: finding.id, reused: true }] : [];
63
63
  }),
64
+ decided: proposal.result ? [] : (input.decided ?? []),
65
+ edited: input.edited ?? [],
64
66
  receipt: proposal.result,
65
67
  };
66
68
  };
@@ -181,13 +183,13 @@ export const meetingFindingsStoreOver = (context) => {
181
183
  return invalid("a findings review names who decides: the owner or an agent");
182
184
  assertMayDecide({ id, kind: MEETING_FINDINGS_KIND, proposedBy: proposals.proposer(id) }, decision.by, context.decisions);
183
185
  if (batch.receipt) {
184
- if (JSON.stringify(batch.receipt.accepted) !== JSON.stringify(accepted))
186
+ if (!core.sameDecision(batch.receipt, accepted))
185
187
  return invalid("this findings batch was already reviewed with a different decision");
186
188
  return batch;
187
189
  }
188
190
  const input = proposal.payload;
189
191
  // Rejecting creates nothing, so a batch whose evidence changed can still be closed.
190
- if (accepted.length && snapshot(account, batch.input) !== input.snapshotHash)
192
+ if (accepted.length && snapshot(account, pendingOf(batch.input, input.decided)) !== input.snapshotHash)
191
193
  return stale();
192
194
  if (proposal.proposedBy.type !== "bot" || !proposal.proposedBy.name)
193
195
  return invalid("a findings author must be an agent");
@@ -195,8 +197,52 @@ export const meetingFindingsStoreOver = (context) => {
195
197
  bot: proposal.proposedBy.name,
196
198
  ...(input.agentModel === null ? {} : { model: input.agentModel }),
197
199
  };
198
- const items = core.outcomes(account, batch.input, accepted, agent, decision.by);
199
- return view(proposals.approve(id, { previewFingerprint: batch.fingerprint, accepted, items }, deciderAuthor(decision.by)));
200
+ const by = decision.by;
201
+ const { items, pending } = core.settle({
202
+ batch: id,
203
+ account,
204
+ findings: batch.input.findings,
205
+ decided: input.decided ?? [],
206
+ accepted,
207
+ fingerprintOf: meetingFindingFingerprint,
208
+ make: (finding) => core.create(finding, agent, by),
209
+ });
210
+ const named = core.named(input.accepted, accepted);
211
+ if (pending.length) {
212
+ core.keepWaiting(id, {
213
+ ...input,
214
+ decided: items,
215
+ accepted: named,
216
+ snapshotHash: snapshot(account, { ...batch.input, findings: pending }),
217
+ });
218
+ return view(load(account, id));
219
+ }
220
+ return view(proposals.approve(id, { previewFingerprint: batch.fingerprint, accepted: named, items }, deciderAuthor(by)));
221
+ }),
222
+ edit: async (key, id, finding, changes, options) => write(database, () => {
223
+ const account = accountId(key);
224
+ const proposal = load(account, id);
225
+ const batch = view(proposal);
226
+ const original = findingToEdit(batch, finding, options, stale);
227
+ const input = proposal.payload;
228
+ if (snapshot(account, pendingOf(batch.input, input.decided)) !== input.snapshotHash)
229
+ return stale();
230
+ const edited = editedFinding(original, changes, FINDING_EDITS, "meeting finding");
231
+ const checked = validateMeetingFindings({
232
+ ...batch.input,
233
+ findings: batch.input.findings.map((one) => (one.id === finding ? edited : one)),
234
+ });
235
+ const fingerprints = checked.findings.map(meetingFindingFingerprint);
236
+ if (new Set(fingerprints).size !== fingerprints.length)
237
+ return invalid("the edit makes two findings the same");
238
+ // The agent's inputHash stays: its rerun of the same key still finds this batch, now as the owner left it.
239
+ core.keepWaiting(id, {
240
+ ...input,
241
+ findings: checked.findings,
242
+ snapshotHash: snapshot(account, pendingOf(checked, input.decided)),
243
+ edited: [...new Set([...(input.edited ?? []), finding])],
244
+ });
245
+ return view(load(account, id));
200
246
  }),
201
247
  };
202
248
  };
@@ -55,8 +55,7 @@ export const meetingParticipantSearchOver = (context) => ({
55
55
  query: query.trim(),
56
56
  items: [],
57
57
  limit: limits.limit,
58
- has_more: false,
59
- next_cursor: null,
58
+ hasMore: false,
60
59
  ambiguity: { scope: "page", multiple_identities: false, identity_ids: [] },
61
60
  coverage: { scanned: 0, read_bytes: 0, archive_completeness: "unknown", truncated_by: null },
62
61
  };
@@ -92,9 +91,9 @@ export const meetingParticipantSearchOver = (context) => ({
92
91
  email,
93
92
  });
94
93
  }
95
- result.has_more = result.coverage.truncated_by !== null;
96
- if (result.has_more)
97
- result.next_cursor = Buffer.from(JSON.stringify({ version: 1, key, after, until })).toString("base64url");
94
+ result.hasMore = result.coverage.truncated_by !== null;
95
+ if (result.hasMore)
96
+ result.nextCursor = Buffer.from(JSON.stringify({ version: 1, key, after, until })).toString("base64url");
98
97
  result.ambiguity.identity_ids = [...new Set(result.items.map((item) => item.identity_id))];
99
98
  result.ambiguity.multiple_identities = result.ambiguity.identity_ids.length > 1;
100
99
  input.signal?.throwIfAborted();
@@ -506,10 +506,10 @@ export const wordsQuery = (query) => {
506
506
  return words.length ? words.map((word) => `"${word}"*`).join(" AND ") : null;
507
507
  };
508
508
  /** Pages over meetings, then lists their hits, as the reference store does. */
509
- const search = (database, query, filter) => {
509
+ const search = (database, query, filter = {}) => {
510
510
  const match = wordsQuery(query);
511
511
  if (match === null)
512
- return [];
512
+ return { items: [], hasMore: false };
513
513
  drainMeetingIndex(database);
514
514
  return read(database, () => {
515
515
  const picked = filtered(filter);
@@ -541,7 +541,10 @@ const search = (database, query, filter) => {
541
541
  legacyBudget(total);
542
542
  }
543
543
  const scopes = ["transcript", "chat", "summary"];
544
- return rows.map((row) => {
544
+ const [limit, offset] = page(filter);
545
+ const beyond = limit < 0 ? undefined : filtered({ ...filter, limit: 1, offset: offset + limit });
546
+ const hasMore = beyond !== undefined && database.prepare(`SELECT 1 FROM (${beyond.sql})`).get(...beyond.params) !== undefined;
547
+ const items = rows.map((row) => {
545
548
  const scope = scopes[Number(row.kind)];
546
549
  const cue = scope === "transcript"
547
550
  ? {
@@ -571,6 +574,7 @@ const search = (database, query, filter) => {
571
574
  startMs: int(row.start_ms),
572
575
  };
573
576
  });
577
+ return hasMore ? { items, hasMore, nextOffset: offset + limit } : { items, hasMore };
574
578
  });
575
579
  };
576
580
  const participants = (database, query, accountId) => {
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { MEMORY_KINDS, MEMORY_SCOPES, type MEMORY_STATUSES } from "../../domain/knowledge.js";
2
3
  import { type Decider } from "../decisions.js";
3
4
  import type { SourceReviewMarker } from "../source-review.js";
@@ -74,7 +75,7 @@ export interface MemoriesStore {
74
75
  limit?: number;
75
76
  /** Rows to skip, for the next page: newest first, ties by id, so pages do not overlap. */
76
77
  offset?: number;
77
- }): Promise<Memory[]>;
78
+ }): Promise<ListResult<Memory>>;
78
79
  /** Moves it to another project, or to none with `null`. */
79
80
  update(reference: string, change: {
80
81
  project: string | null;
@@ -103,7 +104,8 @@ export interface MemoriesStore {
103
104
  subject?: string;
104
105
  scope?: Memory["scope"];
105
106
  limit?: number;
106
- }): Promise<Memory[]>;
107
+ offset?: number;
108
+ }): Promise<ListResult<Memory>>;
107
109
  indexState(): Promise<NoteIndexState>;
108
110
  }
109
111
  type Row = Record<string, unknown>;
@@ -9,6 +9,7 @@ import { linkKind } from "./link-kinds.js";
9
9
  import { idsOf } from "./merged-persons.js";
10
10
  import { CORPORA, corpusIndexState, drainCorpus } from "./note-index.js";
11
11
  import { requiredThing } from "./notes.js";
12
+ import { pageOfRows } from "./rows-page.js";
12
13
  import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
13
14
  import { stemmerCache } from "./stems.js";
14
15
  import { referenceOfThing, storedThing } from "./things.js";
@@ -269,12 +270,15 @@ export const memoriesStoreOver = (context) => {
269
270
  const subject = options.subject === undefined ? undefined : requiredThing(database, options.subject);
270
271
  const project = options.project === undefined ? null : projectId(database, options.project);
271
272
  const by = proposedBySql("m.author_type", "m.author_id", options.proposedBy);
272
- return database
273
+ const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
274
+ const offset = Math.max(options.offset ?? 0, 0);
275
+ const rows = database
273
276
  .prepare(`${NAMED} WHERE m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id IN (SELECT value FROM json_each(?)))) ` +
274
277
  "AND (? IS NULL OR m.project_id = ?) AND (? IS NULL OR m.kind = ?) AND (? IS NULL OR m.status = ?) AND (? IS NULL OR m.scope = ?) " +
275
278
  `AND ${by.sql} ORDER BY m.created_at DESC, m.id DESC LIMIT ? OFFSET ?`)
276
- .all(subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, project, project, options.kind ?? null, options.kind ?? null, options.status ?? null, options.status ?? null, options.scope ?? null, options.scope ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500), Math.max(options.offset ?? 0, 0))
279
+ .all(subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, project, project, options.kind ?? null, options.kind ?? null, options.status ?? null, options.status ?? null, options.scope ?? null, options.scope ?? null, ...by.params, limit + 1, offset)
277
280
  .map(memoryOf);
281
+ return pageOfRows(rows, limit, offset);
278
282
  },
279
283
  update: async (reference, change) => write(database, () => {
280
284
  const id = Number(rowOf(reference).id);
@@ -313,7 +317,7 @@ export const memoriesStoreOver = (context) => {
313
317
  return { ref: `memory:${id}`, removed: true, links };
314
318
  },
315
319
  sources: async (reference) => evidenceSourcesOf(database, { type: "memory", id: Number(rowOf(reference).id) }),
316
- search: async (text, { subject: subjectRef, scope, limit = 20 } = {}) => {
320
+ search: async (text, { subject: subjectRef, scope, limit: asked = 20, offset: from = 0 } = {}) => {
317
321
  const subject = subjectRef === undefined ? undefined : requiredThing(database, subjectRef);
318
322
  drainCorpus(database, CORPORA.memory, stemmerFor);
319
323
  const words = normalize(text)
@@ -322,13 +326,16 @@ export const memoriesStoreOver = (context) => {
322
326
  if (words.length === 0)
323
327
  throw new CliError("validation_error", "say what to find in the memories");
324
328
  const match = `normalized_text : (${words.map((word) => `"${word.replaceAll('"', '""')}"*`).join(" AND ")})`;
325
- return database
329
+ const limit = Math.min(Math.max(asked, 1), 200);
330
+ const offset = Math.max(from, 0);
331
+ const rows = database
326
332
  .prepare("SELECT m.*, b.name AS author_name, b.kind AS author_kind FROM memory_words w JOIN memories m ON m.id = w.rowid " +
327
333
  "LEFT JOIN bots b ON m.author_type = 'bot' AND b.id = m.author_id WHERE memory_words MATCH ? " +
328
334
  "AND m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id IN (SELECT value FROM json_each(?)))) " +
329
- "AND (? IS NULL OR m.scope = ?) ORDER BY bm25(memory_words), m.id LIMIT ?")
330
- .all(match, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, scope ?? null, scope ?? null, Math.min(Math.max(limit, 1), 200))
335
+ "AND (? IS NULL OR m.scope = ?) ORDER BY bm25(memory_words), m.id LIMIT ? OFFSET ?")
336
+ .all(match, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, scope ?? null, scope ?? null, limit + 1, offset)
331
337
  .map(memoryOf);
338
+ return pageOfRows(rows, limit, offset);
332
339
  },
333
340
  indexState: async () => corpusIndexState(database, CORPORA.memory),
334
341
  };
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type TransactionStatus } from "../../domain/business.js";
2
3
  import { type FinanceReview, type MoneyDirection } from "../../domain/finance.js";
3
4
  import { type Money } from "../../domain/money.js";
@@ -94,6 +95,7 @@ export interface TransactionFilter {
94
95
  uncategorized?: boolean;
95
96
  /** 1–500, 100 by default; latest statement day first. */
96
97
  limit?: number;
98
+ offset?: number;
97
99
  }
98
100
  export interface CategoryTotal extends Money {
99
101
  /** `null` for what no split categorizes. */
@@ -106,7 +108,7 @@ export interface CategoryTotal extends Money {
106
108
  export interface TransactionsStore {
107
109
  add(input: TransactionInput): Promise<MoneyTransaction>;
108
110
  get(reference: string): Promise<MoneyTransaction>;
109
- list(filter?: TransactionFilter): Promise<MoneyTransaction[]>;
111
+ list(filter?: TransactionFilter): Promise<ListResult<MoneyTransaction>>;
110
112
  update(reference: string, input: TransactionUpdate): Promise<MoneyTransaction>;
111
113
  addSplit(reference: string, input: SplitInput & {
112
114
  by: Author;
@@ -7,6 +7,7 @@ import { proposedBySql } from "./actors.js";
7
7
  import { projectId } from "./memories.js";
8
8
  import { requiredThing } from "./notes.js";
9
9
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
10
+ import { pageOfRows } from "./rows-page.js";
10
11
  import { write } from "./transaction.js";
11
12
  const TRANSACTIONS = "SELECT t.*, w.name AS wallet_name, b.name AS author_name, b.kind AS author_kind, " +
12
13
  "(SELECT coalesce(sum(amount), 0) FROM transaction_splits WHERE transaction_id = t.id) AS split " +
@@ -167,6 +168,8 @@ export const transactionOperationsOver = (context) => {
167
168
  },
168
169
  get: (reference) => transactionOf(rowOf(reference)),
169
170
  list: (filter = {}) => {
171
+ const limit = limitOf(filter.limit);
172
+ const offset = Math.max(filter.offset ?? 0, 0);
170
173
  const wallet = filter.wallet === undefined ? null : linkedId(filter.wallet, "wallet", "transaction.ref");
171
174
  const project = filter.project === undefined ? null : projectId(database, filter.project);
172
175
  const direction = filter.direction === undefined ? null : oneOf(filter.direction, MONEY_DIRECTIONS, "a direction");
@@ -174,16 +177,17 @@ export const transactionOperationsOver = (context) => {
174
177
  const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
175
178
  const category = filter.category === undefined ? null : fold(filter.category.trim());
176
179
  const by = proposedBySql("t.author_type", "t.author_id", filter.proposedBy);
177
- return database
180
+ const rows = database
178
181
  .prepare(`${TRANSACTIONS} WHERE t.deleted_at IS NULL AND (? IS NULL OR t.financial_account_id = ?) ` +
179
182
  "AND (? IS NULL OR t.direction = ?) AND (? IS NULL OR t.status = ?) AND (? IS NULL OR t.review = ?) " +
180
183
  "AND (? IS NULL OR t.project_id = ? OR EXISTS (SELECT 1 FROM transaction_splits s WHERE s.transaction_id = t.id " +
181
184
  "AND s.project_id = ?)) AND (? IS NULL OR EXISTS (SELECT 1 FROM transaction_splits s " +
182
185
  "WHERE s.transaction_id = t.id AND s.category_folded = ?)) " +
183
186
  `${filter.uncategorized ? "AND split < t.amount " : ""}AND ${by.sql} ` +
184
- "ORDER BY t.statement_date DESC, t.id DESC LIMIT ?")
185
- .all(wallet, wallet, direction, direction, status, status, review, review, project, project, project, category, category, ...by.params, limitOf(filter.limit))
187
+ "ORDER BY t.statement_date DESC, t.id DESC LIMIT ? OFFSET ?")
188
+ .all(wallet, wallet, direction, direction, status, status, review, review, project, project, project, category, category, ...by.params, limit + 1, offset)
186
189
  .map(transactionOf);
190
+ return pageOfRows(rows, limit, offset);
187
191
  },
188
192
  update: (reference, input) => {
189
193
  const row = rowOf(reference);
@@ -12,14 +12,14 @@ export interface SharedTrace {
12
12
  /** An identity of each side that holds it. */
13
13
  identity: number;
14
14
  with: number;
15
- kind: "chat" | "email" | "email-domain" | "phone";
15
+ kind: "chat" | "email" | "crm-company" | "email-domain" | "phone";
16
16
  /** The phone or address, for the kinds that have one. */
17
17
  value?: string;
18
18
  evidence: string[];
19
19
  reason: string;
20
20
  }
21
21
  /**
22
- * The traces two people share, strongest first: each phone, each address, a chat, a company's domain. `except` is an
23
- * address left out, with its domain, when it is the very thing being weighed.
22
+ * The traces two people share, strongest first: each phone, each address, a chat, one company in the CRM, a company's
23
+ * domain. `except` is an address left out, with its domain, when it is the very thing being weighed.
24
24
  */
25
25
  export declare function sharedTraces(database: CacheDatabase, a: number, b: number, name: string, except?: string): Generator<SharedTrace>;
@@ -73,9 +73,27 @@ const commonChat = (database, a, b) => database
73
73
  "JOIN identity_links l2 ON l2.identity_id = m2.identity_id " +
74
74
  "WHERE l1.person_id = ? AND l2.person_id = ? ORDER BY m1.chat_id LIMIT 1")
75
75
  .get(a, b);
76
+ /** An organization the CRM puts both people in, with a CRM identity of each: the owner's CRM, not a mail domain. */
77
+ const crmCompany = (database, a, b) => {
78
+ const row = database
79
+ .prepare("SELECT k1.to_id AS organization, (SELECT min(identity_id) FROM identity_links WHERE person_id = ?) AS one, " +
80
+ "(SELECT min(identity_id) FROM identity_links WHERE person_id = ?) AS other FROM links k1 " +
81
+ "JOIN links k2 ON k2.to_type = 'organization' AND k2.to_id = k1.to_id AND k2.kind = 'member-of' " +
82
+ "AND k2.source = 'crm' AND k2.deleted_at IS NULL AND k2.from_type = 'person' AND k2.from_id = ? " +
83
+ "WHERE k1.from_type = 'person' AND k1.from_id = ? AND k1.to_type = 'organization' AND k1.kind = 'member-of' " +
84
+ "AND k1.source = 'crm' AND k1.deleted_at IS NULL ORDER BY k1.to_id LIMIT 1")
85
+ .get(a, b, b, a);
86
+ if (!row || row.one == null || row.other == null)
87
+ return undefined;
88
+ return {
89
+ one: row.one,
90
+ other: row.other,
91
+ ref: referenceOfThing(database, { type: "organization", id: Number(row.organization) }),
92
+ };
93
+ };
76
94
  /**
77
- * The traces two people share, strongest first: each phone, each address, a chat, a company's domain. `except` is an
78
- * address left out, with its domain, when it is the very thing being weighed.
95
+ * The traces two people share, strongest first: each phone, each address, a chat, one company in the CRM, a company's
96
+ * domain. `except` is an address left out, with its domain, when it is the very thing being weighed.
79
97
  */
80
98
  export function* sharedTraces(database, a, b, name, except) {
81
99
  const [one, other] = [tracesOf(database, a, except), tracesOf(database, b, except)];
@@ -108,6 +126,15 @@ export function* sharedTraces(database, a, b, name, except) {
108
126
  reason: `same name «${name}» and a chat they are both in`,
109
127
  };
110
128
  }
129
+ const company = crmCompany(database, a, b);
130
+ if (company)
131
+ yield {
132
+ identity: Number(company.one),
133
+ with: Number(company.other),
134
+ kind: "crm-company",
135
+ evidence: company.ref === undefined ? [] : [company.ref],
136
+ reason: `same name «${name}» and the same company in the CRM`,
137
+ };
111
138
  const domain = common(one.domains, other.domains).next().value;
112
139
  if (domain)
113
140
  yield {