@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
@@ -3,9 +3,9 @@ import { CliError } from "@wirecat/cli-base";
3
3
  import { annotate } from "@wirecat/cli-base/commands";
4
4
  import { Command } from "commander";
5
5
  import { fileSchemaOf } from "../store/compatibility.js";
6
- import { explainDamage } from "../store/damage.js";
6
+ import { lossUnknown, storeDamageReport } from "../store/damage.js";
7
7
  import { storeHealth } from "../store/health.js";
8
- import { readDamageMark, readHealthMark, recordDeepCheck } from "../store/marks.js";
8
+ import { readDamageMark, readHealthMark, readJournalMark, recordDeepCheck } from "../store/marks.js";
9
9
  import { storePath } from "../store/path.js";
10
10
  import { activeTimers, recoverStore, sqlite3Program, storeHolders, tableRows, } from "../store/recover.js";
11
11
  import { openSqlite } from "../store/store.js";
@@ -50,20 +50,23 @@ export const storeRecoveryCheck = async (env, command, version) => {
50
50
  }
51
51
  }
52
52
  catch { }
53
+ const journal = readJournalMark(path);
53
54
  recordDeepCheck(path, health, { cli: command, ...(version ? { version } : {}), schema });
54
55
  const mark = readDamageMark(path);
55
- const explanation = explainDamage(health, command, mark);
56
+ const lastKnownGood = readHealthMark(path)?.last_ok_at ?? null;
56
57
  const inUse = storeHolders(path) ?? null;
57
58
  const timers = activeTimers() ?? null;
58
59
  const sqlite3 = sqlite3Program();
59
- const next = health.ok
60
- ? []
61
- : [
62
- ...(timers?.length ? [stopTimers(timers)] : []),
63
- ...(inUse ?? []).map(({ pid, name }) => `stop ${name} (process ${pid}): it has the store open`),
64
- ...(sqlite3.usable ? [] : ["install sqlite3 3.43 or newer (apt install sqlite3, brew install sqlite)"]),
65
- `${command} store recover run`,
66
- ];
60
+ const report = storeDamageReport({
61
+ health,
62
+ command,
63
+ mark,
64
+ journal,
65
+ lastOkAt: lastKnownGood,
66
+ holders: inUse,
67
+ timers,
68
+ sqlite3Usable: sqlite3.usable,
69
+ });
67
70
  return {
68
71
  path,
69
72
  exists: true,
@@ -76,13 +79,13 @@ export const storeRecoveryCheck = async (env, command, version) => {
76
79
  .map(({ name, error }) => ({ name, ...(error ? { error } : {}) })),
77
80
  invalidJson: health.invalidJson ?? [],
78
81
  rows,
79
- explanation,
82
+ report,
80
83
  damageMark: mark ? (({ inode: _, ...seen }) => seen)(mark) : null,
81
- lastKnownGood: readHealthMark(path)?.last_ok_at ?? null,
84
+ lastKnownGood,
82
85
  inUse,
83
86
  timers,
84
87
  sqlite3: { version: sqlite3.version, usable: sqlite3.usable },
85
- next,
88
+ next: report?.steps.map((step) => step.command) ?? [],
86
89
  };
87
90
  };
88
91
  /** `store recover run`: refuses while a WireCat timer is scheduled, so none writes to the file being replaced. */
@@ -132,16 +135,12 @@ export const recoveryNotes = (answer) => {
132
135
  if ("keptAt" in answer) {
133
136
  const lost = answer.lost.map(({ table, before, read, kept, goneAtLeast, seenIn }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}` +
134
137
  (goneAtLeast > 0 ? `; at least ${goneAtLeast} rows are gone (the index ${seenIn} lists them)` : ""));
135
- const since = answer.lastKnownGood
136
- ? `since the last deep check that passed (${answer.lastKnownGood})`
137
- : "since the store was made (no deep check that passed is on record)";
138
138
  return [
139
139
  `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
140
140
  ...lost,
141
141
  ...Object.entries(answer.placed).map(([table, rows]) => `${table}: ${rows} rows found on pages no table claimed were put back`),
142
142
  ...refetchNotes(answer.refetch),
143
- `${lost.some((line) => line.includes("are gone")) ? "more rows may be gone" : "how many rows were lost is unknown"}: ` +
144
- `damage can take rows written ${since} without leaving a trace; a sync fetches again what the servers still hold`,
143
+ lossUnknown(answer.lastKnownGood, lost.some((line) => line.includes("are gone"))),
145
144
  ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
146
145
  ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON — ${required ? "those rows were dropped" : "set to empty"}`),
147
146
  ...answer.next.map((line) => `next: ${line}`),
@@ -149,15 +148,16 @@ export const recoveryNotes = (answer) => {
149
148
  }
150
149
  if (!answer.exists)
151
150
  return ["no store yet"];
152
- if (answer.ok)
151
+ const report = answer.report;
152
+ if (!report)
153
153
  return [`the store is healthy (checked every page and search index in ${answer.seconds} s)`];
154
- const why = answer.explanation;
155
154
  return [
156
- ...(why ? [why.what, ...why.impact, why.externalUnaffected] : []),
157
- answer.lastKnownGood
158
- ? `the store last passed a deep check at ${answer.lastKnownGood}`
159
- : "no deep check that passed is on record for this store",
160
- ...answer.next.map((line) => `next: ${line}`),
155
+ report.whatHappened,
156
+ ...report.impact,
157
+ report.externalDataSafe,
158
+ report.loss,
159
+ ...report.likelyCauses.map(({ cause, check }) => `maybe: ${cause} — check: ${check}`),
160
+ ...report.steps.map(({ command, why, destructive }) => `next: ${command} # ${destructive ? "changes things: " : ""}${why}`),
161
161
  ];
162
162
  };
163
163
  /** `store recover` and `store recover run`, for a CLI whose commands run on cli-core's context. */
@@ -7,6 +7,8 @@ export declare const STORE_SETTINGS: string[];
7
7
  */
8
8
  export declare const storeSettingsOf: (app: Pick<AppIdentity, "messenger">) => string[];
9
9
  export declare const offersStoreSetting: (app: Pick<AppIdentity, "messenger">, setting: string) => boolean;
10
+ /** Whose deals a CRM copy holds: the owner's to set; an agent's run is stopped from changing it by mistake. */
11
+ export declare const isOwnerOnlyStoreSetting: (setting: string) => boolean;
10
12
  export declare const isStoreSetting: (setting: string) => boolean;
11
13
  export declare const changeStoreSetting: (app: AppIdentity, env: NodeJS.ProcessEnv, setting: string, value: string | undefined) => Promise<{
12
14
  result: {
@@ -4,6 +4,7 @@ import { DEFAULT_PHONE_COUNTRIES, parsePhoneCountries } from "../domain/phones.j
4
4
  import { DEFAULT_TASK_CATEGORIES, taskCategoryValue, unlistedNote, withTaskCategory, } from "../domain/task-categories.js";
5
5
  import { typedCommand } from "../runs/scope.js";
6
6
  import { ACCOUNT_GROUPS_SETTING, groupMembers, groupName } from "../search/account-list.js";
7
+ import { NOT_GROUP_NAMES } from "../search/groups.js";
7
8
  import { DEFAULT_STEMMERS, parseStemmers } from "../search/stem.js";
8
9
  import { openCache } from "../store/open.js";
9
10
  import { storePath } from "../store/path.js";
@@ -31,8 +32,11 @@ export const STORE_SETTINGS = [
31
32
  FIRST_PASS,
32
33
  ];
33
34
  const GROUP_PREFIX = `${ACCOUNT_GROUPS_SETTING}.`;
34
- /** A CRM account's: whether what it reports is a relationship or waits for review, and what its company types mean. */
35
- const CRM_SETTINGS = ["crm.<provider>:<account>.links", "crm.<provider>:<account>.company-types"];
35
+ /**
36
+ * A CRM account's: whether what it reports is a relationship or waits for review, what its company types mean, and
37
+ * whose deals and leads its sync copies.
38
+ */
39
+ const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self"].map((name) => `crm.<provider>:<account>.${name}`);
36
40
  /**
37
41
  * The store settings a CLI offers. Phone countries, task rules and account groups belong to messages; a CLI that is
38
42
  * not a messenger would change them for tg and MAX without reading them itself.
@@ -41,6 +45,11 @@ export const storeSettingsOf = (app) => app.messenger === false
41
45
  ? [...Object.keys(SCRIPTS), OWNER_LANGUAGES, ...CRM_SETTINGS]
42
46
  : [...STORE_SETTINGS, `${GROUP_PREFIX}<name>`, ...CRM_SETTINGS];
43
47
  export const offersStoreSetting = (app, setting) => app.messenger !== false || setting in SCRIPTS || setting === OWNER_LANGUAGES || parseCrmSetting(setting) !== undefined;
48
+ /** Whose deals a CRM copy holds: the owner's to set; an agent's run is stopped from changing it by mistake. */
49
+ export const isOwnerOnlyStoreSetting = (setting) => {
50
+ const name = parseCrmSetting(setting)?.name;
51
+ return name === "scope" || name === "self" || name === "unassigned";
52
+ };
44
53
  export const isStoreSetting = (setting) => setting in SCRIPTS ||
45
54
  setting === OWNER_LANGUAGES ||
46
55
  setting === PHONE_COUNTRIES ||
@@ -232,6 +241,8 @@ const changeAgentClose = async (env, setting, value) => {
232
241
  };
233
242
  const changeGroup = async (app, env, setting, value) => {
234
243
  const name = groupName(setting.slice(GROUP_PREFIX.length));
244
+ if (value !== undefined && NOT_GROUP_NAMES.has(name.toLowerCase()))
245
+ throw new CliError("validation_error", `"${name}" cannot name a group — --source ${name} already means something`);
235
246
  const members = value === undefined ? undefined : groupMembers(value);
236
247
  const store = await openStore({ env });
237
248
  try {
@@ -248,9 +259,28 @@ const changeGroup = async (app, env, setting, value) => {
248
259
  };
249
260
  const crmValueText = (value) => typeof value === "string"
250
261
  ? value
251
- : Object.entries(value)
252
- .map(([type, meaning]) => `${type}=${meaning}`)
253
- .join(",");
262
+ : Array.isArray(value)
263
+ ? value.join(",")
264
+ : Object.entries(value)
265
+ .map(([type, meaning]) => `${type}=${meaning}`)
266
+ .join(",");
267
+ const CRM_DEFAULTS = { links: "reported", "company-types": {}, scope: "mine", unassigned: [], self: "" };
268
+ const crmNote = (name, now) => {
269
+ if (name === "links")
270
+ return `store-wide — the next sync of that account writes what it reports as ${now === "review" ? "proposals for the owner to review" : "reported relationships"}; relationships already stored stay`;
271
+ if (name === "company-types")
272
+ return "store-wide — a company of a mapped type becomes a customer, supplier or partner of the own company";
273
+ if (name === "scope")
274
+ return now === "all"
275
+ ? "store-wide — the next sync of that account copies every deal and lead, listing them all again"
276
+ : "store-wide — the next sync of that account copies only the deals and leads of the sign-in's own user and " +
277
+ "of the unassigned users, and marks the others deleted here; contacts and companies stay whole";
278
+ if (name === "unassigned")
279
+ return "store-wide — with scope mine, the next sync also copies the deals and leads of these users";
280
+ return now === ""
281
+ ? "store-wide — the next sync gives the account's copy to its sign-in's user, and narrows it to that user's deals"
282
+ : "store-wide — the account's copy holds this user's deals; a sync signed in as another user is refused";
283
+ };
254
284
  const changeCrm = async (env, setting, value) => {
255
285
  const { name } = parseCrmSetting(setting);
256
286
  const parsed = value === undefined ? undefined : parseCrmSettingValue(name, value);
@@ -262,12 +292,10 @@ const changeCrm = async (env, setting, value) => {
262
292
  finally {
263
293
  database.close();
264
294
  }
265
- const now = parsed ?? (name === "links" ? "reported" : {});
295
+ const now = parsed ?? CRM_DEFAULTS[name];
266
296
  return {
267
297
  result: { store: storePath(env), scope: "store", setting, value: crmValueText(now) },
268
- note: name === "links"
269
- ? `store-wide — the next sync of that account writes what it reports as ${now === "review" ? "proposals for the owner to review" : "reported relationships"}; relationships already stored stay`
270
- : "store-wide — a company of a mapped type becomes a customer, supplier or partner of the own company",
298
+ note: crmNote(name, now),
271
299
  };
272
300
  };
273
301
  /** Each category as `config show` lists it, and where it comes from: the shared file, an older store's list, the default. */
@@ -154,7 +154,7 @@ export const templatesCommand = (app, options) => {
154
154
  .argument("<key>", "the template, such as report/morning-digest")
155
155
  .addOption(channelOption())
156
156
  .addOption(localeOption())
157
- .option("--file <file>", "take the new template from this file instead of opening an editor")
157
+ .option("--file <file>", "take the new template from this file instead of opening an editor; - reads stdin")
158
158
  .addOption(new Option("--undo", "put back the body your last change replaced; twice is back where you were").conflicts("file"))
159
159
  .action(async function (key, given) {
160
160
  const env = options.env();
@@ -175,7 +175,7 @@ export const templatesCommand = (app, options) => {
175
175
  body = previous;
176
176
  }
177
177
  else if (given.file !== undefined) {
178
- body = readFileSync(given.file, "utf8");
178
+ body = readFileSync(given.file === "-" ? 0 : given.file, "utf8");
179
179
  }
180
180
  else {
181
181
  draft = join(mkdtempSync(join(tmpdir(), "wirecat-template-")), `${key.replace("/", "-")}.${channel}.${address.language}.liquid`);
@@ -225,12 +225,12 @@ export const templatesCommand = (app, options) => {
225
225
  .argument("<key>", "the template, such as report/morning-digest")
226
226
  .addOption(channelOption())
227
227
  .addOption(localeOption())
228
- .option("--file <file>", "preview this draft instead of the template that applies")
228
+ .option("--file <file>", "preview this draft instead of the template that applies; - reads stdin")
229
229
  .action(async function (key, given) {
230
230
  const env = options.env();
231
231
  const { address, kind, channel } = await addressOf(key, given, env);
232
232
  const stored = given.file === undefined ? await withStore(env, (store) => store.templates.get(address)?.body) : undefined;
233
- const body = given.file === undefined ? stored : readFileSync(given.file, "utf8");
233
+ const body = given.file === undefined ? stored : readFileSync(given.file === "-" ? 0 : given.file, "utf8");
234
234
  const { against, view } = previewView(stateOf(app, env), kind, address.language, Date.now());
235
235
  const rendering = await renderReport(view, channel, body === undefined ? {} : { template: body });
236
236
  const problems = body === undefined ? [] : (await checkTemplate(view, channel, body)).problems;
@@ -14,6 +14,7 @@ import { CRM_KINDS } from "../../domain/crm.js";
14
14
  import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
15
15
  import { deal as dealEntity } from "../../entities/deal.js";
16
16
  import { count, text } from "../../entities/fields.js";
17
+ import { CRM_SCOPES } from "../../store/sqlite/crm-settings.js";
17
18
  import { crmStatus, syncCrm } from "../sync.js";
18
19
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
19
20
  import { csvFormatOption, renderCsv } from "./csv.js";
@@ -21,6 +22,8 @@ import { pipelineView } from "./pipeline-view.js";
21
22
  import { addCrmSearchAll } from "./search-all.js";
22
23
  export { csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
23
24
  const MOST = 500;
25
+ /** A stage by the store's reference, as memo's `stages list` and a deal's `base_stage` name it. */
26
+ const STAGE_REF = /^stage:\d+$/;
24
27
  const DEAL_FIELDS = [
25
28
  termField("status", "enum", "status:open", { values: DEAL_STATUSES }),
26
29
  termField("stage", "kw", 'stage:"Quote sent"', { relation: "a stage's name, in any letter case" }),
@@ -58,6 +61,10 @@ const STAGE_UNTRUSTED = ["name", "pipeline_name"];
58
61
  const crmSync = v.strictObject({
59
62
  provider: text,
60
63
  account: text,
64
+ scope: v.variant("mode", [
65
+ v.strictObject({ mode: v.literal("all") }),
66
+ v.strictObject({ mode: v.literal("mine"), self: text, also: v.array(text) }),
67
+ ]),
61
68
  pipelines: count,
62
69
  users: v.optional(count),
63
70
  skipped_owner_rejected: count,
@@ -69,8 +76,11 @@ const crmSync = v.strictObject({
69
76
  saved: count,
70
77
  removed: count,
71
78
  unlisted: count,
79
+ out_of_scope: count,
80
+ held: v.optional(v.literal(true)),
72
81
  pass: v.optional(v.picklist(["complete", "partial", "held"])),
73
82
  error: v.optional(text),
83
+ setting: v.optional(text),
74
84
  })),
75
85
  issues: v.array(v.strictObject({
76
86
  kind: v.picklist([...CRM_KINDS, "user"]),
@@ -83,12 +93,22 @@ const crmSync = v.strictObject({
83
93
  stopped: v.optional(v.picklist(["requests", "deadline", "cancelled"])),
84
94
  progress: v.strictObject({ requests: count, saved: count, steps: count }),
85
95
  hint: v.optional(text),
96
+ group_hint: v.optional(text),
86
97
  });
87
98
  const crmSyncProgress = v.strictObject({
88
99
  kind: v.picklist(CRM_KINDS),
89
100
  round: v.nullable(v.picklist(["full", "changes"])),
90
101
  id_pass: v.nullable(text),
91
102
  stored: count,
103
+ scope: v.optional(v.strictObject({
104
+ setting: v.picklist(CRM_SCOPES),
105
+ explicit: v.boolean(),
106
+ held: v.optional(v.literal(true)),
107
+ applied: v.nullable(v.variant("mode", [
108
+ v.strictObject({ mode: v.literal("all") }),
109
+ v.strictObject({ mode: v.literal("mine"), users: v.array(text) }),
110
+ ])),
111
+ })),
92
112
  job: text,
93
113
  profile: text,
94
114
  done: count,
@@ -169,17 +189,20 @@ const addCrmCommandsDefinition = (program, options) => {
169
189
  ...(opts.rescan ? { rescan: true } : {}),
170
190
  });
171
191
  const failed = report.synced.filter((one) => one.error !== undefined);
192
+ // A kind that failed on a setting fails the same way again until the owner changes it: no retry is offered.
193
+ const retried = failed.filter((one) => one.setting === undefined);
194
+ const settings = [...new Set(failed.flatMap((one) => one.setting ?? []))];
172
195
  const timeout = command.optsWithGlobals().timeout;
173
196
  // The same command again, never --rescan: that would drop the round this run leaves in progress.
174
197
  const stuck = report.state === "partial" && report.progress.steps === 0 && failed.length === 0;
175
- const next = failed.length || (report.state === "partial" && !stuck)
198
+ const next = retried.length || (report.state === "partial" && !stuck && failed.length === 0)
176
199
  ? [
177
200
  {
178
201
  kind: "command",
179
202
  step: "crm.sync",
180
203
  command: "sync",
181
204
  args: Object.fromEntries(Object.entries({ max_pages: opts.maxPages, timeout }).filter(([, value]) => value !== undefined)),
182
- why: failed.length
205
+ why: retried.length
183
206
  ? "a kind failed to sync; running sync again retries it"
184
207
  : "the sync stopped before its end to answer in time; running it again goes on from there",
185
208
  safe_to_auto_execute: true,
@@ -187,8 +210,9 @@ const addCrmCommandsDefinition = (program, options) => {
187
210
  ]
188
211
  : undefined;
189
212
  const progressAt = lineOf(command, "store status");
213
+ const fixes = settings.map((setting) => lineOf(command, `config set ${setting} <value>`));
190
214
  const hint = failed.length
191
- ? `${failed.map((one) => `${one.kind}: ${one.error}`).join("; ")} — run sync again to retry`
215
+ ? `${failed.map((one) => `${one.kind}: ${one.error}`).join("; ")} — ${fixes.length ? `fix the setting: ${fixes.join("; ")}` : "run sync again to retry"}`
192
216
  : stuck
193
217
  ? `this run moved nothing on: raise --timeout or --max-pages, then run sync again; see progress: ${progressAt}`
194
218
  : report.state === "partial"
@@ -198,7 +222,7 @@ const addCrmCommandsDefinition = (program, options) => {
198
222
  // What the healthy kinds brought is saved and answered; each failure and each item not kept is an issue.
199
223
  const issues = [
200
224
  ...failed.map((one) => ({
201
- code: "provider_error",
225
+ code: one.setting === undefined ? "provider_error" : "validation_error",
202
226
  reason: "sync.partial",
203
227
  source: `crm:${one.kind}`,
204
228
  })),
@@ -271,7 +295,7 @@ const addCrmCommandsDefinition = (program, options) => {
271
295
  });
272
296
  example(annotate(group.command("show"), { effects: LOCAL_READ, output: { entity: kind } })
273
297
  .description(`one ${kind} with its pipeline, stage, status, amount and the people on it`)
274
- .argument("<ref>", `${kind}:<id>, as a list shows it`), `${plural} show ${kind}:12`).action(async (reference, _opts, command) => {
298
+ .argument(`<${kind}>`, `${kind}:<id>, as a list shows it`), `${plural} show ${kind}:12`).action(async (reference, _opts, command) => {
275
299
  await within(command, async (run) => {
276
300
  const found = await ownCopy(run, kind, reference);
277
301
  return itemOf({ ...dealKeys(found), untrusted: DEAL_UNTRUSTED });
@@ -320,7 +344,7 @@ const addCrmCommandsDefinition = (program, options) => {
320
344
  command.option("--operation-id <id>", "the operation_id a write that ended in outcome_unknown named: the CRM answers the repeat from its record");
321
345
  return command;
322
346
  };
323
- const reference = (command) => command.argument("<ref>", `${kind}:<id>, as a list shows it`);
347
+ const reference = (command) => command.argument(`<${kind}>`, `${kind}:<id>, as a list shows it`);
324
348
  const fields = (command) => command
325
349
  .option("--title <title>", `the ${kind}'s title`)
326
350
  .option("--pipeline <pipeline>", "pipeline:<id>, or a name only one of the CRM's pipelines has")
@@ -358,9 +382,17 @@ const addCrmCommandsDefinition = (program, options) => {
358
382
  });
359
383
  const move = write("move", "move", `move a ${kind} to another stage of its pipeline; a won or lost stage checks the close key too`);
360
384
  if (move)
361
- example(reference(move).argument("<stage>", "the stage, by the CRM's id or a name only one stage of its pipeline has"), `${plural} move ${kind}:12 "Quote sent"`).action(async (ref, stage, opts, command) => {
385
+ example(reference(move).argument("<stage>", "the stage, by the CRM's id or a name only one stage of its pipeline has; or a stage:<id>, of its pipeline " +
386
+ "or of the owner's base set, which moves it to the one stage of its pipeline mapped there and refuses " +
387
+ "several (with the candidates) or none"), `${plural} move ${kind}:12 "Quote sent"`, `${plural} move ${kind}:12 stage:5`).action(async (ref, stage, opts, command) => {
362
388
  await run(command, async (context) => {
363
- const done = await moveCrmItem(context, kind, ref, stage, idOf(opts));
389
+ let target = stage;
390
+ if (STAGE_REF.test(stage.trim())) {
391
+ // Checked first: another account's pipeline and stage names stay out of the refusal.
392
+ await ownCopy(context, kind, ref);
393
+ target = (await context.store.baseStages.resolve(ref, stage.trim())).stage.externalId ?? stage;
394
+ }
395
+ const done = await moveCrmItem(context, kind, ref, target, idOf(opts));
364
396
  return answered(done.operationId, done.item);
365
397
  });
366
398
  });
@@ -11,7 +11,7 @@ import { commandAt, rootOf } from "../../cli/steps.js";
11
11
  import { DEAL_KINDS } from "../../domain/deals.js";
12
12
  import { SAVE_HELP } from "../../meetings/index.js";
13
13
  import { meaningLane } from "../../services/messages-meaning.js";
14
- import { searchAllWithMeetings } from "../../services/search-all-meetings.js";
14
+ import { searchAll } from "../../services/search-all.js";
15
15
  /** What a CRM CLI's `search all` reads: its deals and leads first, then what the other tools stored. */
16
16
  const SEARCHED = ["crm", ...SOURCE_SEARCHED];
17
17
  const DEFAULT_LIMIT = 20;
@@ -21,9 +21,10 @@ const DEFAULT_LIMIT = 20;
21
21
  */
22
22
  export const addCrmSearchAll = (searches, { within, app, example, }) => {
23
23
  const all = annotate(new Command("all"), { effects: LOCAL_READ, partial: true, output: { entity: "hit" } })
24
- .summary("search stored deals and leads, messages, notes and calendar events")
25
- .description("search the CRM's deals and leads by the words of their title, and messages, notes and calendar events other " +
26
- "WireCat tools stored — best match first. Use it when you do not know where something was written")
24
+ .summary("search stored deals and leads, messages, notes, calendar events and meetings")
25
+ .description("search the CRM's deals and leads by the words of their title, and messages, notes, calendar events and " +
26
+ "meetings other WireCat tools stored — best match first. Use it when you do not know where something was " +
27
+ "written")
27
28
  .argument("<query...>", 'words and "phrases"; deals and leads match the words of their title')
28
29
  .addHelpText("after", SAVE_HELP);
29
30
  searches.addCommand(searchAllOptions(all, SEARCHED));
@@ -46,7 +47,7 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
46
47
  const limit = opts.limit ?? DEFAULT_LIMIT;
47
48
  const offset = offsetOf(opts.page, limit);
48
49
  const env = run.env ?? process.env;
49
- const found = await searchAllWithMeetings(run.store, run.account, {
50
+ const found = await searchAll(run.store, run.account, {
50
51
  text: words.join(" "),
51
52
  limit,
52
53
  ...(offset === undefined ? {} : { offset }),
@@ -54,9 +55,9 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
54
55
  ...(opts.timezone === undefined ? {} : { timezone: opts.timezone }),
55
56
  env,
56
57
  only,
58
+ ...(opts.only?.includes("meetings") ? { meetingsAsked: true } : {}),
57
59
  ...(crmKinds.length < DEAL_KINDS.length ? { crmKinds } : {}),
58
60
  ...(opts.source === undefined ? {} : { source: opts.source }),
59
- ...(opts.maxMeetings === undefined ? {} : { maxMeetings: opts.maxMeetings }),
60
61
  ...(run.locked ? { scope: { crm: [run.account] } } : {}),
61
62
  }, { app, hintCommand: commandAt(rootOf(leaf), "models download") ? app.command : null }, undefined, meaningLane({ env, messenger: { app }, store: async () => run.store }));
62
63
  const note = (text) => outputFor(leaf).renderer.note(text);
@@ -0,0 +1,8 @@
1
+ import type { MessageStore } from "../store/store.js";
2
+ import type { AccountKey } from "../store/types.js";
3
+ export declare const workGroupHint: (key: AccountKey) => string;
4
+ /**
5
+ * A CRM account no saved group lists is reachable only by reading everything (WC-ACCT-13); this says how to put
6
+ * it in a work group, and never asks.
7
+ */
8
+ export declare const ungroupedHint: (store: MessageStore, key: AccountKey) => Promise<string | undefined>;
@@ -0,0 +1,13 @@
1
+ import { sameAs } from "../search/account-list.js";
2
+ import { ALL } from "../search/groups.js";
3
+ import { listContextOf } from "../services/search-kind.js";
4
+ export const workGroupHint = (key) => `add it to a work group: \`memo groups add work ${key.provider}:${key.account}\``;
5
+ /**
6
+ * A CRM account no saved group lists is reachable only by reading everything (WC-ACCT-13); this says how to put
7
+ * it in a work group, and never asks.
8
+ */
9
+ export const ungroupedHint = async (store, key) => {
10
+ const { groups } = (await listContextOf(store, key, undefined)).membership;
11
+ const grouped = Object.entries(groups).some(([name, members]) => name !== ALL && members.some(sameAs(key)));
12
+ return grouped ? undefined : workGroupHint(key);
13
+ };
@@ -1,4 +1,4 @@
1
- import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmUser } from "../domain/crm.js";
1
+ import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmUser } from "../domain/crm.js";
2
2
  import type { DealKind } from "../domain/deals.js";
3
3
  export interface CrmSourceTraits {
4
4
  /** What this CRM has: one without leads leaves `lead` out. Contacts and companies come before the items on them. */
@@ -51,12 +51,23 @@ export interface CrmCallContext {
51
51
  message: string;
52
52
  scope?: string;
53
53
  }): void;
54
+ /**
55
+ * Which deals and leads the engine keeps; absent, every one. The engine applies it to what a source lists, so a
56
+ * source may also filter by it to read less, and must still list every assignee's changes.
57
+ */
58
+ scope?: CrmScope;
54
59
  }
55
60
  /** One CRM account, as an adapter reads it. The engine never sees a provider word. */
56
61
  export interface CrmSource {
57
62
  /** The registry name: `bitrix24`, `pipedrive`, `hubspot`, `amocrm`. */
58
63
  readonly provider: string;
59
64
  readonly traits: CrmSourceTraits;
65
+ /**
66
+ * The sign-in's own user id in the CRM, what a `mine` scope keeps besides `unassigned`. A source with it fills every
67
+ * deal's and lead's `assignee`, since `mine` keeps one without as nobody's; a source without it is copied whole. One
68
+ * account's copy belongs to one user: another sign-in's user is refused.
69
+ */
70
+ self?(): string | Promise<string>;
60
71
  /** One kind's pipelines with their stages; a CRM whose leads have no pipelines answers one of its own making. */
61
72
  pipelines(kind: DealKind, context?: CrmCallContext): Promise<CrmPipeline[]>;
62
73
  /**
@@ -1,5 +1,5 @@
1
1
  import { type BudgetStop, type RunBudget } from "../background/budget.js";
2
- import { type CrmKind } from "../domain/crm.js";
2
+ import { type CrmKind, type CrmScope } from "../domain/crm.js";
3
3
  import type { CrmRelationIssue, CrmSkipped } from "../store/sqlite/crm.js";
4
4
  import type { MessageStore } from "../store/store.js";
5
5
  import type { AccountKey } from "../store/types.js";
@@ -28,6 +28,10 @@ export interface CrmCursor {
28
28
  pass: PendingPass | null;
29
29
  /** When the last complete id pass started; 0 before the first. */
30
30
  passAt: number;
31
+ /** Of a deal or lead: the scope the copy is read under, `all` or `mine:<user ids>`; absent, `all`, as before scopes. */
32
+ scope?: string;
33
+ /** The copy still holds stored rows outside `scope`: a held narrowing, done once the owner sets the scope. */
34
+ narrowing?: true;
31
35
  }
32
36
  export declare const parseCrmCursor: (value: string | null | undefined) => CrmCursor | null;
33
37
  export declare const cursorName: (kind: CrmKind) => string;
@@ -46,7 +50,7 @@ export interface CrmSyncOptions {
46
50
  export interface CrmSyncIssue {
47
51
  /** `user`: the account's users and departments. */
48
52
  kind: CrmKind | "user";
49
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.not-reported" | "crm.pending-dropped";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.not-reported" | "crm.pending-dropped";
50
54
  message: string;
51
55
  externalId?: string;
52
56
  }
@@ -62,10 +66,16 @@ export interface CrmSyncResult {
62
66
  removed: number;
63
67
  /** Rows a complete id pass did not list, now marked deleted. */
64
68
  unlisted: number;
69
+ /** Rows that changed and left the scope, such as a deal given to another user, now marked deleted. */
70
+ outOfScope: number;
71
+ /** A narrowing waits for the owner: rows outside the scope are not saved, and the stored ones are kept. */
72
+ held?: true;
65
73
  /** `complete`: a full list of ids arrived; `partial`: it stopped and goes on next run; `held`: it would mark too many. */
66
74
  pass?: "complete" | "partial" | "held";
67
75
  /** Set when the kind failed; its cursor stays at its last saved page. */
68
76
  error?: string;
77
+ /** Set when the kind failed on this setting's value: changing it, not running sync again, fixes it. */
78
+ setting?: string;
69
79
  }
70
80
  export interface CrmSyncReport {
71
81
  provider: string;
@@ -74,6 +84,8 @@ export interface CrmSyncReport {
74
84
  pipelines: number;
75
85
  /** Users read this run; absent when the CRM cannot list them. */
76
86
  users?: number;
87
+ /** The deals and leads this run copied, with the sign-in's own user; `all` too when the CRM names none. */
88
+ scope: CrmScope;
77
89
  /** Relationships left out because the owner removed or rejected that very one, role included. */
78
90
  skippedOwnerRejected: number;
79
91
  synced: CrmSyncResult[];
@@ -90,6 +102,11 @@ export interface CrmSyncReport {
90
102
  steps: number;
91
103
  };
92
104
  hint?: string;
105
+ /**
106
+ * On the first sync of an account no saved group lists: how to add it to a work group. Not `next`, which in an answer
107
+ * is the list of steps to run.
108
+ */
109
+ groupHint?: string;
93
110
  }
94
111
  /** The gaps the account's last sync recorded; none before its first. */
95
112
  export declare const crmGapsOf: (store: MessageStore, account: AccountKey) => Promise<CrmGap[]>;
@@ -121,6 +138,18 @@ export declare const crmStatus: (store: MessageStore, account: AccountKey, { pro
121
138
  round: string | null;
122
139
  id_pass: string | null;
123
140
  stored: number;
141
+ scope?: {
142
+ setting: "all" | "mine";
143
+ explicit: boolean;
144
+ applied: {
145
+ mode: "all";
146
+ users?: undefined;
147
+ } | {
148
+ mode: "mine";
149
+ users: string[];
150
+ } | null;
151
+ held?: boolean | undefined;
152
+ } | undefined;
124
153
  line: string;
125
154
  }[];
126
155
  page: number;