@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,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type OrderDirection } from "../../domain/business.js";
2
3
  import { type FinanceReview } from "../../domain/finance.js";
3
4
  import { type OrderPurpose, type OrderStatus } from "../../domain/orders.js";
@@ -79,6 +80,7 @@ export interface OrderFilter {
79
80
  proposedBy?: ProposedByFilter;
80
81
  /** 1–500, 100 by default; newest written first. */
81
82
  limit?: number;
83
+ offset?: number;
82
84
  }
83
85
  /**
84
86
  * What the owner, his business or a client ordered, from whom, and how far delivery got. The owner's entry is
@@ -87,7 +89,7 @@ export interface OrderFilter {
87
89
  export interface OrdersStore {
88
90
  add(input: OrderInput): Promise<OrderDetail>;
89
91
  get(reference: string): Promise<OrderDetail>;
90
- list(filter?: OrderFilter): Promise<Order[]>;
92
+ list(filter?: OrderFilter): Promise<ListResult<Order>>;
91
93
  /** The owner moves an order on, such as a later mail saying it shipped; `date` is the delivery day. */
92
94
  setStatus(reference: string, input: {
93
95
  status: OrderStatus;
@@ -10,6 +10,7 @@ import { projectId } from "./memories.js";
10
10
  import { MAX_LINES, moneyLinesOver } from "./money-lines.js";
11
11
  import { requiredThing } from "./notes.js";
12
12
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
13
+ import { pageOfRows } from "./rows-page.js";
13
14
  import { write } from "./transaction.js";
14
15
  const ORDERS = "SELECT o.*, b.name AS author_name, b.kind AS author_kind FROM orders o " +
15
16
  "LEFT JOIN bots b ON o.author_type = 'bot' AND b.id = o.author_id";
@@ -171,6 +172,7 @@ export const orderOperationsOver = (context) => {
171
172
  const number = filter.number === undefined ? null : filter.number.trim();
172
173
  const shop = filter.supplierName === undefined ? null : fold(filter.supplierName);
173
174
  const limit = limitOf(filter.limit);
175
+ const offset = Math.max(filter.offset ?? 0, 0);
174
176
  const rows = database
175
177
  .prepare(`${ORDERS} WHERE o.deleted_at IS NULL AND (? IS NULL OR o.status = ?) AND (? IS NULL OR o.purpose = ?) ` +
176
178
  "AND (? IS NULL OR o.review = ?) AND (? IS NULL OR o.project_id = ?) AND (? IS NULL OR o.number = ?) " +
@@ -178,10 +180,11 @@ export const orderOperationsOver = (context) => {
178
180
  "AND (? IS NULL OR (o.supplier_type = ? AND o.supplier_id = ?)) " +
179
181
  `AND ${by.sql} ORDER BY o.created_at DESC, o.id DESC`)
180
182
  .all(status, status, purpose, purpose, review, review, project, project, number, number, customer?.type ?? null, customer?.type ?? null, customer?.id ?? null, supplier?.type ?? null, supplier?.type ?? null, supplier?.id ?? null, ...by.params);
181
- return rows
183
+ const page = rows
182
184
  .filter((row) => shop === null || fold(String(row.supplier_name)) === shop)
183
- .slice(0, limit)
185
+ .slice(offset, offset + limit + 1)
184
186
  .map(orderOf);
187
+ return pageOfRows(page, limit, offset);
185
188
  },
186
189
  setStatus: (reference, { status, date, by }) => {
187
190
  ownerOnly(by, "moves an order on");
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
3
- import { displayName, isReadable, nameKey, takeFallbacks } from "../../domain/display-names.js";
2
+ import { isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddress } from "../../domain/addresses.js";
3
+ import { displayName, isReadable, nameKey, noFallbacks, takeFallbacks } from "../../domain/display-names.js";
4
4
  import { spellings, variantKey } from "../../domain/name-variants.js";
5
5
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
6
6
  import { isQueryOnly } from "../driver.js";
@@ -18,7 +18,8 @@ const matching = (query) => {
18
18
  return { sql: "", params: [] };
19
19
  const text = query.trim();
20
20
  if (text.length < MIN_QUERY)
21
- throw new CliError("validation_error", `a people search takes at least ${MIN_QUERY} characters, got "${query}"`);
21
+ throw new CliError("validation_error", `a people search takes at least ${MIN_QUERY} characters, got "${query}" — write more of the name, ` +
22
+ "or leave the search out and read the list by name", { reason: "query.short-text" });
22
23
  const forms = [...new Set([text, ...spellings(text)])];
23
24
  const like = (form) => `%${form.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
24
25
  return {
@@ -36,10 +37,16 @@ const TASK_COUNTS = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, j
36
37
  const IN_SCOPE = (scope, column) => scope === "all" ? "1" : `${column} IN (SELECT value FROM json_each(?))`;
37
38
  const scopeParams = (scope) => (scope === "all" ? [] : [JSON.stringify(scope)]);
38
39
  const SCOPED_IDENTITIES = (scope) => `SELECT identity_id FROM identity_links WHERE ${IN_SCOPE(scope, "person_id")}`;
39
- /** Counted over `messages_by_sender_identity_id` alone: no message row is read. */
40
- const MESSAGE_COUNTS = (scope) => "SELECT l.person_id AS person, sum(x.n) AS n FROM (SELECT sender_identity_id AS identity, count(*) AS n FROM " +
41
- `messages WHERE sender_identity_id ${scope === "all" ? "IS NOT NULL" : `IN (${SCOPED_IDENTITIES(scope)})`} ` +
42
- "GROUP BY 1) x JOIN identity_links l ON l.identity_id = x.identity GROUP BY 1";
40
+ const OF_SCOPE = (scope, column) => `${column} ${scope === "all" ? "IS NOT NULL" : `IN (${SCOPED_IDENTITIES(scope)})`}`;
41
+ /** Per identity, over `messages_by_sender_identity_id` alone: no message row is read. */
42
+ const IDENTITY_MESSAGE_COUNTS = (scope) => `SELECT sender_identity_id AS identity, count(*) AS n FROM messages WHERE ${OF_SCOPE(scope, "sender_identity_id")} ` +
43
+ "GROUP BY 1";
44
+ const IDENTITY_MAIL_COUNTS = (scope) => `SELECT from_identity_id AS identity, count(*) AS n FROM emails WHERE ${OF_SCOPE(scope, "from_identity_id")} ` +
45
+ "GROUP BY 1";
46
+ /** Who wrote in a private chat the owner wrote in too: a conversation, which no mail signal makes automated. */
47
+ const TWO_WAY = "SELECT DISTINCT s.sender_identity_id AS identity_id FROM messages s WHERE s.outgoing IS NOT 1 " +
48
+ "AND s.sender_identity_id IS NOT NULL AND s.chat_id IN (SELECT c.id FROM chats c WHERE c.kind = 'dialog' " +
49
+ "AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id AND o.outgoing = 1))";
43
50
  const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum(EXISTS (SELECT 1 FROM email_mailboxes m " +
44
51
  "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
45
52
  "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
@@ -56,6 +63,15 @@ const LAST_CONTACTS = (identities) => `SELECT l.person_id AS person, max(t) AS a
56
63
  "AND deleted_at IS NULL GROUP BY 1 UNION ALL " +
57
64
  `SELECT identity_id, max(last_messaged_at) FROM account_identities WHERE identity_id IN (${identities}) GROUP BY 1` +
58
65
  ") x JOIN identity_links l ON l.identity_id = x.identity GROUP BY 1";
66
+ const perIdentity = (database, sql, params) => new Map(database
67
+ .prepare(sql)
68
+ .all(...params)
69
+ .map((row) => [Number(row.identity), Number(row.n)]));
70
+ /**
71
+ * The name comes from the oldest identity that has one. The phone, address and username come from the identity that
72
+ * wrote the most and has one (the owner's rule, 2026-11-11): an old mail contact's address is no way to reach someone
73
+ * who writes in a messenger every day. On a tie, or when nobody wrote, the oldest identity wins, as for the name.
74
+ */
59
75
  const factsOf = (database, scope) => {
60
76
  const facts = new Map();
61
77
  const text = (value) => (value == null || value === "" ? null : String(value));
@@ -65,9 +81,19 @@ const factsOf = (database, scope) => {
65
81
  .map((row) => Number(row.identity_id)));
66
82
  const neverReplied = ids(NEVER_REPLIED);
67
83
  const owned = ids(OWNED);
84
+ const twoWay = ids(TWO_WAY);
85
+ const messages = perIdentity(database, IDENTITY_MESSAGE_COUNTS(scope), scopeParams(scope));
86
+ const mail = perIdentity(database, IDENTITY_MAIL_COUNTS(scope), scopeParams(scope));
87
+ const rows = new Map();
68
88
  for (const row of database.prepare(IDENTITIES(scope)).all(...scopeParams(scope))) {
69
89
  const person = Number(row.person);
70
- const one = facts.get(person) ?? {
90
+ const id = Number(row.id);
91
+ const held = rows.get(person) ?? [];
92
+ held.push({ row, written: (messages.get(id) ?? 0) + (mail.get(id) ?? 0) });
93
+ rows.set(person, held);
94
+ }
95
+ for (const [person, held] of rows) {
96
+ const one = {
71
97
  name: null,
72
98
  username: null,
73
99
  usernameSource: null,
@@ -77,10 +103,10 @@ const factsOf = (database, scope) => {
77
103
  bot: false,
78
104
  neverReplied: false,
79
105
  organization: false,
106
+ twoWay: false,
107
+ messages: 0,
80
108
  };
81
- const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
82
- const hadUsername = one.username !== null;
83
- takeFallbacks(one, {
109
+ const source = (row) => ({
84
110
  provider: String(row.provider),
85
111
  id: String(row.external_id),
86
112
  name: text(row.name),
@@ -88,13 +114,30 @@ const factsOf = (database, scope) => {
88
114
  phone: text(row.phone),
89
115
  email: text(row.email),
90
116
  });
91
- if (!hadUsername && one.username !== null)
92
- one.usernameSource = String(row.provider);
93
- if (email !== null)
94
- one.emails.push(email);
95
- one.bot ||= Number(row.bot) === 1;
96
- one.neverReplied ||= neverReplied.has(Number(row.id));
97
- one.organization ||= owned.has(Number(row.id));
117
+ for (const { row } of held) {
118
+ const identity = Number(row.id);
119
+ const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
120
+ if (email !== null)
121
+ one.emails.push(email);
122
+ if (one.name === null)
123
+ one.name = takeFallbacks(noFallbacks(), source(row)).name;
124
+ one.bot ||= Number(row.bot) === 1;
125
+ one.neverReplied ||= neverReplied.has(identity);
126
+ one.organization ||= owned.has(identity);
127
+ one.twoWay ||= twoWay.has(identity);
128
+ one.messages += messages.get(identity) ?? 0;
129
+ }
130
+ const contact = noFallbacks();
131
+ // Stable: equal counts keep the identities' stored order.
132
+ for (const { row } of [...held].sort((a, b) => b.written - a.written)) {
133
+ const hadUsername = contact.username !== null;
134
+ takeFallbacks(contact, source(row));
135
+ if (!hadUsername && contact.username !== null)
136
+ one.usernameSource = String(row.provider);
137
+ }
138
+ one.username = contact.username;
139
+ one.phone = contact.phone;
140
+ one.email = contact.email;
98
141
  facts.set(person, one);
99
142
  }
100
143
  return facts;
@@ -125,11 +168,14 @@ const kindOf = (shown, facts, ties, mail, test) => {
125
168
  ...(facts?.neverReplied ? ["bulk-never-replied"] : []),
126
169
  ...(isAutomatedName(shown) ? ["automated-name"] : []),
127
170
  ];
128
- if (automated.length > 0)
171
+ // One mailbox's newsletter signal must not hide someone the owner talks to in a private chat.
172
+ if (automated.length > 0 && (facts?.bot || !facts?.twoWay))
129
173
  return { kind: "automated", signals: automated };
130
174
  const organization = [
131
175
  ...(facts?.organization ? ["organization"] : []),
132
- ...(emails.length > 0 && emails.every(isRoleAddress) ? ["role-address"] : []),
176
+ ...(emails.length > 0 && emails.every((one) => isRoleAddress(one) && !isPersonLikeRoleAddress(one))
177
+ ? ["role-address"]
178
+ : []),
133
179
  ...(isCompanyName(shown) ? ["company-name"] : []),
134
180
  ];
135
181
  if (organization.length > 0)
@@ -145,7 +191,6 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
145
191
  const facts = factsOf(database, scope);
146
192
  const test = hiddenTestPeople(database);
147
193
  const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
148
- const messages = countsOf(database, MESSAGE_COUNTS(scope), ...scopeParams(scope));
149
194
  const mail = new Map(database
150
195
  .prepare(MAIL_COUNTS(scope))
151
196
  .all(...scopeParams(scope))
@@ -169,7 +214,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
169
214
  contact: contact.phone ?? contact.email ?? (contact.username === null ? null : `@${contact.username.replace(/^@/, "")}`),
170
215
  ...contact,
171
216
  usernameSource: own?.usernameSource ?? null,
172
- messagesFrom: (messages.get(id) ?? 0) + (mail.get(id)?.n ?? 0),
217
+ messagesFrom: (own?.messages ?? 0) + (mail.get(id)?.n ?? 0),
173
218
  ties,
174
219
  };
175
220
  });
@@ -6,7 +6,8 @@ export declare const RULE: Author;
6
6
  * NEED-2529: every rule's proposal on the scale of `SHARED_SCORE`, so the review lists the strongest first. A phone two
7
7
  * people alone have but that does not join (a CRM's or a card's), one name with a phone or an address only these two
8
8
  * hold, and a pair the owner rejected that meets new evidence of that kind are 0.7; one name with a chat or a company
9
- * domain in one source, and a meeting guest's typed address, 0.5; a phone or personal address 3–6 people share, 0.4.
9
+ * domain in one source, and a meeting guest's typed address, 0.5; a phone or personal address 3–6 people share, 0.4;
10
+ * one name alone, written in private chats the owner answers on two messengers, 0.3.
10
11
  */
11
12
  export declare const PROPOSAL_SCORE: {
12
13
  ownPhone: number;
@@ -15,6 +16,7 @@ export declare const PROPOSAL_SCORE: {
15
16
  nameAndPlace: number;
16
17
  guestEmail: number;
17
18
  group: number;
19
+ nameInChats: number;
18
20
  };
19
21
  /**
20
22
  * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
@@ -1,4 +1,5 @@
1
- import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
1
+ import { isEmailAddress, isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { displayName, isReadable } from "../../domain/display-names.js";
2
3
  import { variantKey } from "../../domain/name-variants.js";
3
4
  import { BARE_INTERNATIONAL_PROVIDERS, storedPhone } from "../../domain/phones.js";
4
5
  import { linkIndex, settleLinks } from "./identity-link-rows.js";
@@ -17,17 +18,18 @@ export const RULE = { bot: "rule", kind: "rule" };
17
18
  const MOST_SHARING = 6;
18
19
  const CURSOR = "people.scan";
19
20
  /** Raised when a rule changes what a pass finds in values nobody touched: the next pass then reads everything once. */
20
- const RULES = 3;
21
+ const RULES = 4;
21
22
  /**
22
23
  * NEED-2526: a shared mailbox says little alone, so its proposal is scored by what else the two people have in common.
23
- * The role word itself does not move the score: the list does not tell a department's inbox from a company's.
24
+ * The owner's word (2026-11-11): `hr@` is often one person's, so it starts below `info@`.
24
25
  */
25
- const SHARED_SCORE = { alone: 0.1, name: 0.4, trace: 0.3, weakTrace: 0.2 };
26
+ const SHARED_SCORE = { alone: 0.1, personLike: 0.05, name: 0.4, trace: 0.3, weakTrace: 0.2 };
26
27
  /**
27
28
  * NEED-2529: every rule's proposal on the scale of `SHARED_SCORE`, so the review lists the strongest first. A phone two
28
29
  * people alone have but that does not join (a CRM's or a card's), one name with a phone or an address only these two
29
30
  * hold, and a pair the owner rejected that meets new evidence of that kind are 0.7; one name with a chat or a company
30
- * domain in one source, and a meeting guest's typed address, 0.5; a phone or personal address 3–6 people share, 0.4.
31
+ * domain in one source, and a meeting guest's typed address, 0.5; a phone or personal address 3–6 people share, 0.4;
32
+ * one name alone, written in private chats the owner answers on two messengers, 0.3.
31
33
  */
32
34
  export const PROPOSAL_SCORE = {
33
35
  ownPhone: 0.7,
@@ -36,6 +38,7 @@ export const PROPOSAL_SCORE = {
36
38
  nameAndPlace: 0.5,
37
39
  guestEmail: 0.5,
38
40
  group: 0.4,
41
+ nameInChats: 0.3,
39
42
  };
40
43
  /**
41
44
  * NEED-2445, safe option until the owner rules: a number two people share joins them only when a messenger, which
@@ -261,11 +264,12 @@ const TRACE_WORDS = {
261
264
  email: "another address only they have",
262
265
  chat: "a chat they are both in",
263
266
  "email-domain": "mail at the same company",
267
+ "crm-company": "the same company in the CRM",
264
268
  };
265
269
  /** What two people on one shared mailbox have in common besides it, as a score and the words that say why. */
266
270
  const sharedMailboxCase = (context, address, from, to) => {
267
271
  const reasons = [`both have the shared mailbox ${address}`];
268
- let score = SHARED_SCORE.alone;
272
+ let score = isPersonLikeRoleAddress(address) ? SHARED_SCORE.personLike : SHARED_SCORE.alone;
269
273
  const name = nameOf(context, from);
270
274
  const key = variantKey(name);
271
275
  if (key !== null && key === variantKey(nameOf(context, to))) {
@@ -280,7 +284,7 @@ const sharedMailboxCase = (context, address, from, to) => {
280
284
  evidence = trace.evidence;
281
285
  break;
282
286
  }
283
- return { score: Math.round(score * 10) / 10, reason: reasons.join("; "), evidence };
287
+ return { score: Math.round(score * 100) / 100, reason: reasons.join("; "), evidence };
284
288
  };
285
289
  /**
286
290
  * NEED-2526: a shared mailbox never joins anyone (SEC-177), but each pair on it is proposed to the owner, scored by
@@ -385,6 +389,88 @@ const sameName = (pass, people, name) => {
385
389
  });
386
390
  }
387
391
  };
392
+ /**
393
+ * The identities that wrote in a private chat the owner wrote in too, by the name they write under. A messenger may
394
+ * hide the phone (a WhatsApp `@lid`), so one name on two messengers, each a conversation, is all there is to go on.
395
+ */
396
+ const chatNames = (database) => {
397
+ const found = new Map();
398
+ for (const row of database
399
+ .prepare("SELECT DISTINCT i.id, i.provider, i.name FROM messages s JOIN identities i ON i.id = s.sender_identity_id " +
400
+ "JOIN identity_links l ON l.identity_id = i.id WHERE s.outgoing IS NOT 1 AND i.bot IS NOT 1 " +
401
+ "AND trim(coalesce(i.name, '')) <> '' AND s.chat_id IN (SELECT c.id FROM chats c WHERE c.kind = 'dialog' " +
402
+ "AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id AND o.outgoing = 1)) ORDER BY i.id")
403
+ .all()) {
404
+ const name = String(row.name).trim();
405
+ const key = name.toLocaleLowerCase();
406
+ const held = found.get(key) ?? [];
407
+ held.push({ identity: Number(row.id), provider: String(row.provider), name });
408
+ found.set(key, held);
409
+ }
410
+ return found;
411
+ };
412
+ /** One name on two messengers, each a private conversation, and nothing else: the owner decides (`nameInChats`). */
413
+ const sameNameInChats = (pass, holders) => {
414
+ const people = new Map();
415
+ for (const holder of holders) {
416
+ const person = personOf(pass.context, holder.identity);
417
+ if (person !== undefined && !people.has(person))
418
+ people.set(person, holder);
419
+ }
420
+ if (people.size < 2)
421
+ return;
422
+ if (people.size > MOST_SHARING) {
423
+ pass.result.skipped.push({
424
+ persons: [...people.keys()].map(String),
425
+ signal: "name",
426
+ reason: "identity.common-name",
427
+ });
428
+ return;
429
+ }
430
+ const persons = [...people.keys()].sort((a, b) => a - b);
431
+ for (const [at, from] of persons.entries())
432
+ for (const to of persons.slice(at + 1)) {
433
+ const [one, other] = [people.get(from), people.get(to)];
434
+ if (one === undefined || other === undefined || one.provider === other.provider)
435
+ continue;
436
+ propose(pass, {
437
+ identity: one.identity,
438
+ with: other.identity,
439
+ from,
440
+ to,
441
+ joins: "person",
442
+ signal: "name",
443
+ score: PROPOSAL_SCORE.nameInChats,
444
+ reason: `same name «${one.name}» in private chats on ${one.provider} and ${other.provider}`,
445
+ });
446
+ }
447
+ };
448
+ /**
449
+ * The person an identity of one of the owner's own accounts sits on (a second profile they use) is named after that
450
+ * profile's label: their own name from their other identities is better, the fullest one first.
451
+ */
452
+ const renameFromOwnAccounts = ({ database, now }) => {
453
+ const named = database
454
+ .prepare("SELECT DISTINCT p.id FROM persons p JOIN identity_links l ON l.person_id = p.id " +
455
+ "JOIN identities i ON i.id = l.identity_id JOIN accounts a ON a.provider = i.provider " +
456
+ "AND a.external_id = i.external_id WHERE p.owner = 0 AND p.name = i.name")
457
+ .all();
458
+ for (const { id } of named) {
459
+ const names = database
460
+ .prepare("SELECT i.name FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ? " +
461
+ "AND trim(coalesce(i.name, '')) <> '' AND NOT EXISTS (SELECT 1 FROM accounts a " +
462
+ "WHERE a.provider = i.provider AND a.external_id = i.external_id) ORDER BY i.id")
463
+ .all(Number(id))
464
+ .map((row) => String(row.name).trim())
465
+ .filter((name) => isReadable(displayName(name)) && !name.startsWith("@"));
466
+ const words = (name) => name.split(/\s+/u).length;
467
+ const fullest = names.reduce((best, name) => best === undefined || words(name) > words(best) || (words(name) === words(best) && name.length > best.length)
468
+ ? name
469
+ : best, undefined);
470
+ if (fullest !== undefined)
471
+ database.prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ?").run(fullest, now(), Number(id));
472
+ }
473
+ };
388
474
  /** What a meeting guest typed is their word only: it is proposed, and only when it names exactly one person. */
389
475
  const guestEmail = (pass, row) => {
390
476
  const { context } = pass;
@@ -453,6 +539,10 @@ export const scanMatches = (context, { full = false } = {}) => {
453
539
  for (const { people, name } of peopleByNameKey(database).values())
454
540
  if (people.length > 1 && (changedPeople === undefined || people.some((one) => changedPeople.has(one))))
455
541
  write(database, () => sameName(pass, people, name));
542
+ for (const holders of chatNames(database).values())
543
+ if (holders.length > 1 && (changed === undefined || holders.some(({ identity }) => changed.has(identity))))
544
+ write(database, () => sameNameInChats(pass, holders));
545
+ write(database, () => renameFromOwnAccounts(context));
456
546
  write(database, () => database
457
547
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
458
548
  .run(CURSOR, JSON.stringify(started), context.now()));
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type CatalogKind } from "../../domain/business.js";
2
3
  import { type Author } from "./memories.js";
3
4
  import type { StoreContext } from "./open.js";
@@ -62,12 +63,13 @@ export interface ProductFilter {
62
63
  name?: string;
63
64
  /** 1–500, 100 by default; by name. */
64
65
  limit?: number;
66
+ offset?: number;
65
67
  }
66
68
  /** What the owner or a supplier sells, written directly by the owner or an agent. */
67
69
  export interface ProductsStore {
68
70
  add(input: ProductInput): Promise<Product>;
69
71
  get(reference: string): Promise<Product>;
70
- list(filter?: ProductFilter): Promise<Product[]>;
72
+ list(filter?: ProductFilter): Promise<ListResult<Product>>;
71
73
  update(reference: string, input: ProductUpdate): Promise<Product>;
72
74
  }
73
75
  type ProductOperations = {
@@ -4,6 +4,7 @@ import { fold } from "../normalize.js";
4
4
  import { authorActor, authorOf } from "./memories.js";
5
5
  import { requiredThing } from "./notes.js";
6
6
  import { iso, isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
7
+ import { pageOfRows } from "./rows-page.js";
7
8
  import { write } from "./transaction.js";
8
9
  const PRODUCTS = "SELECT c.*, b.name AS author_name, b.kind AS author_kind FROM catalog_items c " +
9
10
  "LEFT JOIN bots b ON c.author_type = 'bot' AND b.id = c.author_id";
@@ -89,14 +90,16 @@ export const productOperationsOver = (context) => {
89
90
  const archived = filter.archived === undefined ? null : filter.archived ? 1 : 0;
90
91
  const words = filter.name === undefined ? [] : fold(filter.name).split(/\s+/).filter(Boolean);
91
92
  const limit = limitOf(filter.limit);
92
- return database
93
+ const offset = Math.max(filter.offset ?? 0, 0);
94
+ const rows = database
93
95
  .prepare(`${PRODUCTS} WHERE c.deleted_at IS NULL AND (? IS NULL OR c.kind = ?) ` +
94
96
  "AND (? IS NULL OR (c.supplier_type = ? AND c.supplier_id = ?)) " +
95
97
  "AND (? IS NULL OR (c.archived_date IS NOT NULL) = ?) ORDER BY c.name_folded, c.id")
96
98
  .all(kind, kind, supplier?.type ?? null, supplier?.type ?? null, supplier?.id ?? null, archived, archived)
97
99
  .filter((row) => words.every((word) => String(row.name_folded).includes(word)))
98
- .slice(0, limit)
100
+ .slice(offset, offset + limit + 1)
99
101
  .map(productOf);
102
+ return pageOfRows(rows, limit, offset);
100
103
  },
101
104
  update: (reference, input) => {
102
105
  const row = rowOf(reference);
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type Decider, type Proposer } from "../decisions.js";
2
3
  import type { AccountKey } from "../types.js";
3
4
  import { type Actor, type ProposedByFilter } from "./actors.js";
@@ -65,7 +66,7 @@ export interface ProposedActionsStore {
65
66
  project?: string;
66
67
  /** A reference the payload's `evidence` holds. */
67
68
  evidence?: string;
68
- }): Promise<ProposedAction[]>;
69
+ }): Promise<ListResult<ProposedAction>>;
69
70
  /** `result` records what the approval made, such as the task it became. `by` must be allowed to decide it. */
70
71
  approve(id: string, by: Decider, result?: unknown): Promise<ProposedAction>;
71
72
  /** `reason` is kept as the result: why it was turned down. */
@@ -9,6 +9,7 @@ import { SOURCE_REVIEW_KIND } from "../source-review.js";
9
9
  import { proposedBySql } from "./actors.js";
10
10
  import { authorActor } from "./memories.js";
11
11
  import { requiredThing } from "./notes.js";
12
+ import { pageOfRows } from "./rows-page.js";
12
13
  import { referenceOfThing, storedThing } from "./things.js";
13
14
  import { write } from "./transaction.js";
14
15
  export const PROPOSAL_STATUSES = ["proposed", "approved", "rejected", "executed", "failed"];
@@ -133,18 +134,21 @@ export const proposalOperationsOver = (context) => {
133
134
  .prepare(`${NAMED} WHERE p.status = 'proposed' ORDER BY p.created_at, p.id LIMIT ?`)
134
135
  .all(Math.min(Math.max(limit, 1), 500))
135
136
  .map(actionOf),
136
- list: ({ status, limit = 100, offset = 0, kinds, except, proposedBy, project, evidence } = {}) => {
137
+ list: ({ status, limit: asked = 100, offset: from = 0, kinds, except, proposedBy, project, evidence } = {}) => {
138
+ const limit = Math.min(Math.max(asked, 1), 500);
139
+ const offset = Math.max(from, 0);
137
140
  if (status !== undefined && !PROPOSAL_STATUSES.includes(status))
138
141
  throw new CliError("validation_error", `a status is one of ${PROPOSAL_STATUSES.join(", ")}`);
139
142
  const by = proposedBySql("p.proposed_by_type", "p.proposed_by_id", proposedBy);
140
- return database
143
+ const rows = database
141
144
  .prepare(`${NAMED} WHERE (? IS NULL OR ${STATUS} = ?) AND (? IS NULL OR p.kind IN (SELECT value FROM json_each(?))) ` +
142
145
  "AND p.kind NOT IN (SELECT value FROM json_each(?)) AND (? IS NULL OR (p.target_type = 'project' AND " +
143
146
  "'project:' || p.target_id = ?) OR json_extract(p.payload, '$.to') = ? OR json_extract(p.payload, '$.from') = ? " +
144
147
  `OR json_extract(p.payload, '$.project') = ?) AND (? IS NULL OR EXISTS (SELECT 1 FROM json_each(p.payload, '$.evidence') ` +
145
148
  `WHERE value = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ? OFFSET ?`)
146
- .all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), evidence ?? null, evidence ?? null, ...by.params, Math.min(Math.max(limit, 1), 500), Math.max(offset, 0))
149
+ .all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), evidence ?? null, evidence ?? null, ...by.params, limit + 1, offset)
147
150
  .map(actionOf);
151
+ return pageOfRows(rows, limit, offset);
148
152
  },
149
153
  approve: (id, result, by) => decide(id, "approved", result, by),
150
154
  reject: (id, by, result) => decide(id, "rejected", result, by),
@@ -24,6 +24,10 @@ export interface FilterOptions extends QueryContext {
24
24
  zone?: string;
25
25
  now?: number;
26
26
  }
27
+ /** A folded text column read by its words: each word of a term, or a whole phrase, is found inside it; a pattern matches it whole. */
28
+ export declare const foldedWords: (column: string) => {
29
+ where: (node: Predicate) => Where;
30
+ };
27
31
  /**
28
32
  * A validated list query as a `WHERE` condition with bound parameters, matching cli-base's `evaluate`: kw, enum
29
33
  * and ref compare without case (a `folded` column for names in any script), a lone NOT means everything else, and a
@@ -8,6 +8,20 @@ const glob = (value) => [...fold(value).matchAll(/\\(.)|([*?])|(.)/gsu)]
8
8
  return wildcard ?? (/[*?[]/u.test(literal) ? `[${literal}]` : literal);
9
9
  })
10
10
  .join("");
11
+ /** A folded text column read by its words: each word of a term, or a whole phrase, is found inside it; a pattern matches it whole. */
12
+ export const foldedWords = (column) => ({
13
+ where: (node) => {
14
+ if (node.operator === "wildcard")
15
+ return node.value === "*"
16
+ ? { sql: `${column} IS NOT NULL AND ${column} <> ''`, params: [], known: true }
17
+ : { sql: `${column} IS NOT NULL AND ${column} GLOB ?`, params: [glob(node.value)], known: true };
18
+ const wanted = fold(node.value);
19
+ const parts = node.operator === "phrase" ? [wanted] : (wanted.match(/[\p{L}\p{N}]+/gu) ?? []);
20
+ if (!parts.length)
21
+ return { sql: "0", params: [], known: true };
22
+ return { sql: parts.map(() => `instr(${column}, ?) > 0`).join(" AND "), params: parts };
23
+ },
24
+ });
11
25
  const like = (value) => value
12
26
  .toLowerCase()
13
27
  .replace(/[\\%_]/gu, "\\$&")
@@ -923,6 +923,7 @@ export declare const around: (context: StoreContext, chatKey: number | undefined
923
923
  }) => WindowedMessage[];
924
924
  export declare const message: (context: StoreContext, accountKey: number, messageId: Id, chatId: Id | undefined) => Message | undefined;
925
925
  export declare const chatStats: ({ orm }: StoreContext, accountKey: number, chatId: Id | undefined) => ChatStats[];
926
+ export declare const chatsNewest: ({ database }: StoreContext, accountKey: number) => Pick<ChatStats, "chatId" | "title" | "messages" | "newestAt">[];
926
927
  /** One sender's stored messages per chat — count, first and last — in one grouped read. */
927
928
  export declare const senderStats: ({ orm }: StoreContext, accountKey: number, provider: string, senderId: Id) => SenderChatStats[];
928
929
  /**
@@ -179,6 +179,19 @@ export const chatStats = ({ orm }, accountKey, chatId) => {
179
179
  lastStoredAt: toIso(row.stored),
180
180
  }));
181
181
  };
182
+ // `message_count` is kept by triggers; ORDER BY … LIMIT 1 walks `messages_by_time` and skips a tombstone, where
183
+ // max() over the same rows would read the whole chat (PERF-100: 0.48 s of every search at 1M messages).
184
+ export const chatsNewest = ({ database }, accountKey) => database
185
+ .prepare(`SELECT c.external_id AS chat, c.title, c.message_count AS messages, (SELECT m.sent_at FROM messages m WHERE m.chat_id = c.id
186
+ AND m.deleted_at IS NULL ORDER BY m.sent_at DESC LIMIT 1) AS newest
187
+ FROM chats c WHERE c.account_id = ? AND c.message_count > 0`)
188
+ .all(accountKey)
189
+ .map((row) => ({
190
+ chatId: String(row.chat),
191
+ title: row.title === null ? null : String(row.title),
192
+ messages: Number(row.messages),
193
+ newestAt: toIso(row.newest === null ? null : Number(row.newest)),
194
+ }));
182
195
  /** One sender's stored messages per chat — count, first and last — in one grouped read. */
183
196
  export const senderStats = ({ orm }, accountKey, provider, senderId) => {
184
197
  const newest = sql `max(${messages.sentAt})`;
@@ -219,6 +232,7 @@ const toAttachment = (row) => ({
219
232
  mime: row.mime,
220
233
  duration: row.duration,
221
234
  providerRef: parsed(row.providerRef),
235
+ localPath: row.localPath,
222
236
  contact: parsed(row.contact),
223
237
  }),
224
238
  });
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import type { EnvelopeSource, IngestError } from "../../domain/records.js";
2
3
  import type { Author } from "./memories.js";
3
4
  import type { StoreContext } from "./open.js";
@@ -88,7 +89,8 @@ export interface RecordStore {
88
89
  deleted?: boolean;
89
90
  /** 1–500, 100 by default. */
90
91
  limit?: number;
91
- }): Promise<SourceRecord[]>;
92
+ offset?: number;
93
+ }): Promise<ListResult<SourceRecord>>;
92
94
  /**
93
95
  * The relations of live records that point at a record of the account, or at an entity: by its ref, or through a
94
96
  * record mapped to it. An entity's are read across every account, and each names its own. Oldest relation first.
@@ -8,6 +8,7 @@ import { noteError, recordRelationshipsOver } from "./record-relationships.js";
8
8
  import { recordRemapOver } from "./record-remap.js";
9
9
  import { recordRunOver } from "./record-run.js";
10
10
  import { recordWritesOver } from "./record-writes.js";
11
+ import { pageOfRows } from "./rows-page.js";
11
12
  import { storedThing } from "./things.js";
12
13
  import { read, rehearse, write } from "./transaction.js";
13
14
  export { waitingPointer } from "./record-run.js";
@@ -92,12 +93,12 @@ export const recordStoreOver = (context) => {
92
93
  const row = rowOf(key);
93
94
  return row ? sourceRecordOf(row) : undefined;
94
95
  }),
95
- list: async ({ provider, account, type, waiting, unmatched, flagged, entity, batch, deleted, limit = 100 }) => {
96
+ list: async ({ provider, account, type, waiting, unmatched, flagged, entity, batch, deleted, limit = 100, offset = 0, }) => {
96
97
  checkLimit(limit);
97
98
  return read(database, () => {
98
99
  const accountId = findAccountPk(context, { provider, account });
99
100
  if (accountId === undefined)
100
- return [];
101
+ return pageOfRows([], limit);
101
102
  const where = ["r.account_id = ?"];
102
103
  const params = [accountId];
103
104
  const and = (condition, ...values) => {
@@ -122,10 +123,11 @@ export const recordStoreOver = (context) => {
122
123
  and("r.batch_id = ?", batch);
123
124
  if (deleted !== undefined)
124
125
  and(`r.deleted_at IS ${deleted ? "NOT " : ""}NULL`);
125
- return database
126
- .prepare(`${SELECT}WHERE ${where.join(" AND ")} ORDER BY r.updated_at DESC, r.id DESC LIMIT ?`)
127
- .all(...params, limit)
126
+ const rows = database
127
+ .prepare(`${SELECT}WHERE ${where.join(" AND ")} ORDER BY r.updated_at DESC, r.id DESC LIMIT ? OFFSET ?`)
128
+ .all(...params, limit + 1, Math.max(offset, 0))
128
129
  .map(sourceRecordOf);
130
+ return pageOfRows(rows, limit, Math.max(offset, 0));
129
131
  });
130
132
  },
131
133
  incoming: async (target, { limit = 100 } = {}) => {
@@ -0,0 +1,3 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
2
+ /** One page from rows read with `limit + 1`: the extra row only says that another page exists. */
3
+ export declare const pageOfRows: <T>(rows: T[], limit: number, offset?: number) => ListResult<T>;
@@ -0,0 +1,4 @@
1
+ /** One page from rows read with `limit + 1`: the extra row only says that another page exists. */
2
+ export const pageOfRows = (rows, limit, offset = 0) => rows.length > limit
3
+ ? { items: rows.slice(0, limit), hasMore: true, nextOffset: offset + limit }
4
+ : { items: rows, hasMore: false };