@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
@@ -0,0 +1,154 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { parseLucene } from "@wirecat/cli-base/query";
3
+ import { DEAL_KINDS } from "../domain/deals.js";
4
+ import { isUsable } from "../domain/relations.js";
5
+ import { isClosedState } from "../tasks/index.js";
6
+ import { coverageFor, edgesOf, grouped, namesOf, notRejected, organizationCategories, SECTION_LIMIT, STORE_PAGE, scopeOf, sectionOf, } from "./business-context.js";
7
+ import { communicationsOf } from "./communications.js";
8
+ import { moneyOf } from "./money-context.js";
9
+ export const dealLine = (deal) => ({
10
+ ref: deal.ref,
11
+ kind: deal.kind,
12
+ title: deal.title,
13
+ summary: deal.summary,
14
+ stage: deal.stage,
15
+ status: deal.status,
16
+ currency: deal.currency,
17
+ amount: deal.amount,
18
+ closeDate: deal.closeDate,
19
+ project: deal.project,
20
+ });
21
+ /** Open tasks of these projects, the soonest due first, and the command that lists them when it is one project's. */
22
+ export const openTasksOf = async (store, projects) => {
23
+ const tasks = [];
24
+ let full = false;
25
+ for (const project of projects) {
26
+ const found = await store.tasks.find({ project: project.ref, limit: STORE_PAGE });
27
+ full ||= found.length >= STORE_PAGE;
28
+ for (const task of found)
29
+ if (!isClosedState(task.status))
30
+ tasks.push({
31
+ ref: task.ref,
32
+ key: task.key,
33
+ title: task.title,
34
+ status: task.status,
35
+ project: task.project,
36
+ dueAt: task.dueAt,
37
+ });
38
+ }
39
+ const [only] = projects;
40
+ return {
41
+ tasks: tasks.sort((a, b) => (a.dueAt ?? "~").localeCompare(b.dueAt ?? "~") || a.ref.localeCompare(b.ref)),
42
+ full,
43
+ next: projects.length === 1 && only ? `tasks list project:${only.key}` : null,
44
+ };
45
+ };
46
+ /** The one list command that holds every row, when the rows are all of one kind. */
47
+ const oneKind = (rows, commands) => commands.find(([fits]) => rows.every(fits))?.[1] ?? null;
48
+ /**
49
+ * One answer about an organization from the store: its people, its customers, suppliers and partners, projects,
50
+ * open deals, money and how much the owner talks with its people. Every relationship says its standing; a source
51
+ * nobody confirmed is `reported`, one that stopped is `ended`, one waiting for the owner `proposed`. A CRM's rows
52
+ * outside `accounts` are left out, and `coverage` names that CRM.
53
+ */
54
+ export const organizationContext = async (store, reference, { accounts, limit = SECTION_LIMIT, deniedKinds = [] } = {}) => {
55
+ const id = /^(?:organization:)?(\d+)$/.exec(reference.trim())?.[1];
56
+ if (id === undefined)
57
+ throw new CliError("validation_error", "an organization is organization:<id>");
58
+ const ref = `organization:${id}`;
59
+ const [organization] = await store.knowledge.organizations(parseLucene(`id:${id}`));
60
+ if (!organization)
61
+ throw new CliError("not_found", `no ${ref} in the store`);
62
+ const scope = scopeOf(accounts, deniedKinds);
63
+ const own = (await store.knowledge.ownOrganizations()).some((one) => one.ref === ref);
64
+ const { edges, full } = await edgesOf(store, ref, scope);
65
+ const names = await namesOf(store, edges.flatMap(({ from, to }) => [from, to]));
66
+ const into = (kind, from) => (edge) => edge.role.kind === kind && edge.to === ref && edge.from.startsWith(from) ? edge.from : undefined;
67
+ const people = grouped(edges, into("member-of", "person:"), names);
68
+ const customers = grouped(edges, into("customer-of", ""), names);
69
+ const suppliers = grouped(edges, (edge) => (edge.role.kind === "customer-of" && edge.from === ref ? edge.to : undefined), names);
70
+ const partners = grouped(edges, (edge) => (edge.role.kind !== "partner-of" ? undefined : edge.from === ref ? edge.to : edge.from), names);
71
+ const deals = [];
72
+ let dealsFull = false;
73
+ for (const kind of DEAL_KINDS.filter((one) => !scope.denied.has(one))) {
74
+ const found = await store.deals.list({
75
+ kind,
76
+ organization: ref,
77
+ status: "open",
78
+ limit: STORE_PAGE,
79
+ ...(accounts === undefined ? {} : { accounts }),
80
+ });
81
+ dealsFull ||= found.length >= STORE_PAGE;
82
+ for (const deal of found)
83
+ deals.push(deal);
84
+ }
85
+ const catalog = new Map((await store.knowledge.projects()).map((project) => [project.ref, project]));
86
+ const projects = new Map();
87
+ for (const project of catalog.values())
88
+ if (project.organizationId === organization.id)
89
+ projects.set(project.ref, { ref: project.ref, name: project.name, via: ["organization"] });
90
+ for (const deal of deals)
91
+ if (deal.project !== null) {
92
+ const held = projects.get(deal.project) ?? { ref: deal.project, name: deal.projectName ?? deal.project, via: [] };
93
+ if (!held.via.includes("deal"))
94
+ held.via.push("deal");
95
+ projects.set(deal.project, held);
96
+ }
97
+ const invoiceRows = await store.finance.invoices({ counterparty: ref, limit: STORE_PAGE });
98
+ const paymentRows = await store.finance.payments({ party: ref, limit: STORE_PAGE });
99
+ const invoices = notRejected(invoiceRows).map((invoice) => [invoice, "counterparty"]);
100
+ const payments = notRejected(paymentRows).map((payment) => [payment, "counterparty"]);
101
+ const orders = [];
102
+ let ordersFull = false;
103
+ for (const side of ["customer", "supplier"]) {
104
+ const found = await store.orders.list({ [side]: ref, limit: STORE_PAGE });
105
+ ordersFull ||= found.length >= STORE_PAGE;
106
+ for (const order of notRejected(found))
107
+ orders.push({
108
+ ref: order.ref,
109
+ title: order.title,
110
+ status: order.status,
111
+ review: order.review,
112
+ currency: order.currency,
113
+ total: order.total,
114
+ side,
115
+ });
116
+ }
117
+ const financeComplete = invoiceRows.length < STORE_PAGE && paymentRows.length < STORE_PAGE && !ordersFull;
118
+ const members = [];
119
+ for (const person of people)
120
+ if (person.roles.some((role) => isUsable(role.standing))) {
121
+ const record = await store.people.personByUid(person.ref.slice("person:".length));
122
+ if (record)
123
+ members.push(record);
124
+ }
125
+ const talks = await communicationsOf(store, members, scope);
126
+ const categories = (await organizationCategories(store, scope)).get(ref) ?? [];
127
+ const tasks = await openTasksOf(store, [...projects.keys()].flatMap((one) => {
128
+ const project = catalog.get(one);
129
+ return project ? [{ ref: one, key: project.key }] : [];
130
+ }));
131
+ const about = `about:${ref}`;
132
+ const more = { more: full };
133
+ return {
134
+ organization: { ...organization, own },
135
+ categories,
136
+ people: sectionOf(people, limit, `relationships list ${about} kind:member-of`, more),
137
+ customers: sectionOf(customers, limit, `relationships list to:${ref} kind:customer-of`, more),
138
+ suppliers: sectionOf(suppliers, limit, `relationships list from:${ref} kind:customer-of`, more),
139
+ partners: sectionOf(partners, limit, `relationships list ${about} kind:partner-of`, more),
140
+ projects: sectionOf([...projects.values()], limit, null),
141
+ deals: sectionOf(deals.map(dealLine), limit, oneKind(deals, [
142
+ [(deal) => deal.kind === "deal", `deals list organization:"${ref}" status:open`],
143
+ [(deal) => deal.kind === "lead", `leads list organization:"${ref}" status:open`],
144
+ ]), { more: dealsFull }),
145
+ money: moneyOf({ invoices, payments, orders }, limit, {
146
+ invoices: `invoices list counterparty:"${ref}"`,
147
+ payments: `payments list party:"${ref}"`,
148
+ orders: oneKind(orders, [[(order) => order.side === "customer", `orders list customer:"${ref}"`]]),
149
+ }, financeComplete),
150
+ communications: { ...talks.counts, hasMore: talks.hasMore },
151
+ tasks: sectionOf(tasks.tasks, limit, tasks.next, { more: tasks.full }),
152
+ coverage: await coverageFor(store, talks.coverage, scope),
153
+ };
154
+ };
@@ -73,8 +73,11 @@ export interface PeopleService {
73
73
  fetch?: boolean;
74
74
  }): Promise<PersonMessages>;
75
75
  /** `other` may name another messenger of the store: `max:Ana`. */
76
- link(person: string, other: string, method?: string): Promise<PersonRecord>;
77
- unlink(person: string): Promise<PersonRecord>;
76
+ link(person: string, other: string, options: LinkPeopleOptions): Promise<LinkedPeople>;
77
+ /** The owner's alone: an unlink separates two people, and nothing links them again on its own. */
78
+ unlink(person: string, options: {
79
+ by: string;
80
+ }): Promise<PersonRecord>;
78
81
  /**
79
82
  * Only counts and the people recognised: never a number. `IMPORT_CHUNK` numbers a request, each request
80
83
  * through the guard, each number counted toward the hourly limit.
@@ -85,12 +88,25 @@ export interface PeopleService {
85
88
  }>>;
86
89
  }
87
90
  export declare const peopleService: (deps: ServiceDeps) => PeopleService;
88
- /** Digits, with the `+` and the spaces, dashes and brackets people type dropped. */
91
+ export interface LinkPeopleOptions {
92
+ /** `"owner"`, or the agent the run is attributed to (`actorOf`): only the owner's link is made at once. */
93
+ by: string;
94
+ /** Why an agent thinks they are one person; it is required of an agent and kept on the proposal. */
95
+ reason?: string | undefined;
96
+ method?: string;
97
+ }
98
+ /** The person as linked, or, for an agent, as still unlinked with the `identity_link` proposal waiting for the owner. */
99
+ export type LinkedPeople = PersonRecord & {
100
+ proposal?: string;
101
+ };
89
102
  /**
90
- * The owner's link of two people, each read in the account's messenger unless prefixed (`max:Ana`, `email:ana@x.com`,
91
- * `person:12`); `me` links the first to the owner. A tool without a messenger (a calendar CLI) calls it directly.
103
+ * Links two people, each read in the account's messenger unless prefixed (`max:Ana`, `email:ana@x.com`, `person:12`);
104
+ * `me` links the first to the owner. The owner's link is made at once; an agent's opens an `identity_link` proposal
105
+ * only the owner confirms, and an agent never says who the owner is. A tool without a messenger (a calendar CLI) calls
106
+ * it directly.
92
107
  */
93
- export declare const linkPeople: (store: MessageStore, account: AccountKey, person: string, other: string, method?: string) => Promise<PersonRecord>;
108
+ export declare const linkPeople: (store: MessageStore, account: AccountKey, person: string, other: string, { by, reason, method }: LinkPeopleOptions) => Promise<LinkedPeople>;
109
+ /** Digits, with the `+` and the spaces, dashes and brackets people type dropped. */
94
110
  export declare const phoneOf: (typed: string) => string;
95
111
  /** `--hide-phone`: the answer without the number, for output that will be pasted somewhere. */
96
112
  export declare const withoutPhone: <T extends {
@@ -109,8 +109,12 @@ export const peopleService = (deps) => {
109
109
  ...(detail ? { detail } : {}),
110
110
  });
111
111
  },
112
- link: async (person, other, method = "manual") => linkPeople(await deps.store(), await deps.account(), person, other, method),
113
- unlink: async (person) => {
112
+ link: async (person, other, options) => linkPeople(await deps.store(), await deps.account(), person, other, options),
113
+ unlink: async (person, { by }) => {
114
+ if (by !== "owner")
115
+ throw new CliError("permission_error", "only the owner unlinks an identity; the owner runs this", {
116
+ reason: "identity.owner-only",
117
+ });
114
118
  const store = await deps.store();
115
119
  return store.people.unlinkIdentity(await identityIn(store, await deps.account(), person), {
116
120
  method: "manual",
@@ -188,20 +192,46 @@ export const peopleService = (deps) => {
188
192
  };
189
193
  /** Numbers per request: one big list in one request is what a contact-scraping account sends. */
190
194
  const IMPORT_CHUNK = 10;
191
- /** Digits, with the `+` and the spaces, dashes and brackets people type dropped. */
192
195
  /**
193
- * The owner's link of two people, each read in the account's messenger unless prefixed (`max:Ana`, `email:ana@x.com`,
194
- * `person:12`); `me` links the first to the owner. A tool without a messenger (a calendar CLI) calls it directly.
196
+ * Links two people, each read in the account's messenger unless prefixed (`max:Ana`, `email:ana@x.com`, `person:12`);
197
+ * `me` links the first to the owner. The owner's link is made at once; an agent's opens an `identity_link` proposal
198
+ * only the owner confirms, and an agent never says who the owner is. A tool without a messenger (a calendar CLI) calls
199
+ * it directly.
195
200
  */
196
- export const linkPeople = async (store, account, person, other, method = "manual") => {
201
+ export const linkPeople = async (store, account, person, other, { by, reason, method = "manual" }) => {
197
202
  const one = await identityIn(store, account, person);
198
- if (other === "me")
203
+ const owner = by === "owner";
204
+ if (other === "me") {
205
+ if (!owner)
206
+ throw new CliError("permission_error", "only the owner links an identity to themselves; the owner runs this", {
207
+ reason: "identity.owner-only",
208
+ });
199
209
  return store.people.linkToOwner(one);
210
+ }
200
211
  const two = await identityIn(store, account, other);
201
212
  if (one.provider === two.provider && one.id === two.id)
202
213
  throw new CliError("validation_error", "that is the same person twice");
203
- return store.people.linkIdentities(one, two, { method, by: "owner" });
214
+ if (owner)
215
+ return store.people.linkIdentities(one, two, { method, by });
216
+ const why = reason?.trim();
217
+ if (!why)
218
+ throw new CliError("validation_error", "an agent proposing a link gives a reason: --reason <why they are one>", {
219
+ reason: "proposal.reason-required",
220
+ });
221
+ const record = (await store.people.personOf(one));
222
+ if (record.identities.some(({ provider, id }) => provider === two.provider && id === two.id))
223
+ return record;
224
+ // `linkIdentities` merges `other`'s person into `person`'s; a confirmed proposal merges `identity`'s into `with`'s.
225
+ const proposed = await store.people.proposeLink({
226
+ identity: two,
227
+ with: one,
228
+ signal: "agent",
229
+ by: { bot: by },
230
+ reason: why,
231
+ });
232
+ return { ...record, proposal: proposed.id };
204
233
  };
234
+ /** Digits, with the `+` and the spaces, dashes and brackets people type dropped. */
205
235
  export const phoneOf = (typed) => {
206
236
  const digits = typed.replace(/[\s()+-]/g, "");
207
237
  if (!/^\d{6,15}$/.test(digits)) {
@@ -0,0 +1,43 @@
1
+ import type { DealKind } from "../domain/deals.js";
2
+ import type { AccountKey, MessageStore, PersonRecord } from "../store/store.js";
3
+ import { type Category, type Coverage, type Related, type Scope, type Section } from "./business-context.js";
4
+ import { type ContextOptions, type PersonContext } from "./person-context.js";
5
+ /** What a person is in the owner's business, each relationship with its standing. */
6
+ export interface PersonBusiness {
7
+ organizations: Section<Related & {
8
+ categories: Category[];
9
+ }>;
10
+ /** Whom they report to. */
11
+ reportsTo: Section<Related>;
12
+ /** Who reports to them: `reports-to` read backwards, "manages". */
13
+ directReports: Section<Related>;
14
+ /** Deals and leads they are on, with their roles there. */
15
+ deals: Section<Related>;
16
+ projects: Section<Related>;
17
+ /** `client` when they are `customer-of` an own organization, and each category of an organization they belong to. */
18
+ categories: Category[];
19
+ }
20
+ /** `personContext` of any canonical person, with no account to ask from: every account in scope is read. */
21
+ export interface CanonicalPersonContext extends Omit<PersonContext, "person"> {
22
+ person: PersonRecord;
23
+ business: PersonBusiness;
24
+ coverage: Coverage;
25
+ }
26
+ export interface CanonicalContextOptions extends ContextOptions {
27
+ /** The accounts read; left out, every account in the store, and `coverage.accounts` names them. */
28
+ accounts?: AccountKey[];
29
+ /** Items per business section. */
30
+ limit?: number;
31
+ /** The kinds the profile denies: no deal or lead of theirs is named. */
32
+ deniedKinds?: readonly DealKind[];
33
+ }
34
+ export declare const personBusiness: (store: MessageStore, uid: string, { limit, scope }?: {
35
+ limit?: number;
36
+ scope?: Scope;
37
+ }) => Promise<PersonBusiness>;
38
+ /**
39
+ * What the store knows about one canonical person, by `person:<uid>`: a CRM contact, a name the owner added, or
40
+ * someone seen by several accounts alike. Every identity is read in every account in scope that saw it — never one
41
+ * picked for them (WC-ACCT-9) — and `coverage` says what was read and what was not.
42
+ */
43
+ export declare const canonicalPersonContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, ...options }?: CanonicalContextOptions) => Promise<CanonicalPersonContext>;
@@ -0,0 +1,67 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { isUsable } from "../domain/relations.js";
3
+ import { CATEGORIES, coverageFor, edgesOf, grouped, keyOf, namesOf, organizationCategories, SECTION_LIMIT, scopeOf, sectionOf, usable, } from "./business-context.js";
4
+ import { calendarsOf, coverageOf, readsIn } from "./communications.js";
5
+ import { recordContext } from "./person-context.js";
6
+ export const personBusiness = async (store, uid, { limit = SECTION_LIMIT, scope = scopeOf(undefined) } = {}) => {
7
+ const ref = `person:${uid}`;
8
+ const { edges, full } = await edgesOf(store, ref, scope);
9
+ const names = await namesOf(store, edges.flatMap(({ from, to }) => [from, to]));
10
+ const outward = (kind, to) => (edge) => edge.role.kind === kind && edge.from === ref && edge.to.startsWith(to) ? edge.to : undefined;
11
+ const categories = await organizationCategories(store, scope);
12
+ const own = new Set((await store.knowledge.ownOrganizations()).map((one) => one.ref));
13
+ const about = `about:${ref}`;
14
+ const more = { more: full };
15
+ const organizations = grouped(edges, outward("member-of", "organization:"), names).map((one) => ({
16
+ ...one,
17
+ categories: categories.get(one.ref) ?? [],
18
+ }));
19
+ const held = new Set();
20
+ if (edges.some((edge) => usable(edge) && edge.role.kind === "customer-of" && edge.from === ref && own.has(edge.to)))
21
+ held.add("client");
22
+ for (const one of organizations)
23
+ if (one.roles.some((role) => isUsable(role.standing)))
24
+ for (const category of one.categories)
25
+ held.add(category);
26
+ return {
27
+ organizations: sectionOf(organizations, limit, `relationships list ${about} kind:member-of`, more),
28
+ reportsTo: sectionOf(grouped(edges, outward("reports-to", "person:"), names), limit, `relationships list from:${ref} kind:reports-to`, more),
29
+ directReports: sectionOf(grouped(edges, (edge) => (edge.role.kind === "reports-to" && edge.to === ref ? edge.from : undefined), names), limit, `relationships list to:${ref} kind:reports-to`, more),
30
+ deals: sectionOf(grouped(edges, (edge) => edge.role.kind === "related-to" && edge.to === ref && /^(deal|lead):/.test(edge.from) ? edge.from : undefined, names), limit, `relationships list ${about} kind:related-to`, more),
31
+ projects: sectionOf(grouped(edges, outward("member-of", "project:"), names), limit, `relationships list ${about} kind:member-of`, more),
32
+ categories: CATEGORIES.filter((one) => held.has(one)),
33
+ };
34
+ };
35
+ /**
36
+ * What the store knows about one canonical person, by `person:<uid>`: a CRM contact, a name the owner added, or
37
+ * someone seen by several accounts alike. Every identity is read in every account in scope that saw it — never one
38
+ * picked for them (WC-ACCT-9) — and `coverage` says what was read and what was not.
39
+ */
40
+ export const canonicalPersonContext = async (store, reference, { accounts, limit, deniedKinds, ...options } = {}) => {
41
+ const uid = /^person:(\d+)$/.exec(reference.trim())?.[1];
42
+ if (uid === undefined)
43
+ throw new CliError("validation_error", "a person is person:<id>");
44
+ const record = await store.people.personByUid(uid);
45
+ if (!record)
46
+ throw new CliError("not_found", `no person:${uid} in the store`);
47
+ const scope = scopeOf(accounts, deniedKinds);
48
+ const stored = await store.accounts.storedAccounts();
49
+ // The scope is the caller's: every stored account it holds is readable, whatever its personal or work scope.
50
+ const readable = stored.filter((one) => scope.has(one));
51
+ const scopes = new Map(stored.map((one) => [keyOf(one), one.scope]));
52
+ const reads = readsIn(stored, record, scope).map((one) => ({
53
+ ...one,
54
+ scope: scopes.get(keyOf(one.key)),
55
+ }));
56
+ const calendars = (await calendarsOf(store, stored)).filter((one) => scope.has(one));
57
+ const read = [...reads.map(({ key }) => keyOf(key)), ...calendars.map(keyOf)];
58
+ return {
59
+ person: record,
60
+ ...(await recordContext(store, record, reads, readable, {
61
+ ...options,
62
+ ...(accounts === undefined ? {} : { calendarIds: calendars.map(({ id }) => id) }),
63
+ })),
64
+ business: await personBusiness(store, uid, { ...(limit === undefined ? {} : { limit }), scope }),
65
+ coverage: await coverageFor(store, coverageOf([record], read, calendars.length > 0), scope),
66
+ };
67
+ };
@@ -1,4 +1,5 @@
1
1
  import type { ChatKind, Id, Message, Provider } from "../domain/models.js";
2
+ import type { Event, EventFilter } from "../meetings/index.js";
2
3
  import type { AccountKey, IdentityRef, LinkedIdentity, MessageStore, PersonRecord, StoredAccount } from "../store/store.js";
3
4
  export declare const CONTEXT_MESSAGES = 10;
4
5
  export declare const CONTEXT_BYTES: number;
@@ -88,10 +89,19 @@ export interface ContextOptions {
88
89
  * and a work contact into one person, so a personal account must not read that person's work mail by default.
89
90
  */
90
91
  scopes?: readonly AccountScope[];
92
+ /** The calendar accounts' store ids whose events are read; left out, every calendar's. */
93
+ calendarIds?: readonly number[];
91
94
  }
92
95
  export declare const toContext: (key: AccountKey, message: Message, chatTitle: string | null) => ContextMessage;
96
+ /** Up to `limit` events of `filter`, in its order, the first occurrence of each series only and none cancelled. */
97
+ export declare const eventsOnce: (store: MessageStore, filter: EventFilter, limit: number) => Promise<{
98
+ items: Event[];
99
+ cut: boolean;
100
+ }>;
93
101
  /** The stored accounts of `scopes`, or of the asked account's own scope; the asked account must be stored. */
94
102
  export declare const readableAccounts: (store: MessageStore, asked: AccountKey, scopes?: readonly AccountScope[]) => Promise<StoredAccount[]>;
103
+ /** `scopes`, or the asked account's own scope: what a read that belongs to no account may show. */
104
+ export declare const readableScopes: (store: MessageStore, asked: AccountKey, scopes?: readonly AccountScope[]) => Promise<readonly AccountScope[]>;
95
105
  /**
96
106
  * The accounts each identity is read in, among `readable` only: for the messenger asked, only the account asked
97
107
  * about — a second account of the same messenger is somebody else's view; for a linked messenger, every readable
@@ -115,7 +125,7 @@ export declare const recordContext: (store: MessageStore, record: PersonRecord,
115
125
  key: AccountKey;
116
126
  scope: AccountScope;
117
127
  identity: LinkedIdentity;
118
- }[], readable: readonly StoredAccount[], { messages, bytes, since, now }?: ContextOptions) => Promise<Omit<PersonContext, "person">>;
128
+ }[], readable: readonly StoredAccount[], { messages, bytes, since, now, calendarIds, scopes, }?: ContextOptions) => Promise<Omit<PersonContext, "person">>;
119
129
  /** `max:Ana` names a person in another messenger of this store; a reference with no prefix, this one. */
120
130
  export declare const identityIn: (store: MessageStore, asked: AccountKey, reference: string) => Promise<IdentityRef>;
121
131
  export declare const CHAT_MESSAGES = 20;
@@ -58,7 +58,7 @@ const EVENT_PAGE = 100;
58
58
  /** A weekly meeting held for years is hundreds of occurrences; past this many rows the list stops, cut. */
59
59
  const EVENT_ROWS = 1000;
60
60
  /** Up to `limit` events of `filter`, in its order, the first occurrence of each series only and none cancelled. */
61
- const eventsOnce = async (store, filter, limit) => {
61
+ export const eventsOnce = async (store, filter, limit) => {
62
62
  const items = [];
63
63
  const series = new Set();
64
64
  for (let offset = 0; offset < EVENT_ROWS; offset += EVENT_PAGE) {
@@ -81,15 +81,20 @@ const eventsOnce = async (store, filter, limit) => {
81
81
  return { items, cut: true };
82
82
  };
83
83
  const nameOf = ({ provider, account }) => `${provider}:${account}`;
84
- /** The stored accounts of `scopes`, or of the asked account's own scope; the asked account must be stored. */
85
- export const readableAccounts = async (store, asked, scopes) => {
84
+ const allowedOf = async (store, asked, scopes) => {
86
85
  const stored = await store.accounts.storedAccounts();
87
86
  const own = stored.find((one) => nameOf(one) === nameOf(asked));
88
87
  if (!own || (asked.scope !== undefined && asked.scope !== own.scope))
89
88
  throw new CliError("not_found", `no ${asked.provider} account ${asked.account} in the store`);
90
- const allowed = scopes ?? [own.scope];
89
+ return { stored, allowed: scopes ?? [own.scope] };
90
+ };
91
+ /** The stored accounts of `scopes`, or of the asked account's own scope; the asked account must be stored. */
92
+ export const readableAccounts = async (store, asked, scopes) => {
93
+ const { stored, allowed } = await allowedOf(store, asked, scopes);
91
94
  return stored.filter((one) => allowed.includes(one.scope));
92
95
  };
96
+ /** `scopes`, or the asked account's own scope: what a read that belongs to no account may show. */
97
+ export const readableScopes = async (store, asked, scopes) => (await allowedOf(store, asked, scopes)).allowed;
93
98
  /**
94
99
  * The accounts each identity is read in, among `readable` only: for the messenger asked, only the account asked
95
100
  * about — a second account of the same messenger is somebody else's view; for a linked messenger, every readable
@@ -123,8 +128,14 @@ export const personContext = async (store, asked, reference, options = {}) => {
123
128
  * `personContext` of a person already found, read in the identities and accounts `reads` names; their calendar
124
129
  * events in every calendar account of `readable`.
125
130
  */
126
- export const recordContext = async (store, record, reads, readable, { messages = CONTEXT_MESSAGES, bytes = CONTEXT_BYTES, since, now = Date.now() } = {}) => {
131
+ export const recordContext = async (store, record, reads, readable, { messages = CONTEXT_MESSAGES, bytes = CONTEXT_BYTES, since, now = Date.now(), calendarIds, scopes, } = {}) => {
127
132
  const recent = (message) => since === undefined || Date.parse(message.timestamp) >= since;
133
+ // A chat pinned to the other side of the owner's life stays out even when its account is readable.
134
+ const allowed = new Set(scopes ?? readable.map((one) => one.scope));
135
+ const inScope = async (key, scope, hits) => {
136
+ const pinned = await store.chats.chatScopes(key, [...new Set(hits.map((hit) => hit.chatId))]);
137
+ return hits.filter((hit) => allowed.has(pinned.get(hit.chatId) ?? scope));
138
+ };
128
139
  const shared = [];
129
140
  const notRead = [];
130
141
  const direct = [];
@@ -133,8 +144,8 @@ export const recordContext = async (store, record, reads, readable, { messages =
133
144
  const theirs = [];
134
145
  const mentions = [];
135
146
  let cut = false;
136
- for (const { key, identity } of reads) {
137
- const chats = await store.chats.chatsWith(key, identity.id);
147
+ for (const { key, scope, identity } of reads) {
148
+ const chats = (await store.chats.chatsWith(key, identity.id)).filter((chat) => allowed.has(chat.scope ?? scope));
138
149
  for (const chat of chats) {
139
150
  shared.push({ ...key, chatId: chat.id, title: chat.title, kind: chat.kind, lastMessageAt: chat.lastMessageAt });
140
151
  }
@@ -175,10 +186,12 @@ export const recordContext = async (store, record, reads, readable, { messages =
175
186
  cut ||= mail.hasMore;
176
187
  }
177
188
  const written = await store.messages.find({ account: key, senders: [identity.id], limit: messages });
178
- theirs.push(...written.items.map((hit) => toContext(key, hit, hit.chatTitle ?? null)).filter(recent));
189
+ theirs.push(...(await inScope(key, scope, written.items))
190
+ .map((hit) => toContext(key, hit, hit.chatTitle ?? null))
191
+ .filter(recent));
179
192
  cut ||= written.hasMore;
180
193
  const named = await store.messages.mentioning(key, { id: identity.id, username: identity.username }, messages);
181
- mentions.push(...named.items
194
+ mentions.push(...(await inScope(key, scope, named.items))
182
195
  .filter((hit) => hit.senderId !== identity.id)
183
196
  .map((hit) => toContext(key, hit, hit.chatTitle ?? null))
184
197
  .filter(recent));
@@ -189,7 +202,9 @@ export const recordContext = async (store, record, reads, readable, { messages =
189
202
  for (const one of readable)
190
203
  if ((await store.calendar.calendars(one.id)).length)
191
204
  calendars.push(one);
192
- const accountIds = calendars.map(({ id }) => id);
205
+ const readableIds = calendars.map(({ id }) => id);
206
+ // Only the calendars asked for, and never one outside the read scope.
207
+ const accountIds = calendarIds === undefined ? readableIds : readableIds.filter((id) => calendarIds.includes(id));
193
208
  const nothing = { items: [], cut: false };
194
209
  const upcoming = accountIds.length ? await eventsOnce(store, { personId, accountIds, from: now }, messages) : nothing;
195
210
  const upcomingIds = new Set(upcoming.items.map(({ id }) => id));
@@ -1,6 +1,6 @@
1
1
  import type { Id, Provider } from "../domain/models.js";
2
2
  import type { AccountKey, MessageStore, PreparationFact, PreparationNote, PreparationTask } from "../store/store.js";
3
- import { type ContextMessage, type ContextOptions, type PersonContext } from "./person-context.js";
3
+ import { type AccountScope, type ContextMessage, type ContextOptions, type PersonContext } from "./person-context.js";
4
4
  import { type PersonMeetingContextItem } from "./person-meeting-context.js";
5
5
  export declare const PREPARE_BYTES: number;
6
6
  export interface WaitingDialog {
@@ -37,13 +37,16 @@ export interface PersonPreparation extends PersonContext {
37
37
  tasks: SectionCoverage & {
38
38
  selection: "open, assigned to them in any role";
39
39
  accounts: string[];
40
+ scopes: Scopes;
40
41
  };
41
42
  facts: SectionCoverage & {
42
43
  selection: "accepted, about them or a project they are a member of";
44
+ scopes: Scopes;
43
45
  };
44
46
  /** `withheld` when the profile denies `contacts.notes.list`. */
45
47
  notes: SectionCoverage & {
46
48
  selection: "written by you, about them";
49
+ scopes: Scopes;
47
50
  withheld?: "contacts.notes.list";
48
51
  };
49
52
  /** `accounts`: the ones their meetings came from. */
@@ -55,6 +58,7 @@ export interface PersonPreparation extends PersonContext {
55
58
  };
56
59
  };
57
60
  }
61
+ type Scopes = readonly AccountScope[];
58
62
  /**
59
63
  * `contacts context` and what to know before talking to them: the one-to-one chats where they wrote last, open tasks,
60
64
  * accepted facts, your notes and their recent meetings, each item with its reference. The messages keep their own
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseMeetingReference } from "../meetings/index.js";
3
- import { CONTEXT_BYTES, CONTEXT_MESSAGES, personContext, readableAccounts, toContext, } from "./person-context.js";
3
+ import { CONTEXT_BYTES, CONTEXT_MESSAGES, personContext, readableAccounts, readableScopes, toContext, } from "./person-context.js";
4
4
  import { personMeetingContext } from "./person-meeting-context.js";
5
5
  export const PREPARE_BYTES = 96 * 1024;
6
6
  const MEETINGS = 5;
@@ -51,7 +51,8 @@ export const personPreparation = async (store, asked, reference, options = {}) =
51
51
  }
52
52
  waiting.sort((a, b) => Date.parse(b.message.timestamp) - Date.parse(a.message.timestamp));
53
53
  const accounts = context.accounts.map(({ provider, account }) => ({ provider, account }));
54
- const held = await store.people.preparation(context.person.uid, { accounts, limit });
54
+ const scopes = await readableScopes(store, asked, options.scopes);
55
+ const held = await store.people.preparation(context.person.uid, { accounts, scopes, limit });
55
56
  const readable = await readableAccounts(store, asked, options.scopes);
56
57
  const meetings = await meetingsOf(store, context.person.uid, readable, options.since, () => left);
57
58
  const sections = {
@@ -79,11 +80,17 @@ export const personPreparation = async (store, asked, reference, options = {}) =
79
80
  ...sections.tasks.coverage,
80
81
  selection: "open, assigned to them in any role",
81
82
  accounts: accounts.map(accountName),
83
+ scopes,
84
+ },
85
+ facts: {
86
+ ...sections.facts.coverage,
87
+ selection: "accepted, about them or a project they are a member of",
88
+ scopes,
82
89
  },
83
- facts: { ...sections.facts.coverage, selection: "accepted, about them or a project they are a member of" },
84
90
  notes: {
85
91
  ...sections.notes.coverage,
86
92
  selection: "written by you, about them",
93
+ scopes,
87
94
  ...(options.notes === false ? { withheld: "contacts.notes.list" } : {}),
88
95
  },
89
96
  meetings: {
@@ -22,6 +22,8 @@ export interface PersonTimeline {
22
22
  uid: string;
23
23
  name: string | null;
24
24
  };
25
+ /** The scopes read: the asked account's own, or the caller's `scopes`, narrowed by `scope`. */
26
+ scopes: Scope[];
25
27
  items: TimelineItem[];
26
28
  limits: {
27
29
  items: number;
@@ -33,6 +35,9 @@ export interface PersonTimeline {
33
35
  pending: number;
34
36
  }
35
37
  export interface TimelineOptions {
38
+ /** The scopes the caller may read; the asked account's own scope when absent. */
39
+ scopes?: readonly Scope[];
40
+ /** Narrows the read to one of the scopes the caller may read; another is refused. */
36
41
  scope?: Scope;
37
42
  /** ms, inclusive. */
38
43
  since?: number;
@@ -46,4 +51,4 @@ export interface TimelineOptions {
46
51
  * Everything one person took part in, across every identity linked to them, newest first. The index
47
52
  * is derived and nothing else keeps it current, so it is rebuilt for this one person first.
48
53
  */
49
- export declare const personTimeline: (store: MessageStore, asked: AccountKey, reference: string, { scope, since, until, cursor, limit }?: TimelineOptions) => Promise<PersonTimeline>;
54
+ export declare const personTimeline: (store: MessageStore, asked: AccountKey, reference: string, { scopes, scope, since, until, cursor, limit }?: TimelineOptions) => Promise<PersonTimeline>;
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatLocator } from "../domain/locator.js";
3
3
  import { pickPerson } from "../resolve.js";
4
+ import { readableScopes } from "./person-context.js";
4
5
  export const TIMELINE_ITEMS = 50;
5
6
  export const TIMELINE_MAX = 500;
6
7
  export const SCOPES = ["personal", "work"];
@@ -17,11 +18,17 @@ const boundOf = (cursor) => {
17
18
  * Everything one person took part in, across every identity linked to them, newest first. The index
18
19
  * is derived and nothing else keeps it current, so it is rebuilt for this one person first.
19
20
  */
20
- export const personTimeline = async (store, asked, reference, { scope, since, until, cursor, limit = TIMELINE_ITEMS } = {}) => {
21
+ export const personTimeline = async (store, asked, reference, { scopes, scope, since, until, cursor, limit = TIMELINE_ITEMS } = {}) => {
21
22
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > TIMELINE_MAX)
22
23
  throw new CliError("validation_error", `the limit takes 1–${TIMELINE_MAX}`);
23
24
  if (since !== undefined && until !== undefined && since > until)
24
25
  throw new CliError("validation_error", "the start of the range is after its end");
26
+ const allowed = await readableScopes(store, asked, scopes);
27
+ if (scope !== undefined && !allowed.includes(scope))
28
+ throw new CliError("permission_error", `this profile reads ${allowed.join(" and ")}, not ${scope}`, {
29
+ reason: "selection.out-of-scope",
30
+ });
31
+ const read = scope === undefined ? [...allowed] : [scope];
25
32
  const found = pickPerson(reference, await store.people.people(asked.provider, { account: asked.account }));
26
33
  const record = await store.people.personOf({ provider: asked.provider, id: found.id });
27
34
  if (!record)
@@ -29,7 +36,7 @@ export const personTimeline = async (store, asked, reference, { scope, since, un
29
36
  const personId = Number(record.uid);
30
37
  const pending = store.involvements.pending();
31
38
  const rows = store.involvements.forPerson(personId, {
32
- ...(scope === undefined ? {} : { scope }),
39
+ scopes: read,
33
40
  ...(since === undefined ? {} : { since }),
34
41
  ...(until === undefined ? {} : { until }),
35
42
  only: asked,
@@ -41,6 +48,7 @@ export const personTimeline = async (store, asked, reference, { scope, since, un
41
48
  const hasMore = rows.length > limit;
42
49
  return {
43
50
  person: { uid: record.uid, name: record.name },
51
+ scopes: read,
44
52
  items: shown.map((row) => ({
45
53
  at: new Date(row.occurredAt).toISOString(),
46
54
  subject: row.subjectType,
@@ -0,0 +1,4 @@
1
+ import type { MessageStore } from "../../../store/index.js";
2
+ import type { ProposalKind } from "../types.js";
3
+ /** Two identities' people that may be one; only the owner says whether they are. */
4
+ export declare const identityLinkKind: (store: Pick<MessageStore, "people" | "proposedActions">) => ProposalKind;