@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,113 @@
1
+ import { CATEGORIES, type Category } from "../domain/categories.js";
2
+ import type { DealKind } from "../domain/deals.js";
3
+ import { type Standing } from "../domain/relations.js";
4
+ import type { AccountKey, KnowledgeRelation, MessageStore } from "../store/index.js";
5
+ /** Items a context section lists before it says `hasMore`. */
6
+ export declare const SECTION_LIMIT = 20;
7
+ /** What one store list answers at most: a read that fills it may hold more. */
8
+ export declare const STORE_PAGE = 500;
9
+ /**
10
+ * A bounded list: the first `limit`, how many there are, and the memo command that lists the rest; `null` when
11
+ * nothing was left out or no one command lists exactly the rest.
12
+ */
13
+ export interface Section<T> {
14
+ items: T[];
15
+ total: number;
16
+ hasMore: boolean;
17
+ next: string | null;
18
+ }
19
+ export declare const sectionOf: <T>(all: T[], limit: number, next: string | null, { more, total, newest }?: {
20
+ more?: boolean;
21
+ total?: number;
22
+ newest?: boolean;
23
+ }) => Section<T>;
24
+ export declare const keyOf: ({ provider, account }: AccountKey) => string;
25
+ /**
26
+ * The accounts a context reads, the caller's `--source` or group already resolved; every account when none is
27
+ * given. A row no account reported — the owner's, an agent's — is always in it. `left` collects every account whose
28
+ * rows were kept out, so `coverage` can say so. `denied` holds the kinds the profile denies (`deals.list`,
29
+ * `leads.list`): no row, title or count of them is answered, and `coverage` says they were denied.
30
+ */
31
+ export interface Scope {
32
+ accounts: AccountKey[] | undefined;
33
+ has(account: AccountKey | string | null | undefined): boolean;
34
+ left: Set<string>;
35
+ denied: ReadonlySet<DealKind>;
36
+ /** A ref the answer may name: none of a denied kind. */
37
+ allows(ref: string): boolean;
38
+ }
39
+ export declare const scopeOf: (accounts: AccountKey[] | undefined, denied?: readonly DealKind[]) => Scope;
40
+ export declare const notRejected: <T extends {
41
+ review: string;
42
+ }>(rows: T[]) => T[];
43
+ /** One relationship, as seen from the entity a context is about: a link, or a proposal waiting for the owner. */
44
+ export interface RelationRole {
45
+ /** `link:<id>`; absent for a proposal. */
46
+ link?: string;
47
+ /** The pending `relationship` proposal's id, when it is one (`standing: proposed`). */
48
+ proposal?: string;
49
+ kind: KnowledgeRelation["kind"];
50
+ role: string | null;
51
+ standing: Standing;
52
+ /** The source account that reported it, `<provider>:<account>`. */
53
+ account?: string;
54
+ position?: string;
55
+ derived?: string;
56
+ startsAt?: string;
57
+ endsAt?: string;
58
+ }
59
+ /** Another entity and every relationship joining it to the one asked about: counted once however many. */
60
+ export interface Related {
61
+ ref: string;
62
+ name: string | null;
63
+ roles: RelationRole[];
64
+ }
65
+ /** What a context read, and what it did not and why: `notRead` names a missing source, never fills the gap. */
66
+ export interface Coverage {
67
+ /** `<provider>:<account>` of every account read. */
68
+ accounts: string[];
69
+ notRead: {
70
+ source: string;
71
+ reason: string;
72
+ }[];
73
+ }
74
+ /** A relationship's two ends and what it is, whether a link or a proposal. */
75
+ export interface Edge {
76
+ from: string;
77
+ to: string;
78
+ role: RelationRole;
79
+ }
80
+ /**
81
+ * Every relationship touching `ref`, both ways, in scope and of no denied kind: its links with their standing, ended
82
+ * ones too, and the `relationship` proposals waiting for the owner (plan §2.4), read through `listRelations`. `full`
83
+ * when more than a store page holds.
84
+ */
85
+ export declare const edgesOf: (store: MessageStore, ref: string, scope: Scope) => Promise<{
86
+ edges: Edge[];
87
+ full: boolean;
88
+ }>;
89
+ /** A title for each ref, read in one batch. */
90
+ export declare const namesOf: (store: MessageStore, refs: Iterable<string>) => Promise<Map<string, string | null>>;
91
+ /**
92
+ * The other ends of `edges` that `pick` keeps, each once with all its roles: the usable ones first, then those
93
+ * waiting for the owner, then the ended ones.
94
+ */
95
+ export declare const grouped: (edges: Edge[], pick: (edge: Edge) => string | undefined, names: Map<string, string | null>) => Related[];
96
+ export declare const usable: (edge: Edge) => boolean;
97
+ export { CATEGORIES, type Category };
98
+ /**
99
+ * Each organization's categories, derived from usable relationships in scope and never stored (NEED-2377): `client`
100
+ * is `customer-of` an own organization, `supplier` one an own organization is `customer-of`, `partner` `partner-of`
101
+ * one, `employer` one the owner's person is `member-of` as employee, contractor or founder. Read once per answer.
102
+ */
103
+ export declare const organizationCategories: (store: MessageStore, scope: Scope) => Promise<Map<string, Category[]>>;
104
+ /**
105
+ * The answer's `coverage`: what was read, each account kept out by the scope, and what each CRM account in scope
106
+ * said its last sync could not read, such as reporting lines with no department list. Named, never filled in.
107
+ */
108
+ export declare const coverageFor: (store: MessageStore, base: Coverage, scope: Scope) => Promise<Coverage>;
109
+ /** Newest first; one with no date last, in a fixed order. */
110
+ export declare const newestFirst: <T extends {
111
+ at: string | null;
112
+ ref: string;
113
+ }>(a: T, b: T) => number;
@@ -0,0 +1,156 @@
1
+ import { crmGapsOf } from "../crm/index.js";
2
+ import { CATEGORIES } from "../domain/categories.js";
3
+ import { isUsable } from "../domain/relations.js";
4
+ /** Items a context section lists before it says `hasMore`. */
5
+ export const SECTION_LIMIT = 20;
6
+ /** What one store list answers at most: a read that fills it may hold more. */
7
+ export const STORE_PAGE = 500;
8
+ export const sectionOf = (all, limit, next, { more = false, total = all.length, newest = false } = {}) => {
9
+ const cut = more || total > limit || all.length > limit;
10
+ return {
11
+ items: newest ? all.slice(Math.max(0, all.length - limit)) : all.slice(0, limit),
12
+ total,
13
+ hasMore: cut,
14
+ next: cut ? next : null,
15
+ };
16
+ };
17
+ export const keyOf = ({ provider, account }) => `${provider}:${account}`;
18
+ export const scopeOf = (accounts, denied = []) => {
19
+ const asked = accounts && new Set(accounts.map(keyOf));
20
+ const left = new Set();
21
+ const kinds = new Set(denied);
22
+ return {
23
+ accounts,
24
+ left,
25
+ denied: kinds,
26
+ has: (account) => {
27
+ if (account == null)
28
+ return true;
29
+ const key = typeof account === "string" ? account : keyOf(account);
30
+ if (asked === undefined || asked.has(key))
31
+ return true;
32
+ left.add(key);
33
+ return false;
34
+ },
35
+ allows: (ref) => !kinds.has(ref.slice(0, ref.indexOf(":"))),
36
+ };
37
+ };
38
+ export const notRejected = (rows) => rows.filter((row) => row.review !== "rejected");
39
+ const roleOf = (relation) => ({
40
+ link: `link:${relation.id}`,
41
+ kind: relation.kind,
42
+ role: relation.role,
43
+ standing: relation.standing,
44
+ ...(relation.account === undefined ? {} : { account: relation.account }),
45
+ ...(relation.position == null ? {} : { position: relation.position }),
46
+ ...(relation.derived === undefined ? {} : { derived: relation.derived }),
47
+ ...(relation.startsAt == null ? {} : { startsAt: relation.startsAt }),
48
+ ...(relation.endsAt == null ? {} : { endsAt: relation.endsAt }),
49
+ });
50
+ /**
51
+ * Every relationship touching `ref`, both ways, in scope and of no denied kind: its links with their standing, ended
52
+ * ones too, and the `relationship` proposals waiting for the owner (plan §2.4), read through `listRelations`. `full`
53
+ * when more than a store page holds.
54
+ */
55
+ export const edgesOf = async (store, ref, scope) => {
56
+ const { items, hasMore } = await store.knowledge.listRelations({
57
+ about: ref,
58
+ includeEnded: true,
59
+ deniedKinds: [...scope.denied],
60
+ limit: STORE_PAGE,
61
+ ...(scope.accounts === undefined ? {} : { accounts: scope.accounts }),
62
+ });
63
+ const edges = items.map((relation) => ({
64
+ from: relation.from,
65
+ to: relation.to,
66
+ role: relation.source === "proposal"
67
+ ? { proposal: relation.id, kind: relation.kind, role: relation.role, standing: relation.standing }
68
+ : roleOf(relation),
69
+ }));
70
+ return { edges, full: hasMore };
71
+ };
72
+ /** A title for each ref, read in one batch. */
73
+ export const namesOf = async (store, refs) => {
74
+ const summaries = await store.refs.summaries([...new Set(refs)]);
75
+ return new Map([...summaries].map(([ref, summary]) => [ref, summary.title]));
76
+ };
77
+ /**
78
+ * The other ends of `edges` that `pick` keeps, each once with all its roles: the usable ones first, then those
79
+ * waiting for the owner, then the ended ones.
80
+ */
81
+ export const grouped = (edges, pick, names) => {
82
+ const byRef = new Map();
83
+ for (const edge of edges) {
84
+ const ref = pick(edge);
85
+ if (ref === undefined)
86
+ continue;
87
+ const held = byRef.get(ref) ?? { ref, name: names.get(ref) ?? null, roles: [] };
88
+ held.roles.push(edge.role);
89
+ byRef.set(ref, held);
90
+ }
91
+ const rank = (one) => one.roles.some((role) => isUsable(role.standing))
92
+ ? 0
93
+ : one.roles.some((role) => role.standing === "proposed")
94
+ ? 1
95
+ : 2;
96
+ return [...byRef.values()].sort((a, b) => rank(a) - rank(b));
97
+ };
98
+ export const usable = (edge) => isUsable(edge.role.standing);
99
+ export { CATEGORIES };
100
+ /** The roles that make an organization the owner's employer. */
101
+ const EMPLOYED = new Set(["employee", "contractor", "founder"]);
102
+ /**
103
+ * Each organization's categories, derived from usable relationships in scope and never stored (NEED-2377): `client`
104
+ * is `customer-of` an own organization, `supplier` one an own organization is `customer-of`, `partner` `partner-of`
105
+ * one, `employer` one the owner's person is `member-of` as employee, contractor or founder. Read once per answer.
106
+ */
107
+ export const organizationCategories = async (store, scope) => {
108
+ const found = new Map();
109
+ const add = (ref, category) => found.set(ref, (found.get(ref) ?? new Set()).add(category));
110
+ for (const own of await store.knowledge.ownOrganizations())
111
+ for (const edge of (await edgesOf(store, own.ref, scope)).edges) {
112
+ if (!usable(edge))
113
+ continue;
114
+ const other = edge.from === own.ref ? edge.to : edge.to === own.ref ? edge.from : undefined;
115
+ if (!other?.startsWith("organization:"))
116
+ continue;
117
+ if (edge.role.kind === "customer-of")
118
+ add(other, edge.to === own.ref ? "client" : "supplier");
119
+ if (edge.role.kind === "partner-of")
120
+ add(other, "partner");
121
+ }
122
+ const owner = await store.people.owner();
123
+ if (owner)
124
+ for (const edge of (await edgesOf(store, `person:${owner.uid}`, scope)).edges)
125
+ if (usable(edge) &&
126
+ edge.role.kind === "member-of" &&
127
+ edge.to.startsWith("organization:") &&
128
+ EMPLOYED.has(edge.role.role ?? ""))
129
+ add(edge.to, "employer");
130
+ return new Map([...found].map(([ref, categories]) => [ref, CATEGORIES.filter((one) => categories.has(one))]));
131
+ };
132
+ /**
133
+ * The answer's `coverage`: what was read, each account kept out by the scope, and what each CRM account in scope
134
+ * said its last sync could not read, such as reporting lines with no department list. Named, never filled in.
135
+ */
136
+ export const coverageFor = async (store, base, scope) => {
137
+ const read = new Set(base.accounts);
138
+ const notRead = [...base.notRead];
139
+ const named = new Set(notRead.map((one) => one.source));
140
+ for (const kind of scope.denied)
141
+ notRead.push({ source: `${kind}s`, reason: "denied" });
142
+ if (scope.accounts !== undefined)
143
+ for (const key of await store.accounts.accounts())
144
+ if (!scope.has(key))
145
+ scope.left.add(keyOf(key));
146
+ for (const key of [...scope.left].sort())
147
+ if (!read.has(key) && !named.has(key))
148
+ notRead.push({ source: key, reason: "outside the accounts asked for" });
149
+ for (const key of await store.accounts.accounts())
150
+ if (scope.accounts === undefined || scope.accounts.some((one) => keyOf(one) === keyOf(key)))
151
+ for (const gap of await crmGapsOf(store, key))
152
+ notRead.push({ source: keyOf(key), reason: gap.message });
153
+ return { accounts: [...read].sort(), notRead };
154
+ };
155
+ /** Newest first; one with no date last, in a fixed order. */
156
+ export const newestFirst = (a, b) => (b.at ?? "").localeCompare(a.at ?? "") || a.ref.localeCompare(b.ref);
@@ -0,0 +1,50 @@
1
+ import type { AccountKey, LinkedIdentity, MessageStore, PersonRecord, StoredAccount } from "../store/store.js";
2
+ import { type Coverage, type Scope } from "./business-context.js";
3
+ /** A one-to-one chat, a mail or a calendar event with some of the people asked about. */
4
+ export interface Touch {
5
+ kind: "message" | "mail" | "meeting";
6
+ /** A message's or mail's locator, an `event:<id>`. */
7
+ ref: string;
8
+ /** The chat's title, the mail's subject, the event's title. */
9
+ title: string | null;
10
+ at: string | null;
11
+ /** `person:<uid>` of each one asked about it involves. */
12
+ people: string[];
13
+ }
14
+ export interface Communications {
15
+ /** Each message, mail and event once, however many of the people it involves. */
16
+ counts: {
17
+ messages: number;
18
+ mail: number;
19
+ meetings: number;
20
+ };
21
+ /** Newest first: every mail and meeting counted, and each chat's newest `limit` messages. */
22
+ items: Touch[];
23
+ /** A read stopped at its cap: there may be more than `counts` says. */
24
+ hasMore: boolean;
25
+ /** The accounts read, and the sources the people have nothing to read by; the scope's own gaps come after. */
26
+ coverage: Coverage;
27
+ }
28
+ export interface CommunicationsOptions {
29
+ /** ms, inclusive. */
30
+ since?: number;
31
+ /** ms, inclusive. */
32
+ until?: number;
33
+ /** Messages listed per chat; 0 counts only. */
34
+ limit?: number;
35
+ }
36
+ /** The stored accounts that hold a calendar: what a person's events are read from. */
37
+ export declare const calendarsOf: (store: MessageStore, stored: StoredAccount[]) => Promise<StoredAccount[]>;
38
+ /** The accounts read, and each source the people have nothing to read by. */
39
+ export declare const coverageOf: (people: PersonRecord[], read: Iterable<string>, calendars: boolean) => Coverage;
40
+ /** Each identity in each stored account of its provider that saw it, inside the scope. */
41
+ export declare const readsIn: (stored: AccountKey[], record: PersonRecord, scope: Scope) => {
42
+ key: AccountKey;
43
+ identity: LinkedIdentity;
44
+ }[];
45
+ /**
46
+ * What the owner's accounts in scope hold with these people: their one-to-one chats, mail with their address and
47
+ * calendar events they are invited to. A group chat is left out: what another member wrote there is not theirs. The
48
+ * owner is never one of the people read: through him every chat and mail of his would count.
49
+ */
50
+ export declare const communicationsOf: (store: MessageStore, asked: PersonRecord[], scope: Scope, { since, until, limit }?: CommunicationsOptions) => Promise<Communications>;
@@ -0,0 +1,140 @@
1
+ import { formatLocator } from "../domain/locator.js";
2
+ import { kindIn } from "../domain/providers.js";
3
+ import { keyOf, newestFirst } from "./business-context.js";
4
+ import { eventsOnce } from "./person-context.js";
5
+ /** Mail read per address when counting: past it the count says `hasMore`. */
6
+ const MAIL_ROWS = 500;
7
+ const EVENT_ROWS = 1000;
8
+ /** The stored accounts that hold a calendar: what a person's events are read from. */
9
+ export const calendarsOf = async (store, stored) => {
10
+ const held = [];
11
+ for (const account of stored)
12
+ if ((await store.calendar.calendars(account.id)).length > 0)
13
+ held.push(account);
14
+ return held;
15
+ };
16
+ /** The accounts read, and each source the people have nothing to read by. */
17
+ export const coverageOf = (people, read, calendars) => {
18
+ const notRead = [];
19
+ if (!people.some((person) => person.identities.some((one) => kindIn(one.provider) === "messages")))
20
+ notRead.push({ source: "messages", reason: "no messenger identity is linked to them" });
21
+ if (!people.some((person) => person.identities.some((one) => one.provider === "email")))
22
+ notRead.push({ source: "mail", reason: "no mail address is linked to them" });
23
+ if (!calendars)
24
+ notRead.push({ source: "events", reason: "no calendar account in the accounts read" });
25
+ return { accounts: [...new Set(read)].sort(), notRead };
26
+ };
27
+ /** Each identity in each stored account of its provider that saw it, inside the scope. */
28
+ export const readsIn = (stored, record, scope) => record.identities.flatMap((identity) => stored
29
+ .filter((one) => one.provider === identity.provider && identity.accounts.includes(one.account))
30
+ .map((one) => ({ key: { provider: one.provider, account: one.account }, identity }))
31
+ .filter(({ key }) => scope.has(key)));
32
+ /**
33
+ * What the owner's accounts in scope hold with these people: their one-to-one chats, mail with their address and
34
+ * calendar events they are invited to. A group chat is left out: what another member wrote there is not theirs. The
35
+ * owner is never one of the people read: through him every chat and mail of his would count.
36
+ */
37
+ export const communicationsOf = async (store, asked, scope, { since, until, limit = 0 } = {}) => {
38
+ const owner = (await store.people.owner())?.uid;
39
+ const people = asked.filter((person) => person.uid !== owner);
40
+ const stored = await store.accounts.storedAccounts();
41
+ const ids = new Map(stored.map((one) => [keyOf(one), one.id]));
42
+ const read = new Set();
43
+ const dialogs = new Set();
44
+ const threads = new Map();
45
+ const messages = new Map();
46
+ const mail = new Map();
47
+ const meetings = new Map();
48
+ let messageCount = 0;
49
+ let cut = false;
50
+ const sinceIso = since === undefined ? undefined : new Date(since).toISOString();
51
+ const untilIso = until === undefined ? undefined : new Date(until).toISOString();
52
+ const touch = (into, id, made, uid) => {
53
+ const held = into.get(id) ?? { ...made, people: [] };
54
+ if (!held.people.includes(`person:${uid}`))
55
+ held.people.push(`person:${uid}`);
56
+ into.set(id, held);
57
+ };
58
+ for (const person of people)
59
+ for (const { key, identity } of readsIn(stored, person, scope)) {
60
+ read.add(keyOf(key));
61
+ if (key.provider === "email") {
62
+ const emails = await store.mail.emails({
63
+ accountId: ids.get(keyOf(key)),
64
+ participant: identity.id,
65
+ limit: MAIL_ROWS + 1,
66
+ ...(since === undefined ? {} : { since }),
67
+ ...(until === undefined ? {} : { until: until + 1 }),
68
+ });
69
+ cut ||= emails.length > MAIL_ROWS;
70
+ for (const email of emails.slice(0, MAIL_ROWS)) {
71
+ const held = mail.get(email.id);
72
+ if (held) {
73
+ touch(mail, email.id, held, person.uid);
74
+ continue;
75
+ }
76
+ if (!threads.has(email.emailThreadId))
77
+ threads.set(email.emailThreadId, (await store.mail.thread(email.emailThreadId))?.thread.externalId ?? null);
78
+ const thread = threads.get(email.emailThreadId);
79
+ const at = email.receivedAt ?? email.sentAt;
80
+ touch(mail, email.id, {
81
+ kind: "mail",
82
+ ref: formatLocator({ ...key, chat: thread ?? String(email.emailThreadId), message: email.externalId }),
83
+ title: email.subject,
84
+ at: at === null ? null : new Date(at).toISOString(),
85
+ }, person.uid);
86
+ }
87
+ continue;
88
+ }
89
+ for (const chat of await store.chats.chatsWith(key, identity.id)) {
90
+ const id = `${keyOf(key)}/${chat.id}`;
91
+ if (chat.kind !== "dialog" || dialogs.has(id))
92
+ continue;
93
+ dialogs.add(id);
94
+ messageCount += await store.messages.countMessages(key, chat.id, {
95
+ ...(sinceIso === undefined ? {} : { since: sinceIso }),
96
+ ...(untilIso === undefined ? {} : { until: untilIso }),
97
+ });
98
+ if (limit === 0)
99
+ continue;
100
+ const page = await store.messages.messages(key, chat.id, {
101
+ limit,
102
+ ...(sinceIso === undefined ? {} : { since: sinceIso }),
103
+ ...(until === undefined ? {} : { until }),
104
+ });
105
+ for (const message of page.items)
106
+ touch(messages, `${id}/${message.id}`, {
107
+ kind: "message",
108
+ ref: formatLocator({ ...key, chat: chat.id, message: message.id }),
109
+ title: chat.title,
110
+ at: message.timestamp,
111
+ }, person.uid);
112
+ }
113
+ }
114
+ const calendars = (await calendarsOf(store, stored)).filter((one) => scope.has(one));
115
+ for (const person of calendars.length === 0 ? [] : people) {
116
+ const found = await eventsOnce(store, {
117
+ personId: Number(person.uid),
118
+ ...(scope.accounts === undefined ? {} : { accountIds: calendars.map(({ id }) => id) }),
119
+ ...(since === undefined ? {} : { from: since }),
120
+ ...(until === undefined ? {} : { to: until }),
121
+ newest: true,
122
+ }, EVENT_ROWS);
123
+ cut ||= found.cut;
124
+ for (const event of found.items)
125
+ touch(meetings, event.id, {
126
+ kind: "meeting",
127
+ ref: `event:${event.id}`,
128
+ title: event.title,
129
+ at: event.startsAt === null ? null : new Date(event.startsAt).toISOString(),
130
+ }, person.uid);
131
+ }
132
+ for (const key of calendars)
133
+ read.add(keyOf(key));
134
+ return {
135
+ counts: { messages: messageCount, mail: mail.size, meetings: meetings.size },
136
+ items: [...messages.values(), ...mail.values(), ...meetings.values()].sort(newestFirst),
137
+ hasMore: cut,
138
+ coverage: coverageOf(people, read, calendars.length > 0),
139
+ };
140
+ };
@@ -0,0 +1,90 @@
1
+ import type { DealKind } from "../domain/deals.js";
2
+ import { type Standing } from "../domain/relations.js";
3
+ import type { AccountKey, Deal, MessageStore, StageChange } from "../store/index.js";
4
+ import { type Category, type Coverage, type Related, type Section } from "./business-context.js";
5
+ import { type Communications, type Touch } from "./communications.js";
6
+ import { type MoneySection } from "./money-context.js";
7
+ import { type TaskLine } from "./organization-context.js";
8
+ /** Met or written to within the deal's lifetime by one of its people: an overlap of people, not a link. */
9
+ export type DealTouch = Touch & {
10
+ standing: Extract<Standing, "proposed">;
11
+ };
12
+ export interface DealContext {
13
+ /** The row as stored: its status is the CRM's or the owner's, and a stage named won is not a payment. */
14
+ deal: Deal;
15
+ /** The newest stages it entered, oldest of them first; `total` counts every one. */
16
+ stages: Section<StageChange>;
17
+ organization: {
18
+ ref: string;
19
+ name: string | null;
20
+ categories: Category[];
21
+ } | null;
22
+ /** Its people, each once with every role and the standing of each. */
23
+ participants: Section<Related>;
24
+ /** The participant whose usable role is `owner`, the CRM's "responsible". */
25
+ owner: Related | null;
26
+ project: {
27
+ ref: string;
28
+ name: string | null;
29
+ } | null;
30
+ /** Its project's invoices and payments and its organization's, each saying how it was reached. */
31
+ money: MoneySection;
32
+ /** From its creation to the day it closed, or now. */
33
+ window: {
34
+ since: string;
35
+ until: string;
36
+ };
37
+ communications: Section<DealTouch> & {
38
+ counts: Communications["counts"];
39
+ };
40
+ tasks: Section<TaskLine>;
41
+ coverage: Coverage;
42
+ }
43
+ export interface DealContextOptions {
44
+ /** The accounts read: a CRM's copy and relationships, and its people's messages, mail and events. */
45
+ accounts?: AccountKey[];
46
+ limit?: number;
47
+ /** ms: the end of an open deal's window; the clock when absent. */
48
+ now?: number;
49
+ /** The kinds the profile denies: a deal or lead of one is not answered. */
50
+ deniedKinds?: readonly DealKind[];
51
+ }
52
+ /**
53
+ * One answer about a deal or a lead from the store: the row, how it moved, its client, people, project, money and
54
+ * what its people said within its lifetime. Nothing is inferred from a stage's name. A CRM's copy outside
55
+ * `accounts` is not answered, and a CRM's relationships outside it are left out.
56
+ */
57
+ export declare const dealContext: (store: MessageStore, reference: string, { accounts, limit, now, deniedKinds }?: DealContextOptions) => Promise<DealContext>;
58
+ /** The compact form for a model's context: names, roles and standings, totals and counts, no row detail. */
59
+ export interface DealBrief {
60
+ ref: string;
61
+ kind: Deal["kind"];
62
+ title: string;
63
+ pipeline: string;
64
+ stage: string;
65
+ status: Deal["status"];
66
+ amount: string | null;
67
+ currency: string | null;
68
+ closeDate: string | null;
69
+ organization: string | null;
70
+ owner: string | null;
71
+ people: {
72
+ ref: string;
73
+ name: string | null;
74
+ roles: string[];
75
+ standing: Standing;
76
+ }[];
77
+ project: string | null;
78
+ /** The newest stage changes, `from → to`. */
79
+ stages: string[];
80
+ money: MoneySection["totals"] & {
81
+ unconfirmed: number;
82
+ complete: boolean;
83
+ };
84
+ communications: Communications["counts"] & {
85
+ standing: "proposed";
86
+ };
87
+ openTasks: number;
88
+ notRead: Coverage["notRead"];
89
+ }
90
+ export declare const dealBrief: (context: DealContext) => DealBrief;