@wirecat/cli-core 0.618.0 → 0.620.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 (335) hide show
  1. package/CHANGELOG.md +453 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/deliver.d.ts +5 -2
  5. package/dist/background/deliver.js +30 -12
  6. package/dist/background/report/render.d.ts +3 -1
  7. package/dist/background/report/render.js +3 -1
  8. package/dist/calendar/cli/answers.d.ts +1 -0
  9. package/dist/calendar/cli/answers.js +6 -1
  10. package/dist/calendar/cli/index.js +2 -14
  11. package/dist/calendar/cli/people-link.d.ts +3 -0
  12. package/dist/calendar/cli/people-link.js +23 -0
  13. package/dist/calendar/cli/search-all.d.ts +1 -1
  14. package/dist/calendar/cli/search-all.js +9 -10
  15. package/dist/calendar/index.d.ts +1 -1
  16. package/dist/calendar/index.js +1 -1
  17. package/dist/calendar/mcp/index.d.ts +12 -12
  18. package/dist/calendar/prepare.js +1 -0
  19. package/dist/cli/base-stages-command.d.ts +22 -0
  20. package/dist/cli/base-stages-command.js +174 -0
  21. package/dist/cli/bot/buttons.d.ts +3 -0
  22. package/dist/cli/bot/buttons.js +24 -0
  23. package/dist/cli/bot/messages.js +14 -1
  24. package/dist/cli/bot/port.d.ts +8 -0
  25. package/dist/cli/command-runs.d.ts +2 -0
  26. package/dist/cli/command-runs.js +3 -1
  27. package/dist/cli/config-command.js +6 -1
  28. package/dist/cli/context.js +1 -0
  29. package/dist/cli/contract-templates.js +31 -2
  30. package/dist/cli/group-lock.d.ts +42 -0
  31. package/dist/cli/group-lock.js +130 -0
  32. package/dist/cli/index.d.ts +7 -2
  33. package/dist/cli/index.js +7 -2
  34. package/dist/cli/messenger/backfill-command.js +27 -15
  35. package/dist/cli/messenger/contacts-command.js +12 -4
  36. package/dist/cli/messenger/context.js +1 -0
  37. package/dist/cli/messenger/conversations-command.js +2 -1
  38. package/dist/cli/messenger/doctor-command.js +3 -1
  39. package/dist/cli/messenger/message-items.js +1 -1
  40. package/dist/cli/messenger/models-command.js +1 -1
  41. package/dist/cli/messenger/search-answers.d.ts +5 -5
  42. package/dist/cli/messenger/search-answers.js +9 -20
  43. package/dist/cli/messenger/search-command.d.ts +2 -2
  44. package/dist/cli/messenger/search-command.js +8 -18
  45. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  46. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  47. package/dist/cli/model-catalogue-command.d.ts +3 -1
  48. package/dist/cli/model-catalogue-command.js +48 -2
  49. package/dist/cli/profile.d.ts +8 -0
  50. package/dist/cli/profile.js +25 -0
  51. package/dist/cli/program.js +2 -0
  52. package/dist/cli/runs/search-query.d.ts +1 -1
  53. package/dist/cli/runs/search-query.js +4 -0
  54. package/dist/cli/runs/search.d.ts +5 -1
  55. package/dist/cli/runs/search.js +12 -1
  56. package/dist/cli/search-harder-consents-command.d.ts +18 -0
  57. package/dist/cli/search-harder-consents-command.js +83 -0
  58. package/dist/cli/search-left-out.d.ts +6 -1
  59. package/dist/cli/search-left-out.js +9 -4
  60. package/dist/cli/settings.d.ts +8 -0
  61. package/dist/cli/settings.js +17 -2
  62. package/dist/cli/shared-command-exports.d.ts +16 -0
  63. package/dist/cli/steps.js +0 -6
  64. package/dist/cli/store-recover.d.ts +3 -3
  65. package/dist/cli/store-recover.js +26 -26
  66. package/dist/cli/store-settings.d.ts +2 -0
  67. package/dist/cli/store-settings.js +37 -9
  68. package/dist/cli/templates-command.js +4 -4
  69. package/dist/crm/cli/index.js +40 -8
  70. package/dist/crm/cli/search-all.js +7 -6
  71. package/dist/crm/group-hint.d.ts +8 -0
  72. package/dist/crm/group-hint.js +13 -0
  73. package/dist/crm/source.d.ts +12 -1
  74. package/dist/crm/sync.d.ts +31 -2
  75. package/dist/crm/sync.js +110 -3
  76. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  77. package/dist/crm/testing/acme-scenario.js +170 -0
  78. package/dist/crm/testing/index.d.ts +1 -0
  79. package/dist/crm/testing/index.js +1 -0
  80. package/dist/crm/testing/source-contract.js +12 -0
  81. package/dist/crm/testing/source.d.ts +2 -0
  82. package/dist/crm/testing/source.js +1 -0
  83. package/dist/domain/addresses.d.ts +13 -0
  84. package/dist/domain/addresses.js +63 -0
  85. package/dist/domain/categories.d.ts +3 -0
  86. package/dist/domain/categories.js +2 -0
  87. package/dist/domain/crm.d.ts +23 -0
  88. package/dist/domain/crm.js +7 -0
  89. package/dist/domain/mentions.d.ts +2 -12
  90. package/dist/domain/mentions.js +2 -19
  91. package/dist/domain/models.d.ts +2 -0
  92. package/dist/domain/orders.d.ts +8 -1
  93. package/dist/domain/orders.js +6 -2
  94. package/dist/domain/phones.d.ts +26 -0
  95. package/dist/domain/phones.js +48 -0
  96. package/dist/domain/record-types.d.ts +1 -1
  97. package/dist/domain/record-types.js +1 -0
  98. package/dist/domain/records.d.ts +5 -0
  99. package/dist/domain/ref-summaries.d.ts +39 -0
  100. package/dist/domain/ref-summaries.js +51 -3
  101. package/dist/domain/relations.d.ts +12 -2
  102. package/dist/domain/relations.js +14 -3
  103. package/dist/domain/vcard.d.ts +2 -2
  104. package/dist/domain/vcard.js +4 -10
  105. package/dist/embeddings/models.d.ts +11 -3
  106. package/dist/embeddings/models.js +28 -4
  107. package/dist/entities/business-context.d.ts +149 -0
  108. package/dist/entities/business-context.js +192 -0
  109. package/dist/entities/contact-activity.d.ts +2 -0
  110. package/dist/entities/contact-activity.js +7 -1
  111. package/dist/entities/contact-context.d.ts +160 -0
  112. package/dist/entities/contact-context.js +6 -0
  113. package/dist/entities/deal.d.ts +10 -0
  114. package/dist/entities/deal.js +2 -0
  115. package/dist/entities/hit.d.ts +9 -2
  116. package/dist/entities/hit.js +6 -2
  117. package/dist/entities/index.d.ts +32 -4
  118. package/dist/entities/index.js +5 -0
  119. package/dist/entities/mention.d.ts +4 -3
  120. package/dist/entities/mention.js +2 -1
  121. package/dist/entities/message-transfer.d.ts +4 -2
  122. package/dist/entities/message-transfer.js +2 -2
  123. package/dist/entities/model.d.ts +2 -2
  124. package/dist/entities/model.js +1 -1
  125. package/dist/entities/relationship.d.ts +4 -0
  126. package/dist/entities/relationship.js +4 -0
  127. package/dist/errors/reasons.js +39 -4
  128. package/dist/fetch/page.js +2 -1
  129. package/dist/index.d.ts +3 -2
  130. package/dist/index.js +3 -2
  131. package/dist/meetings/context-store.d.ts +2 -0
  132. package/dist/meetings/findings-rules.d.ts +4 -0
  133. package/dist/meetings/findings-rules.js +5 -2
  134. package/dist/meetings/hit-query.d.ts +1 -1
  135. package/dist/meetings/hit-query.js +2 -2
  136. package/dist/meetings/index.d.ts +1 -0
  137. package/dist/meetings/index.js +1 -0
  138. package/dist/meetings/result-items.d.ts +1 -0
  139. package/dist/meetings/result-items.js +1 -0
  140. package/dist/meetings/store.d.ts +4 -0
  141. package/dist/meetings/store.js +2 -1
  142. package/dist/models/anthropic.js +5 -0
  143. package/dist/models/index.js +22 -5
  144. package/dist/runs/events.d.ts +11 -1
  145. package/dist/runs/events.js +3 -1
  146. package/dist/runs/log-attributes.js +4 -0
  147. package/dist/runs/log-events.js +2 -0
  148. package/dist/runs/recording.d.ts +3 -0
  149. package/dist/runs/recording.js +36 -12
  150. package/dist/runs/run.d.ts +12 -3
  151. package/dist/runs/run.js +32 -13
  152. package/dist/search/account-list.d.ts +6 -0
  153. package/dist/search/account-list.js +9 -3
  154. package/dist/search/groups.d.ts +68 -0
  155. package/dist/search/groups.js +172 -0
  156. package/dist/search/question-period.d.ts +10 -0
  157. package/dist/search/question-period.js +133 -0
  158. package/dist/sends/buttons.d.ts +2 -0
  159. package/dist/sends/buttons.js +6 -1
  160. package/dist/services/account-groups.d.ts +28 -0
  161. package/dist/services/account-groups.js +89 -0
  162. package/dist/services/archive.d.ts +7 -1
  163. package/dist/services/archive.js +19 -3
  164. package/dist/services/business-context.d.ts +113 -0
  165. package/dist/services/business-context.js +156 -0
  166. package/dist/services/communications.d.ts +50 -0
  167. package/dist/services/communications.js +140 -0
  168. package/dist/services/deal-context.d.ts +90 -0
  169. package/dist/services/deal-context.js +131 -0
  170. package/dist/services/deps.d.ts +2 -0
  171. package/dist/services/enrichment.d.ts +12 -2
  172. package/dist/services/enrichment.js +47 -6
  173. package/dist/services/events-search.js +2 -1
  174. package/dist/services/group-guard.d.ts +28 -0
  175. package/dist/services/group-guard.js +131 -0
  176. package/dist/services/index.d.ts +19 -4
  177. package/dist/services/index.js +12 -3
  178. package/dist/services/ingest.d.ts +12 -0
  179. package/dist/services/ingest.js +4 -0
  180. package/dist/services/meaning-model.d.ts +7 -0
  181. package/dist/services/meaning-model.js +20 -0
  182. package/dist/services/meeting-context.d.ts +6 -1
  183. package/dist/services/meeting-context.js +12 -5
  184. package/dist/services/message-resolution.js +2 -3
  185. package/dist/services/messages-meaning.js +4 -5
  186. package/dist/services/messages-search.d.ts +5 -1
  187. package/dist/services/messages-search.js +1 -1
  188. package/dist/services/messages.d.ts +1 -4
  189. package/dist/services/messages.js +0 -2
  190. package/dist/services/metadata.d.ts +1 -1
  191. package/dist/services/model-downloads.d.ts +1 -1
  192. package/dist/services/model-downloads.js +6 -4
  193. package/dist/services/money-context.d.ts +73 -0
  194. package/dist/services/money-context.js +77 -0
  195. package/dist/services/notes-search.d.ts +4 -1
  196. package/dist/services/notes-search.js +19 -7
  197. package/dist/services/organization-context.d.ts +80 -0
  198. package/dist/services/organization-context.js +154 -0
  199. package/dist/services/people.d.ts +22 -6
  200. package/dist/services/people.js +38 -8
  201. package/dist/services/person-business.d.ts +43 -0
  202. package/dist/services/person-business.js +67 -0
  203. package/dist/services/person-context.d.ts +11 -1
  204. package/dist/services/person-context.js +25 -10
  205. package/dist/services/person-preparation.d.ts +5 -1
  206. package/dist/services/person-preparation.js +10 -3
  207. package/dist/services/person-timeline.d.ts +6 -1
  208. package/dist/services/person-timeline.js +10 -2
  209. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  210. package/dist/services/proposals/kinds/identity-link.js +48 -0
  211. package/dist/services/proposals/kinds/orders.js +1 -1
  212. package/dist/services/proposals/registry.js +2 -0
  213. package/dist/services/search-all-deprecated.d.ts +40 -0
  214. package/dist/services/search-all-deprecated.js +10 -0
  215. package/dist/services/search-all-meetings.d.ts +50 -52
  216. package/dist/services/search-all-meetings.js +265 -272
  217. package/dist/services/search-all.d.ts +34 -6
  218. package/dist/services/search-all.js +118 -24
  219. package/dist/services/search-harder.d.ts +64 -0
  220. package/dist/services/search-harder.js +194 -0
  221. package/dist/services/search-kind.d.ts +12 -5
  222. package/dist/services/search-kind.js +49 -10
  223. package/dist/services/text-model-choice.js +1 -1
  224. package/dist/store/accounts.d.ts +18 -0
  225. package/dist/store/accounts.js +18 -3
  226. package/dist/store/chats.d.ts +3 -1
  227. package/dist/store/chats.js +6 -0
  228. package/dist/store/damage.d.ts +43 -10
  229. package/dist/store/damage.js +119 -36
  230. package/dist/store/decisions.js +3 -1
  231. package/dist/store/evidence-findings.d.ts +14 -0
  232. package/dist/store/evidence-findings.js +2 -0
  233. package/dist/store/exports.d.ts +2 -1
  234. package/dist/store/identity-links.d.ts +92 -0
  235. package/dist/store/identity-links.js +6 -0
  236. package/dist/store/index.d.ts +11 -5
  237. package/dist/store/index.js +5 -2
  238. package/dist/store/journal.d.ts +10 -0
  239. package/dist/store/journal.js +33 -0
  240. package/dist/store/marks.d.ts +19 -1
  241. package/dist/store/marks.js +23 -1
  242. package/dist/store/people.d.ts +28 -2
  243. package/dist/store/people.js +15 -1
  244. package/dist/store/sqlite/accounts.js +2 -0
  245. package/dist/store/sqlite/added-sources.d.ts +15 -3
  246. package/dist/store/sqlite/added-sources.js +26 -5
  247. package/dist/store/sqlite/base-stages.d.ts +122 -0
  248. package/dist/store/sqlite/base-stages.js +443 -0
  249. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  250. package/dist/store/sqlite/base-suggest.js +62 -0
  251. package/dist/store/sqlite/business-contracts.js +10 -1
  252. package/dist/store/sqlite/chats.d.ts +2 -0
  253. package/dist/store/sqlite/chats.js +6 -0
  254. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  255. package/dist/store/sqlite/crm-settings.js +56 -13
  256. package/dist/store/sqlite/crm.d.ts +13 -1
  257. package/dist/store/sqlite/crm.js +20 -4
  258. package/dist/store/sqlite/deals.d.ts +33 -0
  259. package/dist/store/sqlite/deals.js +42 -4
  260. package/dist/store/sqlite/decision-requests.js +7 -3
  261. package/dist/store/sqlite/email-index.js +8 -4
  262. package/dist/store/sqlite/evidence-findings.js +29 -5
  263. package/dist/store/sqlite/findings-core.js +4 -2
  264. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  265. package/dist/store/sqlite/identity-link-rows.js +146 -0
  266. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  267. package/dist/store/sqlite/identity-proposals.js +234 -0
  268. package/dist/store/sqlite/involvements.d.ts +1 -1
  269. package/dist/store/sqlite/involvements.js +4 -2
  270. package/dist/store/sqlite/knowledge.js +2 -2
  271. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  272. package/dist/store/sqlite/link-kinds.js +1 -0
  273. package/dist/store/sqlite/link-row.d.ts +6 -0
  274. package/dist/store/sqlite/link-row.js +35 -0
  275. package/dist/store/sqlite/link-source.d.ts +10 -0
  276. package/dist/store/sqlite/link-source.js +16 -0
  277. package/dist/store/sqlite/manifest.js +1 -0
  278. package/dist/store/sqlite/meeting-context-links.js +9 -6
  279. package/dist/store/sqlite/meeting-hit-query.d.ts +5 -0
  280. package/dist/store/sqlite/meeting-hit-query.js +33 -0
  281. package/dist/store/sqlite/meeting-hit-search.js +10 -8
  282. package/dist/store/sqlite/meetings.js +1 -1
  283. package/dist/store/sqlite/memories.js +9 -7
  284. package/dist/store/sqlite/mentions.d.ts +4 -1
  285. package/dist/store/sqlite/mentions.js +14 -9
  286. package/dist/store/sqlite/migrations.generated.js +8 -0
  287. package/dist/store/sqlite/notes.d.ts +8 -2
  288. package/dist/store/sqlite/notes.js +17 -34
  289. package/dist/store/sqlite/open-store.js +3 -0
  290. package/dist/store/sqlite/open.js +11 -2
  291. package/dist/store/sqlite/orders.d.ts +2 -0
  292. package/dist/store/sqlite/orders.js +9 -3
  293. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  294. package/dist/store/sqlite/organization-categories.js +34 -0
  295. package/dist/store/sqlite/organizations.d.ts +5 -1
  296. package/dist/store/sqlite/organizations.js +14 -4
  297. package/dist/store/sqlite/person-links.d.ts +19 -4
  298. package/dist/store/sqlite/person-links.js +49 -11
  299. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  300. package/dist/store/sqlite/person-match-scan.js +251 -0
  301. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  302. package/dist/store/sqlite/person-matcher.js +32 -0
  303. package/dist/store/sqlite/person-preparation.d.ts +7 -3
  304. package/dist/store/sqlite/person-preparation.js +20 -6
  305. package/dist/store/sqlite/proposed-actions.js +6 -0
  306. package/dist/store/sqlite/record-matching.d.ts +2 -8
  307. package/dist/store/sqlite/record-matching.js +8 -40
  308. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  309. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  310. package/dist/store/sqlite/record-relationships.js +243 -0
  311. package/dist/store/sqlite/record-run.d.ts +5 -0
  312. package/dist/store/sqlite/record-run.js +62 -2
  313. package/dist/store/sqlite/record-writes.d.ts +1 -1
  314. package/dist/store/sqlite/record-writes.js +4 -2
  315. package/dist/store/sqlite/records.js +27 -2
  316. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  317. package/dist/store/sqlite/ref-accounts.js +117 -0
  318. package/dist/store/sqlite/ref-summaries.js +5 -1
  319. package/dist/store/sqlite/relation-list.d.ts +4 -1
  320. package/dist/store/sqlite/relation-list.js +22 -4
  321. package/dist/store/sqlite/relation-proposals.d.ts +6 -0
  322. package/dist/store/sqlite/relation-proposals.js +3 -0
  323. package/dist/store/sqlite/relation-roles.js +12 -6
  324. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  325. package/dist/store/sqlite/reported-relations.js +59 -18
  326. package/dist/store/sqlite/schema.d.ts +32 -0
  327. package/dist/store/sqlite/schema.js +3 -0
  328. package/dist/store/sqlite/transaction.js +11 -1
  329. package/dist/store/store.d.ts +3 -0
  330. package/dist/store/store.js +5 -0
  331. package/dist/store/write-events.d.ts +18 -0
  332. package/dist/store/write-events.js +88 -0
  333. package/package.json +3 -3
  334. package/parity.json +37 -16
  335. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -275,3 +275,36 @@ export const matchMeetingText = (tree, text, stemmer) => {
275
275
  };
276
276
  return check(tree);
277
277
  };
278
+ /**
279
+ * The words of `text` the query's positive terms matched, as the text spells them: by the typed beginning, by stem or
280
+ * as a garbled spelling. A word only under NOT is never one, so an excerpt centred on these shows why it is a hit.
281
+ */
282
+ export const matchedMeetingWords = (tree, text, stemmer) => {
283
+ const tokens = normalize(text).match(/[\p{L}\p{N}]+/gu) ?? [];
284
+ let stemmed;
285
+ const stemsOf = () => (stemmed ??= stemmer ? stemmer.explain(meetingStemmableText(text)) : []);
286
+ const found = new Set();
287
+ const word = (term) => {
288
+ for (const token of tokens)
289
+ if (term.whole ? token === term.literal : token.startsWith(term.literal))
290
+ found.add(token);
291
+ for (const { word, stem } of stemsOf())
292
+ if (term.stems.includes(stem))
293
+ found.add(word);
294
+ for (const widened of term.widened)
295
+ if (tokens.includes(widened))
296
+ found.add(widened);
297
+ };
298
+ const visit = (node) => {
299
+ if (node.kind === "speaker")
300
+ return;
301
+ if (node.kind === "boolean")
302
+ for (const part of [...node.must, ...node.should])
303
+ visit(part);
304
+ else
305
+ for (const term of node.words)
306
+ word(term);
307
+ };
308
+ visit(tree);
309
+ return [...found];
310
+ };
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
- import { formatMeetingReference, MEETING_FIELD_NAMES, parseMeetingQuery } from "../../meetings/index.js";
3
+ import { formatMeetingReference, MEETING_FIELD_NAMES, parseMeetingQuery, READ_BUDGET_EXCEEDED, } from "../../meetings/index.js";
4
4
  import { plainQuery } from "../../search/lucene/plain.js";
5
- import { matchMeetingText, meetingQuerySql, resolveMeetingQuery } from "./meeting-hit-query.js";
5
+ import { matchedMeetingWords, matchMeetingText, meetingQuerySql, resolveMeetingQuery } from "./meeting-hit-query.js";
6
6
  import { indexedText } from "./meeting-index-values.js";
7
7
  import { checkMeetingCancelled } from "./meeting-operation.js";
8
8
  import { positiveReadInteger } from "./meeting-reads.js";
@@ -122,9 +122,9 @@ export function meetingHitSearchOver({ database }) {
122
122
  if (after)
123
123
  params.push(after.tier, after.tier, after.started, after.started, after.meeting, after.meeting, after.kind, after.kind, after.id);
124
124
  const sql = `WITH matches AS (${matching}), matching AS (SELECT rid,tier FROM matches h WHERE NOT EXISTS(SELECT 1 FROM meeting_index_pending p WHERE p.id=h.rid/4 AND p.indexable_type=CASE h.rid%4 WHEN 1 THEN 'meeting_transcript_row' WHEN 2 THEN 'meeting_chat_message' ELSE 'meeting_summary' END)), selected AS (SELECT m.id,coalesce(m.started_at,0) AS started FROM meetings m WHERE ${clauses.join(" AND ")}), hits AS (
125
- SELECT h.tier,m.started,m.id AS meeting_id,0 AS kind,r.id,r.start_ms,${bytes("r", ["text"])} AS bytes,t.id AS transcript_id,r.position,t.language,(SELECT count(*) FROM meeting_transcript_rows n WHERE n.meeting_transcript_id=t.id) AS lines_total FROM matching h JOIN meeting_transcript_rows r ON h.rid%4=1 AND r.id=h.rid/4 JOIN meeting_transcripts t ON t.id=r.meeting_transcript_id AND t.superseded_at IS NULL AND t.deleted_at IS NULL JOIN selected m ON m.id=t.meeting_id
126
- UNION ALL SELECT h.tier,m.started,m.id,1,c.id,NULL,${bytes("c", ["text"])},NULL,NULL,NULL,NULL FROM matching h JOIN meeting_chat_messages c ON h.rid%4=2 AND c.id=h.rid/4 JOIN selected m ON m.id=c.meeting_id
127
- UNION ALL SELECT h.tier,m.started,m.id,2,s.id,NULL,${bytes("s", fields)},NULL,NULL,NULL,NULL FROM matching h JOIN meeting_summaries s ON h.rid%4=3 AND s.id=h.rid/4 JOIN selected m ON m.id=s.meeting_id)
125
+ SELECT h.tier,m.started,m.id AS meeting_id,0 AS kind,r.id,r.start_ms,${bytes("r", ["text", "speaker_name"])} AS bytes,t.id AS transcript_id,r.position,t.language,(SELECT count(*) FROM meeting_transcript_rows n WHERE n.meeting_transcript_id=t.id) AS lines_total,r.speaker_name AS speaker FROM matching h JOIN meeting_transcript_rows r ON h.rid%4=1 AND r.id=h.rid/4 JOIN meeting_transcripts t ON t.id=r.meeting_transcript_id AND t.superseded_at IS NULL AND t.deleted_at IS NULL JOIN selected m ON m.id=t.meeting_id
126
+ UNION ALL SELECT h.tier,m.started,m.id,1,c.id,NULL,${bytes("c", ["text"])},NULL,NULL,NULL,NULL,NULL FROM matching h JOIN meeting_chat_messages c ON h.rid%4=2 AND c.id=h.rid/4 JOIN selected m ON m.id=c.meeting_id
127
+ UNION ALL SELECT h.tier,m.started,m.id,2,s.id,NULL,${bytes("s", fields)},NULL,NULL,NULL,NULL,NULL FROM matching h JOIN meeting_summaries s ON h.rid%4=3 AND s.id=h.rid/4 JOIN selected m ON m.id=s.meeting_id)
128
128
  SELECT h.*,${bytes("m", ["title"])}+${bytes("s", ["doc_url"])} AS context_bytes FROM hits h
129
129
  JOIN meetings m ON m.id=h.meeting_id LEFT JOIN meeting_summaries s ON h.kind=2 AND s.id=h.id
130
130
  ${seek} ORDER BY h.tier,h.started DESC,h.meeting_id,h.kind,h.id LIMIT ?`;
@@ -138,7 +138,7 @@ export function meetingHitSearchOver({ database }) {
138
138
  fail("Invalid stored meeting search text size");
139
139
  total += size;
140
140
  if (total > maxReadBytes)
141
- fail("Meeting search exceeds its stored text byte budget");
141
+ fail(READ_BUDGET_EXCEEDED);
142
142
  }
143
143
  checkMeetingCancelled(input.signal);
144
144
  const items = rows.slice(0, limit).map((row) => {
@@ -179,6 +179,7 @@ export function meetingHitSearchOver({ database }) {
179
179
  startMs: row.start_ms === null ? null : Number(row.start_ms),
180
180
  ...(kind === 0
181
181
  ? {
182
+ speakerName: row.speaker === null ? null : String(row.speaker),
182
183
  language: row.language === null ? null : String(row.language),
183
184
  line: Number(row.position) + 1,
184
185
  linesTotal: Number(row.lines_total),
@@ -190,10 +191,11 @@ export function meetingHitSearchOver({ database }) {
190
191
  const corrections = matchMeetingText(tree, item.text, state.stemmer);
191
192
  if (!corrections)
192
193
  return [];
194
+ const matchedWords = matchedMeetingWords(tree, item.text, state.stemmer);
193
195
  return [
194
196
  corrections.length
195
- ? { ...item, match: "corrected", corrections }
196
- : { ...item, match: "words" },
197
+ ? { ...item, match: "corrected", corrections, matchedWords }
198
+ : { ...item, match: "words", matchedWords },
197
199
  ];
198
200
  });
199
201
  if (fresh.length !== items.length)
@@ -447,7 +447,7 @@ const filtered = (filter = {}) => {
447
447
  const [limit, offset] = page(filter);
448
448
  return {
449
449
  sql: `SELECT * FROM meetings${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
450
- ORDER BY coalesce(started_at, 0) DESC, id LIMIT ? OFFSET ?`,
450
+ ORDER BY started_at DESC, id LIMIT ? OFFSET ?`,
451
451
  params: [...params, limit, offset],
452
452
  };
453
453
  };
@@ -182,12 +182,14 @@ export const memoriesStoreOver = (context) => {
182
182
  return row;
183
183
  };
184
184
  /**
185
- * A correction retired the memory if it was ever confirmed. An older store let an agent's proposal retire it at
186
- * once, so a memory superseded only by the one being confirmed is not refused.
185
+ * Another correction retired the memory once it left `proposed`: confirmed, and maybe since then stale or corrected
186
+ * itself. Not `last_verified_at`: the owner's source review sets it on a proposal too. An older store let an agent's
187
+ * proposal retire the memory at once, so a memory superseded only by proposals is not refused.
187
188
  */
188
- const retiredByAnother = (replaced, by) => database
189
- .prepare("SELECT 1 FROM memories WHERE supersedes_id = ? AND id <> ? AND last_verified_at IS NOT NULL LIMIT 1")
190
- .get(replaced, by) !== undefined;
189
+ const retiredByAnother = (replaced, by) => replaced.status === "superseded" &&
190
+ database
191
+ .prepare("SELECT 1 FROM memories WHERE supersedes_id = ? AND id <> ? AND status <> 'proposed' LIMIT 1")
192
+ .get(Number(replaced.id), by) !== undefined;
191
193
  const setStatus = (reference, status, verified) => {
192
194
  const row = rowOf(reference);
193
195
  const at = now();
@@ -247,9 +249,9 @@ export const memoriesStoreOver = (context) => {
247
249
  const confirmNow = (reference, by) => write(database, () => {
248
250
  const row = rowOf(reference);
249
251
  const replaced = row.status === "confirmed" || row.supersedes_id == null ? undefined : rowOf(`memory:${row.supersedes_id}`);
250
- decided(reference, by, replaced?.status === "confirmed");
252
+ decided(reference, by, replaced?.status === "confirmed" || replaced?.status === "superseded");
251
253
  if (replaced !== undefined) {
252
- if (retiredByAnother(Number(replaced.id), Number(row.id)))
254
+ if (retiredByAnother(replaced, Number(row.id)))
253
255
  throw alreadySuperseded(replaced.id);
254
256
  database
255
257
  .prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?")
@@ -26,7 +26,8 @@ export interface StoredMention {
26
26
  /** What was written, read back from the message: never copied into the mention. */
27
27
  written: string;
28
28
  }
29
- export declare const MENTION_STATUSES: readonly ["found", "linked", "dismissed"];
29
+ /** `proposed`: an agent's link of the value to a person waits for the owner as an `identity_link` proposal. */
30
+ export declare const MENTION_STATUSES: readonly ["found", "linked", "proposed", "dismissed"];
30
31
  export type MentionStatus = (typeof MENTION_STATUSES)[number];
31
32
  /** The fields of `mentions list`; a bare word is a `value`. */
32
33
  export declare const MENTION_QUERY: import("@wirecat/cli-base/query").QueryRegistry;
@@ -91,6 +92,8 @@ export interface MentionDecision {
91
92
  target: string | null;
92
93
  /** Every stored mention of this value that now carries the decision. */
93
94
  mentions: number;
95
+ /** An agent's link of the identity to a person waits for the owner as this `identity_link` proposal. */
96
+ proposal?: string;
94
97
  }
95
98
  /** A mention found and allowed to its caller; `chat` is `null` for a text outside a chat. */
96
99
  export interface LocatedMention {
@@ -3,14 +3,16 @@ import { defineQuery } from "@wirecat/cli-base/query";
3
3
  import { MENTION_KINDS, siteOf } from "../../domain/mentions.js";
4
4
  import { findNames, nameIndex } from "../../domain/person-names.js";
5
5
  import { createStemmer } from "../../search/stem.js";
6
+ import { linkOrPropose } from "./identity-proposals.js";
6
7
  import { mentionText } from "./lucene-fields.js";
7
8
  import { knownPeople, participants, SOURCE_TYPES, SOURCES, sourceOf, telegramLink, writer, } from "./mention-drain.js";
8
- import { linkIdentityToPerson, personByUid } from "./person-links.js";
9
+ import { personByUid } from "./person-links.js";
9
10
  import { valueMatch } from "./phone-countries.js";
10
11
  import { placeOf } from "./place-key.js";
11
12
  import { queryFilter } from "./query-filter.js";
12
13
  import { writeBatch } from "./transaction.js";
13
- export const MENTION_STATUSES = ["found", "linked", "dismissed"];
14
+ /** `proposed`: an agent's link of the value to a person waits for the owner as an `identity_link` proposal. */
15
+ export const MENTION_STATUSES = ["found", "linked", "proposed", "dismissed"];
14
16
  /** The fields of `mentions list`; a bare word is a `value`. */
15
17
  export const MENTION_QUERY = defineQuery({
16
18
  entity: "mention",
@@ -237,13 +239,16 @@ export const confirmMention = (context, mention, owner, by) => {
237
239
  const identity = Number(database
238
240
  .prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?")
239
241
  .get(mention.kind, mention.value)?.id);
240
- if ("person" in owner)
241
- linkIdentityToPerson(context, identity, owner.person, { method: "mention", by: by.by });
242
- else
243
- database
244
- .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
245
- "VALUES (?, ?, 'mention', ?, ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING")
246
- .run(identity, owner.organization, by.by, now, now);
242
+ if ("person" in owner) {
243
+ const proposal = linkOrPropose(context, identity, owner.person, { method: "mention", by: by.by });
244
+ const status = proposal === undefined ? "linked" : "proposed";
245
+ const decided = decide(database, mention, status, { type: "identity", id: identity }, by, now);
246
+ return proposal === undefined ? decided : { ...decided, proposal };
247
+ }
248
+ database
249
+ .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
250
+ "VALUES (?, ?, 'mention', ?, ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING")
251
+ .run(identity, owner.organization, by.by, now, now);
247
252
  return decide(database, mention, "linked", { type: "identity", id: identity }, by, now);
248
253
  }
249
254
  if (mention.kind === "document") {
@@ -1216,5 +1216,13 @@ export const GENERATED = [
1216
1216
  "CREATE TABLE `templates_history` (\n\t`id` integer PRIMARY KEY,\n\t`key` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`language` text NOT NULL,\n\t`body` text NOT NULL,\n\t`saved_at` integer NOT NULL,\n\t`saved_by` text NOT NULL,\n\t`replaced_at` integer NOT NULL\n);",
1217
1217
  "CREATE INDEX `templates_history_by_key_channel_language_id` ON `templates_history` (`key`,`channel`,`language`,`id`);"
1218
1218
  ]
1219
+ },
1220
+ {
1221
+ "name": "20261108190101_version-60-base-stages",
1222
+ "statements": [
1223
+ "ALTER TABLE `pipeline_stages` ADD `base_stage_id` integer REFERENCES pipeline_stages(id);",
1224
+ "ALTER TABLE `pipeline_stages` ADD `base_confirmed` integer DEFAULT 0 NOT NULL;",
1225
+ "CREATE INDEX `pipeline_stages_by_base_stage_id` ON `pipeline_stages` (`base_stage_id`);"
1226
+ ]
1219
1227
  }
1220
1228
  ];
@@ -6,6 +6,7 @@ import type { AddedSources } from "./added-sources.js";
6
6
  import { type DocumentMetadata } from "./document-metadata.js";
7
7
  import { type ImportedDocuments } from "./imported-documents.js";
8
8
  import { LINK_KINDS, LINK_ORIGINS, type LINK_SOURCES } from "./link-kinds.js";
9
+ export { linkOf, thingRef } from "./link-row.js";
9
10
  import type { NoteSearch } from "./note-search.js";
10
11
  import type { StoreContext } from "./open.js";
11
12
  import { type Label } from "./tags.js";
@@ -200,12 +201,17 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
200
201
  type Row = Record<string, unknown>;
201
202
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
202
203
  export declare const targetKey: (text: string) => string;
204
+ /**
205
+ * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
206
+ * a citation reads back the words it cited and the source check sees the change.
207
+ */
208
+ export declare const keepRevision: (database: CacheDatabase, row: Row, at: number) => {
209
+ changes: number;
210
+ };
203
211
  export declare const documentOf: (row: Row) => Note;
204
212
  export declare const noteOf: (row: Row) => Note;
205
213
  /** A document or note row by its typed reference, or `undefined`. */
206
214
  export declare const noteRowOf: (database: CacheDatabase, reference: string) => Note | undefined;
207
- export declare const thingRef: (database: CacheDatabase, type: unknown, id: unknown) => string | null;
208
- export declare const linkOf: (database: CacheDatabase, row: Row) => Link;
209
215
  /** The row a reference names, refused when the store holds none. */
210
216
  export declare const requiredThing: (database: CacheDatabase, reference: string, what?: string) => Thing;
211
217
  /**
@@ -3,7 +3,7 @@ import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
3
3
  import { googleDocumentLinks } from "../../domain/google-documents.js";
4
4
  import { ADDED_PROVIDER, DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, notAdded, } from "../../domain/providers.js";
5
5
  import { parseReference } from "../../domain/references.js";
6
- import { isEngagement, isRelationKind } from "../../domain/relations.js";
6
+ import { isRelationKind } from "../../domain/relations.js";
7
7
  import { normalizeTag } from "../../domain/tags.js";
8
8
  import { assertMayWithdraw } from "../decisions.js";
9
9
  import { fold } from "../normalize.js";
@@ -15,12 +15,14 @@ import { PREFERRED_FILE, syncFile } from "./files.js";
15
15
  import { importedDocumentWhere } from "./imported-documents.js";
16
16
  import { LINK_KINDS, LINK_ORIGINS, linkKind } from "./link-kinds.js";
17
17
  import { reviewLink } from "./link-reviews.js";
18
+ import { linkOf } from "./link-row.js";
19
+ export { linkOf, thingRef } from "./link-row.js";
18
20
  import { currentPerson, idsOf } from "./merged-persons.js";
19
21
  import { dateFileNotes } from "./note-dates.js";
20
22
  import { holdingText } from "./note-index.js";
21
23
  import { addTags, ensureTag, labelsOf } from "./tags.js";
22
24
  import { oneOf, textOf } from "./text-input.js";
23
- import { referenceOfThing, storedThing, thingOf } from "./things.js";
25
+ import { thingOf } from "./things.js";
24
26
  import { write } from "./transaction.js";
25
27
  export const NOTE_FORMATS = ["obsidian", "markdown"];
26
28
  export { LINK_ORIGINS } from "./link-kinds.js";
@@ -28,6 +30,13 @@ const iso = (value) => new Date(Number(value)).toISOString();
28
30
  const optionalIso = (value) => (value == null ? null : iso(value));
29
31
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
30
32
  export const targetKey = (text) => fold(text).trim().replace(/^@/, "");
33
+ /**
34
+ * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
35
+ * a citation reads back the words it cited and the source check sees the change.
36
+ */
37
+ export const keepRevision = (database, row, at) => database
38
+ .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at) VALUES (?, ?, ?, ?)")
39
+ .run(Number(row.id), String(row.body ?? ""), Number(row.revision), at);
31
40
  export const documentOf = (row) => ({
32
41
  id: String(row.id),
33
42
  ref: `document:${row.id}`,
@@ -71,33 +80,6 @@ export const noteRowOf = (database, reference) => {
71
80
  return noteOf(database.prepare("SELECT * FROM notes WHERE id = ?").get(thing.id));
72
81
  return undefined;
73
82
  };
74
- export const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
75
- export const linkOf = (database, row) => {
76
- const metadata = row.metadata == null ? {} : JSON.parse(String(row.metadata));
77
- return {
78
- id: String(row.id),
79
- from: thingRef(database, row.from_type, row.from_id),
80
- to: thingRef(database, row.to_type, row.to_id),
81
- kind: row.kind,
82
- anchor: row.anchor == null ? null : String(row.anchor),
83
- origin: row.source,
84
- targetText: row.target_text == null ? null : String(row.target_text),
85
- role: row.role == null ? null : String(row.role),
86
- purpose: row.purpose == null ? null : String(row.purpose),
87
- evidence: row.evidence == null ? null : String(row.evidence),
88
- provenance: typeof metadata.provenance === "string" ? metadata.provenance : null,
89
- confirmed: Number(row.confirmed) === 1,
90
- createdAt: iso(row.created_at),
91
- ...(row.account_id == null ? {} : { accountId: Number(row.account_id) }),
92
- ...(row.starts_at == null ? {} : { startsAt: Number(row.starts_at) }),
93
- ...(row.ends_at == null ? {} : { endsAt: Number(row.ends_at) }),
94
- ...(row.deleted_at == null ? {} : { deletedAt: Number(row.deleted_at) }),
95
- ...(typeof metadata.position === "string" ? { position: metadata.position } : {}),
96
- ...(typeof metadata.roleNote === "string" ? { roleNote: metadata.roleNote } : {}),
97
- ...(isEngagement(metadata.engagement) ? { engagement: metadata.engagement } : {}),
98
- ...(typeof metadata.overrides === "number" ? { overrides: metadata.overrides } : {}),
99
- };
100
- };
101
83
  /** The row a reference names, refused when the store holds none. */
102
84
  export const requiredThing = (database, reference, what = "the target") => {
103
85
  const thing = thingOf(database, reference);
@@ -442,9 +424,7 @@ export const notesStoreOver = (context) => {
442
424
  found.deleted_at == null;
443
425
  if (!same) {
444
426
  if ((found.body ?? "") !== text)
445
- database
446
- .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at) VALUES (?, ?, ?, ?)")
447
- .run(id, String(found.body ?? ""), Number(found.revision), at);
427
+ keepRevision(database, found, at);
448
428
  database
449
429
  .prepare("UPDATE documents SET title = ?, body = ?, front_matter = ?, content_hash = ?, metadata = ?, language = ?, " +
450
430
  "revision = revision + ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
@@ -637,7 +617,9 @@ export const notesStoreOver = (context) => {
637
617
  if (reference === undefined)
638
618
  return { known: true, type: null, id: null };
639
619
  const thing = thingOf(database, reference);
640
- return thing ? { known: true, type: thing.type, id: thing.id } : { known: false, type: null, id: null };
620
+ return thing
621
+ ? { known: true, type: thing.type, id: idsOf(database, thing.type, thing.id) }
622
+ : { known: false, type: null, id: null };
641
623
  };
642
624
  const from = pair(options.from);
643
625
  const to = pair(options.to);
@@ -651,7 +633,8 @@ export const notesStoreOver = (context) => {
651
633
  ...(options.confirmed === undefined ? [] : [{ sql: "confirmed = ?", value: options.confirmed ? 1 : 0 }]),
652
634
  ];
653
635
  return database
654
- .prepare("SELECT * FROM links WHERE (? IS NULL OR (from_type = ? AND from_id = ?)) AND (? IS NULL OR (to_type = ? AND to_id = ?)) " +
636
+ .prepare("SELECT * FROM links WHERE (? IS NULL OR (from_type = ? AND from_id IN (SELECT value FROM json_each(?)))) " +
637
+ "AND (? IS NULL OR (to_type = ? AND to_id IN (SELECT value FROM json_each(?)))) " +
655
638
  `AND (? = 0 OR to_id IS NULL)${filters.map(({ sql }) => ` AND (${sql})`).join("")} ORDER BY created_at, id LIMIT 5000`)
656
639
  .all(from.type, from.type, from.id, to.type, to.type, to.id, options.unresolved ? 1 : 0, ...filters.map(({ value }) => value))
657
640
  .map((row) => linkOf(database, row));
@@ -2,6 +2,7 @@ import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync }
2
2
  import { dirname } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  import { DEFAULT_DECISION_POLICY } from "../decisions.js";
5
+ import { noteShmWithoutWal, watchJournal } from "../journal.js";
5
6
  import { refuseDamagedStore } from "../marks.js";
6
7
  import { migrate } from "../migrations.js";
7
8
  import { storeCapable } from "../open.js";
@@ -83,11 +84,13 @@ export const openStoreContext = async (options = {}) => {
83
84
  else {
84
85
  createWritable(file);
85
86
  refuseDamagedStore(file, command);
87
+ noteShmWithoutWal(file, command ?? "unknown");
86
88
  }
87
89
  const opened = readOnly ? await openReadable(file, options) : await openSqlite(file, { readOnly });
88
90
  const database = opened.database;
89
91
  try {
90
92
  if (!readOnly) {
93
+ watchJournal(database, file, command ?? "unknown");
91
94
  const notice = migrate(database, {
92
95
  now,
93
96
  command,
@@ -1,6 +1,7 @@
1
1
  import { PRAGMAS } from "../driver.js";
2
2
  import { refuseOwnerStoreInTests } from "../path.js";
3
3
  import { quietSqliteWarning } from "../sqlite-warning.js";
4
+ import { countWrites, shareCounts } from "../write-events.js";
4
5
  /**
5
6
  * One SQLite connection, seen two ways: the `CacheDatabase` seam the hand-written SQL and the
6
7
  * migration runner use, and Drizzle. Each Drizzle driver imports its runtime at the top of its
@@ -25,7 +26,11 @@ const openUnderNode = async (path, readOnly) => {
25
26
  const { cacheOverNodeSqlite, nodeClient } = await import("../drivers/node-sqlite.js");
26
27
  const client = await nodeClient(path, { readOnly });
27
28
  try {
28
- return { database: cacheOverNodeSqlite(client), orm: drizzle({ client }) };
29
+ if (!readOnly)
30
+ countWrites(client, ["prepare"], () => client.isTransaction);
31
+ const database = cacheOverNodeSqlite(client);
32
+ shareCounts(client, database);
33
+ return { database, orm: drizzle({ client }) };
29
34
  }
30
35
  catch (error) {
31
36
  client.close();
@@ -37,7 +42,11 @@ const openUnderBun = async (path, readOnly) => {
37
42
  const { drizzle } = (await import("./drizzle/bun.js"));
38
43
  const client = await bunClient(path, readOnly ? { readonly: true, create: false } : undefined);
39
44
  try {
40
- return { database: cacheOverBunSqlite(client), orm: drizzle({ client }) };
45
+ if (!readOnly)
46
+ countWrites(client, ["prepare", "query"], () => client.inTransaction);
47
+ const database = cacheOverBunSqlite(client);
48
+ shareCounts(client, database);
49
+ return { database, orm: drizzle({ client }) };
41
50
  }
42
51
  catch (error) {
43
52
  client.close();
@@ -69,6 +69,8 @@ export interface OrderFilter {
69
69
  status?: OrderStatus;
70
70
  purpose?: OrderPurpose;
71
71
  customer?: string;
72
+ /** `person:` or `organization:` the order is from. */
73
+ supplier?: string;
72
74
  /** The shop's name in any letter case; with `number`, how a later mail finds its order. */
73
75
  supplierName?: string;
74
76
  number?: string;
@@ -18,12 +18,16 @@ export const orderOperationsOver = (context) => {
18
18
  const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
19
19
  const moneyLines = moneyLinesOver(context);
20
20
  const orderOf = (row) => {
21
+ const customer = partyOf(row.customer_type, row.customer_id);
22
+ const direction = row.direction;
21
23
  const currency = row.currency == null ? null : String(row.currency);
22
24
  const total = row.total == null || currency === null ? null : Number(row.total);
23
25
  const fields = {
24
26
  id: Number(row.id),
25
27
  number: row.number == null ? null : String(row.number),
26
28
  supplierName: String(row.supplier_name),
29
+ direction,
30
+ customerName: customer?.name ?? null,
27
31
  total,
28
32
  currency,
29
33
  status: row.status,
@@ -33,7 +37,7 @@ export const orderOperationsOver = (context) => {
33
37
  id: String(row.id),
34
38
  ref: `order:${row.id}`,
35
39
  title: orderTitle(fields),
36
- customer: partyOf(row.customer_type, row.customer_id),
40
+ customer,
37
41
  purpose: row.purpose,
38
42
  supplier: partyOf(row.supplier_type, row.supplier_id),
39
43
  supplierName: fields.supplierName,
@@ -46,7 +50,7 @@ export const orderOperationsOver = (context) => {
46
50
  invoice: row.invoice_id == null ? null : `invoice:${row.invoice_id}`,
47
51
  payment: row.payment_id == null ? null : `payment:${row.payment_id}`,
48
52
  sourceUrl: row.source_url == null ? null : String(row.source_url),
49
- direction: row.direction,
53
+ direction,
50
54
  contract: row.contract_id == null ? null : `contract:${row.contract_id}`,
51
55
  deal: row.deal_id == null ? null : `deal:${row.deal_id}`,
52
56
  ...reviewedOf(row, "order"),
@@ -159,6 +163,7 @@ export const orderOperationsOver = (context) => {
159
163
  list: (filter = {}) => {
160
164
  const project = filter.project === undefined ? null : projectId(database, filter.project);
161
165
  const customer = partyThing(filter.customer, "the customer");
166
+ const supplier = partyThing(filter.supplier, "the supplier");
162
167
  const by = proposedBySql("o.author_type", "o.author_id", filter.proposedBy);
163
168
  const status = filter.status === undefined ? null : statusOf(filter.status);
164
169
  const purpose = filter.purpose === undefined ? null : oneOf(filter.purpose, ORDER_PURPOSES, "a purpose");
@@ -170,8 +175,9 @@ export const orderOperationsOver = (context) => {
170
175
  .prepare(`${ORDERS} WHERE o.deleted_at IS NULL AND (? IS NULL OR o.status = ?) AND (? IS NULL OR o.purpose = ?) ` +
171
176
  "AND (? IS NULL OR o.review = ?) AND (? IS NULL OR o.project_id = ?) AND (? IS NULL OR o.number = ?) " +
172
177
  "AND (? IS NULL OR (o.customer_type = ? AND o.customer_id = ?)) " +
178
+ "AND (? IS NULL OR (o.supplier_type = ? AND o.supplier_id = ?)) " +
173
179
  `AND ${by.sql} ORDER BY o.created_at DESC, o.id DESC`)
174
- .all(status, status, purpose, purpose, review, review, project, project, number, number, customer?.type ?? null, customer?.type ?? null, customer?.id ?? null, ...by.params);
180
+ .all(status, status, purpose, purpose, review, review, project, project, number, number, customer?.type ?? null, customer?.type ?? null, customer?.id ?? null, supplier?.type ?? null, supplier?.type ?? null, supplier?.id ?? null, ...by.params);
175
181
  return rows
176
182
  .filter((row) => shop === null || fold(String(row.supplier_name)) === shop)
177
183
  .slice(0, limit)
@@ -0,0 +1,18 @@
1
+ import { type Category } from "../../domain/categories.js";
2
+ import type { AccountKey } from "../types.js";
3
+ /** Which organizations `organizations` answers: those of one category, read from relationships in `accounts` only. */
4
+ export interface OrganizationFilter {
5
+ category?: Category;
6
+ /** Relationships a source account reported count only from these; the owner's always count. Every one when absent. */
7
+ accounts?: AccountKey[];
8
+ }
9
+ /**
10
+ * The category as SQL over `organizations o`, derived from usable relationships at `now` (NEED-2377), as
11
+ * `organizationCategories` derives it: `client` is `customer-of` an own organization, `supplier` one an own
12
+ * organization is `customer-of`, `partner` `partner-of` one, `employer` one the owner's person is `member-of` as
13
+ * employee, contractor or founder.
14
+ */
15
+ export declare const categorySql: ({ category, accounts }: OrganizationFilter, now: number) => {
16
+ sql: string;
17
+ params: string[];
18
+ } | undefined;
@@ -0,0 +1,34 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { CATEGORIES } from "../../domain/categories.js";
3
+ import { usableLinkSql } from "../../domain/relations.js";
4
+ import { linkKind } from "./link-kinds.js";
5
+ const OWN = "(SELECT id FROM organizations WHERE deleted_at IS NULL AND json_extract(metadata, '$.own') = 1)";
6
+ const EMPLOYED = "('employee', 'contractor', 'founder')";
7
+ /**
8
+ * The category as SQL over `organizations o`, derived from usable relationships at `now` (NEED-2377), as
9
+ * `organizationCategories` derives it: `client` is `customer-of` an own organization, `supplier` one an own
10
+ * organization is `customer-of`, `partner` `partner-of` one, `employer` one the owner's person is `member-of` as
11
+ * employee, contractor or founder.
12
+ */
13
+ export const categorySql = ({ category, accounts }, now) => {
14
+ if (category === undefined)
15
+ return undefined;
16
+ if (!CATEGORIES.includes(category))
17
+ throw new CliError("validation_error", `a category is one of ${CATEGORIES.join(", ")}`);
18
+ const keys = accounts?.map(({ provider, account }) => `${provider}:${account}`) ?? [];
19
+ const reporter = accounts === undefined
20
+ ? ""
21
+ : ` AND (l.account_id IS NULL OR l.account_id IN (SELECT id FROM accounts WHERE provider || ':' || external_id ` +
22
+ `IN (${keys.map(() => "?").join(", ") || "NULL"})))`;
23
+ const usable = `${usableLinkSql("l", now)}${reporter}`;
24
+ const org = (end) => `l.${end}_type = 'organization'`;
25
+ const where = {
26
+ client: `l.kind = ${linkKind("customer-of")} AND ${org("from")} AND l.from_id = o.id AND ${org("to")} AND l.to_id IN ${OWN}`,
27
+ supplier: `l.kind = ${linkKind("customer-of")} AND ${org("from")} AND l.from_id IN ${OWN} AND ${org("to")} AND l.to_id = o.id`,
28
+ partner: `l.kind = ${linkKind("partner-of")} AND ${org("from")} AND ${org("to")} AND ` +
29
+ `((l.from_id = o.id AND l.to_id IN ${OWN}) OR (l.to_id = o.id AND l.from_id IN ${OWN}))`,
30
+ employer: `l.kind = ${linkKind("member-of")} AND l.from_type = 'person' AND l.from_id IN (SELECT id FROM persons WHERE ` +
31
+ `owner = 1) AND ${org("to")} AND l.to_id = o.id AND l.role IN ${EMPLOYED}`,
32
+ }[category];
33
+ return { sql: `EXISTS (SELECT 1 FROM links l WHERE ${where} AND ${usable})`, params: keys };
34
+ };
@@ -1,10 +1,12 @@
1
1
  import { type QueryAst } from "@wirecat/cli-base/query";
2
2
  import type { Organization } from "./knowledge.js";
3
3
  import type { StoreContext } from "./open.js";
4
+ import { type OrganizationFilter } from "./organization-categories.js";
4
5
  type Row = Record<string, unknown>;
5
6
  export declare const organizationOf: (row: Row) => Organization;
6
7
  export interface OrganizationsStore {
7
- organizations(query?: QueryAst): Promise<Organization[]>;
8
+ /** At most 500, by name; with `filter.category`, only that category's, chosen in SQL. */
9
+ organizations(query?: QueryAst, filter?: OrganizationFilter): Promise<Organization[]>;
8
10
  /** Renames an organization given as `organization:<id>` or by its id; its kind and scope stay. */
9
11
  updateOrganization(organization: string, input: {
10
12
  name: string;
@@ -17,6 +19,8 @@ export interface OrganizationsStore {
17
19
  ref: string;
18
20
  own: boolean;
19
21
  }>;
22
+ /** The owner's own companies: the owner's mark, else a CRM's own-company flag (`metadata.own`). */
23
+ ownOrganizations(): Promise<Organization[]>;
20
24
  }
21
25
  export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
22
26
  export {};
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { evaluate, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { ORGANIZATIONS_QUERY } from "../knowledge-query.js";
4
+ import { categorySql } from "./organization-categories.js";
4
5
  import { queryFilter } from "./query-filter.js";
5
6
  import { thingOf } from "./things.js";
6
7
  import { write } from "./transaction.js";
@@ -13,10 +14,14 @@ export const organizationOf = (row) => ({
13
14
  createdAt: new Date(Number(row.created_at)).toISOString(),
14
15
  });
15
16
  export const organizationsStoreOver = ({ database, now }) => ({
16
- organizations: async (query) => {
17
+ organizations: async (query, filter = {}) => {
18
+ const category = categorySql(filter, now());
19
+ const inCategory = category ? ` AND ${category.sql}` : "";
17
20
  // `lower()` folds ASCII only and an organization has no folded copy, so a name filter runs on the rows.
18
21
  if (query && walkQuery(query.root).some((node) => node.field === "name"))
19
- return database.prepare("SELECT * FROM organizations WHERE deleted_at IS NULL ORDER BY name, id").all()
22
+ return database
23
+ .prepare(`SELECT * FROM organizations o WHERE deleted_at IS NULL${inCategory} ORDER BY name, id`)
24
+ .all(...(category?.params ?? []))
20
25
  .map(organizationOf)
21
26
  .filter((one) => evaluate(query, ORGANIZATIONS_QUERY.fields, { ...one, created_at: one.createdAt }))
22
27
  .slice(0, 500);
@@ -28,10 +33,15 @@ export const organizationsStoreOver = ({ database, now }) => ({
28
33
  created_at: { type: "time", sql: "created_at" },
29
34
  });
30
35
  return database
31
- .prepare(`SELECT * FROM organizations WHERE deleted_at IS NULL${where ? ` AND (${where.sql})` : ""} ORDER BY name, id LIMIT 500`)
32
- .all(...(where?.params ?? []))
36
+ .prepare(`SELECT * FROM organizations o WHERE deleted_at IS NULL${where ? ` AND (${where.sql})` : ""}${inCategory} ` +
37
+ "ORDER BY name, id LIMIT 500")
38
+ .all(...(where?.params ?? []), ...(category?.params ?? []))
33
39
  .map(organizationOf);
34
40
  },
41
+ ownOrganizations: async () => database
42
+ .prepare("SELECT * FROM organizations WHERE deleted_at IS NULL AND json_extract(metadata, '$.own') = 1 ORDER BY name, id")
43
+ .all()
44
+ .map(organizationOf),
35
45
  updateOrganization: async (organization, { name }) => write(database, () => {
36
46
  const title = name.trim();
37
47
  if (!title || title.length > 200)
@@ -24,14 +24,29 @@ export declare const linkIdentityToPerson: (context: StoreContext, identityPk: n
24
24
  * name: a caller links only what someone decided belongs together, and says how in `method`.
25
25
  */
26
26
  export declare const linkIdentities: (context: StoreContext, person: IdentityRef, other: IdentityRef, options: LinkOptions) => PersonRecord;
27
- /** Moves every identity of `from` to `to`, as `linkIdentities` does once it has found both people. */
28
- export declare const mergePerson: (context: StoreContext, from: number, to: number, options: LinkOptions) => void;
27
+ /** The person `mergePerson(one, other)` keeps: `other`, unless `one` is the owner's. */
28
+ export declare const survivorOf: (context: StoreContext, one: number, other: number) => number;
29
+ /**
30
+ * Moves every identity of `from` to `to`, as `linkIdentities` does once it has found both people, and gives the
31
+ * person that stays. The owner's person always stays: merging it away would leave the owner with no identity.
32
+ * Proposals naming either person are brought up to date.
33
+ */
34
+ export declare const mergePerson: (context: StoreContext, one: number, other: number, options: LinkOptions) => number;
35
+ /** Keeps the address an identity's source gave it, so a later contact with it counts this one. */
36
+ export declare const noteAddress: (context: StoreContext, ref: IdentityRef, address: string) => void;
29
37
  /**
30
38
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
31
39
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
32
- * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
40
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart. A role address such
41
+ * as `info@` joins no one; the scan proposes its people instead. A pair the owner rejected is not joined either: it is
42
+ * given back, so the caller proposes it when the evidence is new to the owner.
33
43
  */
34
- export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => void;
44
+ export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => {
45
+ identity: number;
46
+ with: number;
47
+ from: number;
48
+ to: number;
49
+ } | undefined;
35
50
  /** Gives the identity a person of its own again; the ones left keep theirs. */
36
51
  export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options: LinkOptions) => PersonRecord;
37
52
  /** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */