@wirecat/cli-core 0.618.0 → 0.619.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 (274) hide show
  1. package/CHANGELOG.md +339 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/daily-archive-timer.d.ts +1 -1
  5. package/dist/background/deliver.d.ts +5 -2
  6. package/dist/background/deliver.js +30 -12
  7. package/dist/background/report/render.d.ts +3 -1
  8. package/dist/background/report/render.js +3 -1
  9. package/dist/calendar/cli/answers.d.ts +1 -0
  10. package/dist/calendar/cli/answers.js +6 -1
  11. package/dist/calendar/cli/index.js +2 -14
  12. package/dist/calendar/cli/people-link.d.ts +3 -0
  13. package/dist/calendar/cli/people-link.js +23 -0
  14. package/dist/calendar/index.d.ts +1 -1
  15. package/dist/calendar/index.js +1 -1
  16. package/dist/calendar/mcp/index.d.ts +12 -12
  17. package/dist/cli/base-stages-command.d.ts +22 -0
  18. package/dist/cli/base-stages-command.js +174 -0
  19. package/dist/cli/command-runs.d.ts +2 -0
  20. package/dist/cli/command-runs.js +3 -1
  21. package/dist/cli/config-command.js +6 -1
  22. package/dist/cli/context.js +1 -0
  23. package/dist/cli/group-lock.d.ts +42 -0
  24. package/dist/cli/group-lock.js +130 -0
  25. package/dist/cli/index.d.ts +7 -2
  26. package/dist/cli/index.js +7 -2
  27. package/dist/cli/messenger/backfill-command.js +27 -15
  28. package/dist/cli/messenger/contacts-command.js +10 -3
  29. package/dist/cli/messenger/context.js +1 -0
  30. package/dist/cli/messenger/doctor-command.js +3 -1
  31. package/dist/cli/messenger/models-command.js +1 -1
  32. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  33. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  34. package/dist/cli/model-catalogue-command.d.ts +3 -1
  35. package/dist/cli/model-catalogue-command.js +46 -2
  36. package/dist/cli/profile.d.ts +8 -0
  37. package/dist/cli/profile.js +25 -0
  38. package/dist/cli/program.js +2 -0
  39. package/dist/cli/runs/search-query.d.ts +1 -1
  40. package/dist/cli/runs/search-query.js +4 -0
  41. package/dist/cli/runs/search.d.ts +5 -1
  42. package/dist/cli/runs/search.js +12 -1
  43. package/dist/cli/search-left-out.d.ts +6 -1
  44. package/dist/cli/search-left-out.js +9 -4
  45. package/dist/cli/settings.d.ts +8 -0
  46. package/dist/cli/settings.js +17 -2
  47. package/dist/cli/shared-command-exports.d.ts +16 -0
  48. package/dist/cli/store-recover.d.ts +3 -3
  49. package/dist/cli/store-recover.js +26 -26
  50. package/dist/cli/store-settings.d.ts +2 -0
  51. package/dist/cli/store-settings.js +37 -9
  52. package/dist/crm/cli/index.js +38 -6
  53. package/dist/crm/group-hint.d.ts +8 -0
  54. package/dist/crm/group-hint.js +13 -0
  55. package/dist/crm/source.d.ts +12 -1
  56. package/dist/crm/sync.d.ts +31 -2
  57. package/dist/crm/sync.js +110 -3
  58. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  59. package/dist/crm/testing/acme-scenario.js +170 -0
  60. package/dist/crm/testing/index.d.ts +1 -0
  61. package/dist/crm/testing/index.js +1 -0
  62. package/dist/crm/testing/source-contract.js +12 -0
  63. package/dist/crm/testing/source.d.ts +2 -0
  64. package/dist/crm/testing/source.js +1 -0
  65. package/dist/domain/addresses.d.ts +13 -0
  66. package/dist/domain/addresses.js +63 -0
  67. package/dist/domain/categories.d.ts +3 -0
  68. package/dist/domain/categories.js +2 -0
  69. package/dist/domain/crm.d.ts +23 -0
  70. package/dist/domain/crm.js +7 -0
  71. package/dist/domain/mentions.d.ts +2 -12
  72. package/dist/domain/mentions.js +2 -19
  73. package/dist/domain/orders.d.ts +8 -1
  74. package/dist/domain/orders.js +6 -2
  75. package/dist/domain/phones.d.ts +26 -0
  76. package/dist/domain/phones.js +48 -0
  77. package/dist/domain/record-types.d.ts +1 -1
  78. package/dist/domain/record-types.js +1 -0
  79. package/dist/domain/records.d.ts +5 -0
  80. package/dist/domain/ref-summaries.d.ts +39 -0
  81. package/dist/domain/ref-summaries.js +51 -3
  82. package/dist/domain/relations.d.ts +12 -2
  83. package/dist/domain/relations.js +14 -3
  84. package/dist/domain/vcard.d.ts +2 -2
  85. package/dist/domain/vcard.js +4 -10
  86. package/dist/embeddings/models.d.ts +11 -3
  87. package/dist/embeddings/models.js +28 -4
  88. package/dist/entities/business-context.d.ts +149 -0
  89. package/dist/entities/business-context.js +192 -0
  90. package/dist/entities/contact-activity.d.ts +2 -0
  91. package/dist/entities/contact-activity.js +7 -1
  92. package/dist/entities/contact-context.d.ts +157 -0
  93. package/dist/entities/contact-context.js +2 -0
  94. package/dist/entities/deal.d.ts +10 -0
  95. package/dist/entities/deal.js +2 -0
  96. package/dist/entities/index.d.ts +23 -3
  97. package/dist/entities/index.js +5 -0
  98. package/dist/entities/mention.d.ts +4 -3
  99. package/dist/entities/mention.js +2 -1
  100. package/dist/entities/message-transfer.d.ts +4 -2
  101. package/dist/entities/message-transfer.js +2 -2
  102. package/dist/entities/model.d.ts +2 -2
  103. package/dist/entities/model.js +1 -1
  104. package/dist/entities/relationship.d.ts +4 -0
  105. package/dist/entities/relationship.js +4 -0
  106. package/dist/errors/reasons.js +37 -4
  107. package/dist/fetch/page.js +2 -1
  108. package/dist/index.d.ts +3 -2
  109. package/dist/index.js +3 -2
  110. package/dist/meetings/context-store.d.ts +2 -0
  111. package/dist/meetings/findings-rules.d.ts +4 -0
  112. package/dist/meetings/findings-rules.js +5 -2
  113. package/dist/meetings/result-items.d.ts +1 -0
  114. package/dist/meetings/result-items.js +1 -0
  115. package/dist/models/index.js +22 -5
  116. package/dist/runs/events.d.ts +11 -1
  117. package/dist/runs/events.js +3 -1
  118. package/dist/runs/log-attributes.js +4 -0
  119. package/dist/runs/log-events.js +2 -0
  120. package/dist/runs/recording.d.ts +3 -0
  121. package/dist/runs/recording.js +36 -12
  122. package/dist/runs/run.d.ts +12 -3
  123. package/dist/runs/run.js +32 -13
  124. package/dist/search/account-list.d.ts +6 -0
  125. package/dist/search/account-list.js +9 -3
  126. package/dist/search/groups.d.ts +68 -0
  127. package/dist/search/groups.js +172 -0
  128. package/dist/services/account-groups.d.ts +28 -0
  129. package/dist/services/account-groups.js +89 -0
  130. package/dist/services/archive.d.ts +7 -1
  131. package/dist/services/archive.js +19 -3
  132. package/dist/services/business-context.d.ts +113 -0
  133. package/dist/services/business-context.js +156 -0
  134. package/dist/services/communications.d.ts +50 -0
  135. package/dist/services/communications.js +140 -0
  136. package/dist/services/deal-context.d.ts +90 -0
  137. package/dist/services/deal-context.js +131 -0
  138. package/dist/services/deps.d.ts +2 -0
  139. package/dist/services/enrichment.d.ts +7 -2
  140. package/dist/services/enrichment.js +46 -5
  141. package/dist/services/events-search.js +2 -1
  142. package/dist/services/group-guard.d.ts +28 -0
  143. package/dist/services/group-guard.js +131 -0
  144. package/dist/services/index.d.ts +15 -2
  145. package/dist/services/index.js +9 -2
  146. package/dist/services/ingest.d.ts +12 -0
  147. package/dist/services/ingest.js +4 -0
  148. package/dist/services/meaning-model.d.ts +7 -0
  149. package/dist/services/meaning-model.js +20 -0
  150. package/dist/services/meeting-context.d.ts +6 -1
  151. package/dist/services/meeting-context.js +12 -5
  152. package/dist/services/message-resolution.js +2 -3
  153. package/dist/services/messages-meaning.js +4 -5
  154. package/dist/services/messages-search.d.ts +5 -1
  155. package/dist/services/messages-search.js +1 -1
  156. package/dist/services/model-downloads.d.ts +1 -1
  157. package/dist/services/model-downloads.js +6 -4
  158. package/dist/services/money-context.d.ts +73 -0
  159. package/dist/services/money-context.js +77 -0
  160. package/dist/services/notes-search.d.ts +4 -1
  161. package/dist/services/notes-search.js +19 -7
  162. package/dist/services/organization-context.d.ts +80 -0
  163. package/dist/services/organization-context.js +154 -0
  164. package/dist/services/people.d.ts +22 -6
  165. package/dist/services/people.js +38 -8
  166. package/dist/services/person-business.d.ts +43 -0
  167. package/dist/services/person-business.js +67 -0
  168. package/dist/services/person-context.d.ts +9 -1
  169. package/dist/services/person-context.js +5 -3
  170. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  171. package/dist/services/proposals/kinds/identity-link.js +48 -0
  172. package/dist/services/proposals/kinds/orders.js +1 -1
  173. package/dist/services/proposals/registry.js +2 -0
  174. package/dist/services/search-kind.d.ts +12 -5
  175. package/dist/services/search-kind.js +49 -10
  176. package/dist/services/text-model-choice.js +1 -1
  177. package/dist/store/accounts.d.ts +18 -0
  178. package/dist/store/accounts.js +18 -3
  179. package/dist/store/damage.d.ts +43 -10
  180. package/dist/store/damage.js +119 -36
  181. package/dist/store/decisions.js +3 -1
  182. package/dist/store/evidence-findings.d.ts +14 -0
  183. package/dist/store/evidence-findings.js +2 -0
  184. package/dist/store/exports.d.ts +2 -1
  185. package/dist/store/identity-links.d.ts +92 -0
  186. package/dist/store/identity-links.js +6 -0
  187. package/dist/store/index.d.ts +11 -5
  188. package/dist/store/index.js +5 -2
  189. package/dist/store/journal.d.ts +10 -0
  190. package/dist/store/journal.js +33 -0
  191. package/dist/store/marks.d.ts +19 -1
  192. package/dist/store/marks.js +23 -1
  193. package/dist/store/people.d.ts +22 -0
  194. package/dist/store/people.js +15 -1
  195. package/dist/store/sqlite/accounts.js +2 -0
  196. package/dist/store/sqlite/base-stages.d.ts +122 -0
  197. package/dist/store/sqlite/base-stages.js +443 -0
  198. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  199. package/dist/store/sqlite/base-suggest.js +62 -0
  200. package/dist/store/sqlite/business-contracts.js +10 -1
  201. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  202. package/dist/store/sqlite/crm-settings.js +56 -13
  203. package/dist/store/sqlite/crm.d.ts +13 -1
  204. package/dist/store/sqlite/crm.js +20 -4
  205. package/dist/store/sqlite/deals.d.ts +33 -0
  206. package/dist/store/sqlite/deals.js +42 -4
  207. package/dist/store/sqlite/decision-requests.js +7 -3
  208. package/dist/store/sqlite/email-index.js +8 -4
  209. package/dist/store/sqlite/evidence-findings.js +29 -5
  210. package/dist/store/sqlite/findings-core.js +4 -2
  211. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  212. package/dist/store/sqlite/identity-link-rows.js +146 -0
  213. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  214. package/dist/store/sqlite/identity-proposals.js +234 -0
  215. package/dist/store/sqlite/knowledge.js +2 -2
  216. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  217. package/dist/store/sqlite/link-kinds.js +1 -0
  218. package/dist/store/sqlite/link-row.d.ts +6 -0
  219. package/dist/store/sqlite/link-row.js +35 -0
  220. package/dist/store/sqlite/link-source.d.ts +10 -0
  221. package/dist/store/sqlite/link-source.js +16 -0
  222. package/dist/store/sqlite/manifest.js +1 -0
  223. package/dist/store/sqlite/meeting-context-links.js +9 -6
  224. package/dist/store/sqlite/memories.js +9 -7
  225. package/dist/store/sqlite/mentions.d.ts +4 -1
  226. package/dist/store/sqlite/mentions.js +14 -9
  227. package/dist/store/sqlite/migrations.generated.js +8 -0
  228. package/dist/store/sqlite/notes.d.ts +1 -2
  229. package/dist/store/sqlite/notes.js +4 -29
  230. package/dist/store/sqlite/open-store.js +3 -0
  231. package/dist/store/sqlite/open.js +11 -2
  232. package/dist/store/sqlite/orders.d.ts +2 -0
  233. package/dist/store/sqlite/orders.js +9 -3
  234. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  235. package/dist/store/sqlite/organization-categories.js +34 -0
  236. package/dist/store/sqlite/organizations.d.ts +5 -1
  237. package/dist/store/sqlite/organizations.js +14 -4
  238. package/dist/store/sqlite/person-links.d.ts +19 -4
  239. package/dist/store/sqlite/person-links.js +49 -11
  240. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  241. package/dist/store/sqlite/person-match-scan.js +251 -0
  242. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  243. package/dist/store/sqlite/person-matcher.js +32 -0
  244. package/dist/store/sqlite/proposed-actions.js +6 -0
  245. package/dist/store/sqlite/record-matching.d.ts +2 -8
  246. package/dist/store/sqlite/record-matching.js +8 -40
  247. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  248. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  249. package/dist/store/sqlite/record-relationships.js +243 -0
  250. package/dist/store/sqlite/record-run.d.ts +5 -0
  251. package/dist/store/sqlite/record-run.js +62 -2
  252. package/dist/store/sqlite/record-writes.d.ts +1 -1
  253. package/dist/store/sqlite/record-writes.js +4 -2
  254. package/dist/store/sqlite/records.js +27 -2
  255. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  256. package/dist/store/sqlite/ref-accounts.js +117 -0
  257. package/dist/store/sqlite/ref-summaries.js +5 -1
  258. package/dist/store/sqlite/relation-list.d.ts +4 -1
  259. package/dist/store/sqlite/relation-list.js +18 -2
  260. package/dist/store/sqlite/relation-proposals.d.ts +6 -0
  261. package/dist/store/sqlite/relation-proposals.js +3 -0
  262. package/dist/store/sqlite/relation-roles.js +12 -6
  263. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  264. package/dist/store/sqlite/reported-relations.js +59 -18
  265. package/dist/store/sqlite/schema.d.ts +32 -0
  266. package/dist/store/sqlite/schema.js +3 -0
  267. package/dist/store/sqlite/transaction.js +11 -1
  268. package/dist/store/store.d.ts +3 -0
  269. package/dist/store/store.js +5 -0
  270. package/dist/store/write-events.d.ts +18 -0
  271. package/dist/store/write-events.js +88 -0
  272. package/package.json +3 -3
  273. package/parity.json +11 -4
  274. 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,8 +89,15 @@ 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[]>;
95
103
  /**
@@ -115,7 +123,7 @@ export declare const recordContext: (store: MessageStore, record: PersonRecord,
115
123
  key: AccountKey;
116
124
  scope: AccountScope;
117
125
  identity: LinkedIdentity;
118
- }[], readable: readonly StoredAccount[], { messages, bytes, since, now }?: ContextOptions) => Promise<Omit<PersonContext, "person">>;
126
+ }[], readable: readonly StoredAccount[], { messages, bytes, since, now, calendarIds }?: ContextOptions) => Promise<Omit<PersonContext, "person">>;
119
127
  /** `max:Ana` names a person in another messenger of this store; a reference with no prefix, this one. */
120
128
  export declare const identityIn: (store: MessageStore, asked: AccountKey, reference: string) => Promise<IdentityRef>;
121
129
  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) {
@@ -123,7 +123,7 @@ export const personContext = async (store, asked, reference, options = {}) => {
123
123
  * `personContext` of a person already found, read in the identities and accounts `reads` names; their calendar
124
124
  * events in every calendar account of `readable`.
125
125
  */
126
- export const recordContext = async (store, record, reads, readable, { messages = CONTEXT_MESSAGES, bytes = CONTEXT_BYTES, since, now = Date.now() } = {}) => {
126
+ export const recordContext = async (store, record, reads, readable, { messages = CONTEXT_MESSAGES, bytes = CONTEXT_BYTES, since, now = Date.now(), calendarIds } = {}) => {
127
127
  const recent = (message) => since === undefined || Date.parse(message.timestamp) >= since;
128
128
  const shared = [];
129
129
  const notRead = [];
@@ -189,7 +189,9 @@ export const recordContext = async (store, record, reads, readable, { messages =
189
189
  for (const one of readable)
190
190
  if ((await store.calendar.calendars(one.id)).length)
191
191
  calendars.push(one);
192
- const accountIds = calendars.map(({ id }) => id);
192
+ const readableIds = calendars.map(({ id }) => id);
193
+ // Only the calendars asked for, and never one outside the read scope.
194
+ const accountIds = calendarIds === undefined ? readableIds : readableIds.filter((id) => calendarIds.includes(id));
193
195
  const nothing = { items: [], cut: false };
194
196
  const upcoming = accountIds.length ? await eventsOnce(store, { personId, accountIds, from: now }, messages) : nothing;
195
197
  const upcomingIds = new Set(upcoming.items.map(({ id }) => id));
@@ -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;
@@ -0,0 +1,48 @@
1
+ import { IDENTITY_LINK_KIND, proposerOfAction } from "../../../store/index.js";
2
+ import { actionStatus, kept, pushed, storedStatus } from "./shared.js";
3
+ const rowOf = (action) => {
4
+ const payload = action.payload;
5
+ const [from, to] = payload.persons;
6
+ return {
7
+ id: action.id,
8
+ kind: IDENTITY_LINK_KIND,
9
+ status: actionStatus(action.status),
10
+ project: null,
11
+ subject: `person:${from}`,
12
+ object: `person:${to}`,
13
+ summary: `${payload.identity} may be the same person as ${payload.with ?? `person:${to}`} (${payload.signal})`,
14
+ proposedBy: proposerOfAction(action),
15
+ reason: action.reason,
16
+ evidence: payload.evidence.slice(0, 5),
17
+ score: payload.score,
18
+ signals: null,
19
+ parts: null,
20
+ createdAt: action.createdAt,
21
+ };
22
+ };
23
+ /** Two identities' people that may be one; only the owner says whether they are. */
24
+ export const identityLinkKind = (store) => ({
25
+ kind: IDENTITY_LINK_KIND,
26
+ stored: [IDENTITY_LINK_KIND],
27
+ ownerOnly: true,
28
+ list: async (filter) => {
29
+ const status = storedStatus(filter);
30
+ const stored = await store.proposedActions.list({
31
+ kinds: [IDENTITY_LINK_KIND],
32
+ ...(status === undefined ? {} : { status }),
33
+ ...pushed(filter),
34
+ });
35
+ return kept(stored.map(rowOf), filter);
36
+ },
37
+ get: async (id) => rowOf(await store.proposedActions.get(id)),
38
+ decide: async (id, { confirm, by, reason }) => {
39
+ const decided = await store.people.decideLink(id, { confirm, by, ...(reason === undefined ? {} : { reason }) });
40
+ const person = decided.result?.person;
41
+ return {
42
+ id,
43
+ kind: IDENTITY_LINK_KIND,
44
+ status: confirm ? "confirmed" : "rejected",
45
+ made: person === undefined ? [] : [`person:${person}`],
46
+ };
47
+ },
48
+ });
@@ -4,6 +4,6 @@ export const orderKind = (store) => reviewedKind({
4
4
  type: "order",
5
5
  list: (options) => store.orders.list(options),
6
6
  get: (id) => store.orders.get(id),
7
- row: (order) => reviewedRow("order", order, order.supplier?.ref ?? null),
7
+ row: (order) => reviewedRow("order", order, (order.direction === "sale" ? order.customer : order.supplier)?.ref ?? null),
8
8
  decide: async (id, confirm, { by, reason }) => (confirm ? await store.orders.confirm(id, by, reason) : await store.orders.reject(id, by, reason)).ref,
9
9
  });
@@ -5,6 +5,7 @@ import { contractKind } from "./kinds/contracts.js";
5
5
  import { factKind } from "./kinds/fact.js";
6
6
  import { invoiceKind, paymentKind } from "./kinds/finance.js";
7
7
  import { findingsKind } from "./kinds/findings.js";
8
+ import { identityLinkKind } from "./kinds/identity-link.js";
8
9
  import { keyDocumentKind } from "./kinds/key-document.js";
9
10
  import { mailFindingsKind } from "./kinds/mail-findings.js";
10
11
  import { meetingFindingsKind } from "./kinds/meeting-findings.js";
@@ -152,6 +153,7 @@ export const proposalRegistry = (store) => {
152
153
  meetingFindingsKind(store),
153
154
  taskCloseKind(store),
154
155
  sourceReviewKind(store),
156
+ identityLinkKind(store),
155
157
  ])
156
158
  registry.register(kind);
157
159
  registry.register(actionKind(store, registry.claimed));
@@ -1,16 +1,23 @@
1
- import type { AppIdentity } from "../ports/app.js";
2
- import { type ListContext, type SkippedSource } from "../search/account-list.js";
1
+ import { type AppIdentity } from "../ports/app.js";
2
+ import { type SkippedSource } from "../search/account-list.js";
3
+ import { type GroupContext } from "../search/groups.js";
3
4
  import type { AccountKey, MessageStore, StoredAccount } from "../store/store.js";
4
5
  export type SearchKind = "messages" | "mail";
5
6
  export declare const NO_MAIL = "no_mail";
6
7
  export declare const MAIL = "email";
7
- /** What a `--source` list is resolved against: the store's accounts, groups and profiles, and the app running. */
8
- export declare const listContextOf: (store: MessageStore, account: AccountKey, app: AppIdentity | undefined, stored?: StoredAccount[]) => Promise<ListContext>;
8
+ /** The group `<PREFIX>_GROUP_LOCK` pins this process to; `all`, every account, locks nothing. */
9
+ export declare const groupLockOf: (app: AppIdentity | undefined, env: NodeJS.ProcessEnv | undefined) => string | undefined;
10
+ /**
11
+ * What a `--source` list is resolved against: the store's accounts, profiles and groups — the saved ones and `all`
12
+ * (WC-ACCT-13) — and the app running. Under a group lock in the run's `env` it holds only that group's
13
+ * accounts, so a reader that never scoped its run to the group still cannot name an account outside it.
14
+ */
15
+ export declare const listContextOf: (store: MessageStore, account: AccountKey, app: AppIdentity | undefined, stored?: StoredAccount[], env?: NodeJS.ProcessEnv) => Promise<GroupContext>;
9
16
  /**
10
17
  * `--source` as a list of accounts and groups: `undefined` when it is a bare word like `all` or `telegram`. The
11
18
  * accounts are those of `kind` the list names; an entry naming none of them is in `skipped`.
12
19
  */
13
- export declare const listedAccounts: (store: MessageStore, account: AccountKey, source: string | undefined, app: AppIdentity | undefined, kind?: SearchKind) => Promise<{
20
+ export declare const listedAccounts: (store: MessageStore, account: AccountKey, source: string | undefined, app: AppIdentity | undefined, kind?: SearchKind, env?: NodeJS.ProcessEnv) => Promise<{
14
21
  accounts: AccountKey[];
15
22
  skipped: SkippedSource[];
16
23
  } | undefined>;
@@ -1,35 +1,74 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { holdsKindOf, isKind, providerNamed } from "../domain/providers.js";
3
- import { entriesOfList, fitting, isAccountList } from "../search/account-list.js";
2
+ import { holdsKindOf, isDocumentAccountProvider, isFolderProvider, isKind, providerNamed } from "../domain/providers.js";
3
+ import { envName } from "../ports/app.js";
4
+ import { entriesOfList, fitting, isAccountList, keyOf, } from "../search/account-list.js";
5
+ import { ALL, groupEntries, groupMembership, hasGroup, OWNER_NOTES } from "../search/groups.js";
4
6
  export const NO_MAIL = "no_mail";
5
7
  export const MAIL = "email";
6
- /** What a `--source` list is resolved against: the store's accounts, groups and profiles, and the app running. */
7
- export const listContextOf = async (store, account, app, stored) => {
8
+ /** The group `<PREFIX>_GROUP_LOCK` pins this process to; `all`, every account, locks nothing. */
9
+ export const groupLockOf = (app, env) => {
10
+ const lock = app === undefined || env === undefined ? undefined : env[envName(app, "GROUP_LOCK")]?.trim();
11
+ return lock && lock.toLowerCase() !== ALL ? lock : undefined;
12
+ };
13
+ /**
14
+ * What a `--source` list is resolved against: the store's accounts, profiles and groups — the saved ones and `all`
15
+ * (WC-ACCT-13) — and the app running. Under a group lock in the run's `env` it holds only that group's
16
+ * accounts, so a reader that never scoped its run to the group still cannot name an account outside it.
17
+ */
18
+ export const listContextOf = async (store, account, app, stored, env) => {
8
19
  const all = stored ?? (await store.accounts.storedAccounts());
9
20
  // A fresh store has no row yet for the account it runs as.
10
21
  const held = all.some((one) => one.provider === account.provider && one.account === account.account)
11
22
  ? all
12
23
  : [...all, { id: 0, ...account, name: null, scope: "personal" }];
13
- return {
24
+ const context = {
14
25
  held,
15
26
  groups: await store.accounts.accountGroups(),
16
27
  profiles: await store.accounts.profiles(),
17
28
  running: { provider: account.provider, ...(app ? { command: app.command } : {}) },
18
29
  };
30
+ const membership = groupMembership(context);
31
+ const groups = groupEntries(context.groups);
32
+ const lock = groupLockOf(app, env);
33
+ if (lock === undefined)
34
+ return { ...context, groups, membership };
35
+ const members = hasGroup(membership.groups, lock) ? membership.groups[lock] : undefined;
36
+ if (!members)
37
+ throw new CliError("permission_error", `this process is locked to group ${lock} (${envName(app, "GROUP_LOCK")}), which does not exist`);
38
+ const only = new Set([...members, OWNER_NOTES].map(keyOf));
39
+ // A notes folder or a documents account is held under its own key but listed as `notes:<store id>`.
40
+ const listedAs = (one) => isFolderProvider(one.provider) || isDocumentAccountProvider(one.provider)
41
+ ? { provider: "notes", account: String(one.id) }
42
+ : one;
43
+ return {
44
+ ...context,
45
+ held: held.filter((one) => only.has(keyOf(listedAs(one)))),
46
+ groups: { [lock]: groups[lock] ?? [] },
47
+ membership: {
48
+ groups: { [lock]: members },
49
+ duplicates: membership.duplicates.filter(({ groups: names }) => names.includes(lock)),
50
+ suggested: membership.suggested.filter(({ group }) => group === lock),
51
+ unresolved: membership.unresolved,
52
+ },
53
+ only,
54
+ };
19
55
  };
20
56
  /**
21
57
  * `--source` as a list of accounts and groups: `undefined` when it is a bare word like `all` or `telegram`. The
22
58
  * accounts are those of `kind` the list names; an entry naming none of them is in `skipped`.
23
59
  */
24
- export const listedAccounts = async (store, account, source, app, kind) => {
25
- if (source === undefined)
60
+ export const listedAccounts = async (store, account, source, app, kind, env) => {
61
+ const lock = groupLockOf(app, env);
62
+ if (source === undefined && lock === undefined)
26
63
  return undefined;
27
64
  const stored = await store.accounts.storedAccounts();
28
65
  // A provider the store holds by that very name, and all, personal and bots, keep their old path.
29
- const registered = isKind(source) || (providerNamed(source) !== undefined && !stored.some(({ provider }) => provider === source));
30
- if (!isAccountList(source) && !registered)
66
+ const registered = source !== undefined &&
67
+ (isKind(source) || (providerNamed(source) !== undefined && !stored.some(({ provider }) => provider === source)));
68
+ // Under a lock every read goes through the list, which holds only the group's accounts.
69
+ if (lock === undefined && source !== undefined && !isAccountList(source) && !registered)
31
70
  return undefined;
32
- const entries = entriesOfList(source, await listContextOf(store, account, app, stored));
71
+ const entries = entriesOfList(source ?? `group:${lock}`, await listContextOf(store, account, app, stored, env));
33
72
  return fitting(entries, kind ? [kind] : ["messages", "mail"], `${app ? `${app.command} ` : ""}search ${kind ?? "messages"}`);
34
73
  };
35
74
  /**