@wirecat/cli-core 0.617.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 (306) hide show
  1. package/CHANGELOG.md +406 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/backfill.d.ts +21 -0
  5. package/dist/background/backfill.js +41 -0
  6. package/dist/background/daily-archive-timer.d.ts +1 -1
  7. package/dist/background/deliver.d.ts +5 -2
  8. package/dist/background/deliver.js +30 -12
  9. package/dist/background/report/messages.js +4 -1
  10. package/dist/background/report/render.d.ts +3 -1
  11. package/dist/background/report/render.js +3 -1
  12. package/dist/background/report/view.js +4 -1
  13. package/dist/background/schedules.d.ts +17 -0
  14. package/dist/background/schedules.js +21 -8
  15. package/dist/calendar/cli/answers.d.ts +1 -0
  16. package/dist/calendar/cli/answers.js +6 -1
  17. package/dist/calendar/cli/index.js +2 -14
  18. package/dist/calendar/cli/people-link.d.ts +3 -0
  19. package/dist/calendar/cli/people-link.js +23 -0
  20. package/dist/calendar/index.d.ts +1 -1
  21. package/dist/calendar/index.js +1 -1
  22. package/dist/calendar/mcp/index.d.ts +12 -12
  23. package/dist/cli/base-stages-command.d.ts +22 -0
  24. package/dist/cli/base-stages-command.js +174 -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.d.ts +5 -0
  29. package/dist/cli/context.js +1 -0
  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 +10 -4
  33. package/dist/cli/index.js +10 -4
  34. package/dist/cli/messenger/backfill-command.js +27 -15
  35. package/dist/cli/messenger/contacts-command.js +10 -3
  36. package/dist/cli/messenger/context.js +1 -0
  37. package/dist/cli/messenger/doctor-command.js +3 -1
  38. package/dist/cli/messenger/models-command.js +1 -1
  39. package/dist/cli/messenger/serve-command.js +24 -2
  40. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  41. package/dist/cli/messenger/serve-outdated.js +100 -0
  42. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  43. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  44. package/dist/cli/model-catalogue-command.d.ts +3 -1
  45. package/dist/cli/model-catalogue-command.js +46 -2
  46. package/dist/cli/profile.d.ts +8 -0
  47. package/dist/cli/profile.js +25 -0
  48. package/dist/cli/program.js +2 -0
  49. package/dist/cli/runs/search-query.d.ts +1 -1
  50. package/dist/cli/runs/search-query.js +4 -0
  51. package/dist/cli/runs/search.d.ts +5 -1
  52. package/dist/cli/runs/search.js +12 -1
  53. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  54. package/dist/cli/schedule/schedule-command.js +13 -0
  55. package/dist/cli/search-left-out.d.ts +6 -1
  56. package/dist/cli/search-left-out.js +9 -4
  57. package/dist/cli/settings.d.ts +8 -0
  58. package/dist/cli/settings.js +17 -2
  59. package/dist/cli/shared-command-exports.d.ts +16 -0
  60. package/dist/cli/store-recover.d.ts +3 -3
  61. package/dist/cli/store-recover.js +47 -23
  62. package/dist/cli/store-settings.d.ts +2 -0
  63. package/dist/cli/store-settings.js +37 -9
  64. package/dist/crm/cli/index.js +38 -6
  65. package/dist/crm/group-hint.d.ts +8 -0
  66. package/dist/crm/group-hint.js +13 -0
  67. package/dist/crm/source.d.ts +12 -1
  68. package/dist/crm/sync.d.ts +31 -2
  69. package/dist/crm/sync.js +110 -3
  70. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  71. package/dist/crm/testing/acme-scenario.js +170 -0
  72. package/dist/crm/testing/index.d.ts +1 -0
  73. package/dist/crm/testing/index.js +1 -0
  74. package/dist/crm/testing/source-contract.js +12 -0
  75. package/dist/crm/testing/source.d.ts +2 -0
  76. package/dist/crm/testing/source.js +1 -0
  77. package/dist/domain/addresses.d.ts +13 -0
  78. package/dist/domain/addresses.js +63 -0
  79. package/dist/domain/categories.d.ts +3 -0
  80. package/dist/domain/categories.js +2 -0
  81. package/dist/domain/crm.d.ts +23 -0
  82. package/dist/domain/crm.js +7 -0
  83. package/dist/domain/links.d.ts +17 -4
  84. package/dist/domain/links.js +20 -7
  85. package/dist/domain/mentions.d.ts +2 -12
  86. package/dist/domain/mentions.js +2 -19
  87. package/dist/domain/orders.d.ts +8 -1
  88. package/dist/domain/orders.js +6 -2
  89. package/dist/domain/phones.d.ts +26 -0
  90. package/dist/domain/phones.js +48 -0
  91. package/dist/domain/record-types.d.ts +1 -1
  92. package/dist/domain/record-types.js +1 -0
  93. package/dist/domain/records.d.ts +5 -0
  94. package/dist/domain/ref-summaries.d.ts +39 -0
  95. package/dist/domain/ref-summaries.js +51 -3
  96. package/dist/domain/relations.d.ts +27 -2
  97. package/dist/domain/relations.js +37 -3
  98. package/dist/domain/vcard.d.ts +2 -2
  99. package/dist/domain/vcard.js +4 -10
  100. package/dist/embeddings/models.d.ts +11 -3
  101. package/dist/embeddings/models.js +28 -4
  102. package/dist/entities/business-context.d.ts +149 -0
  103. package/dist/entities/business-context.js +192 -0
  104. package/dist/entities/contact-activity.d.ts +2 -0
  105. package/dist/entities/contact-activity.js +7 -1
  106. package/dist/entities/contact-context.d.ts +157 -0
  107. package/dist/entities/contact-context.js +2 -0
  108. package/dist/entities/deal.d.ts +10 -0
  109. package/dist/entities/deal.js +2 -0
  110. package/dist/entities/index.d.ts +23 -3
  111. package/dist/entities/index.js +5 -0
  112. package/dist/entities/mention.d.ts +4 -3
  113. package/dist/entities/mention.js +2 -1
  114. package/dist/entities/message-transfer.d.ts +4 -2
  115. package/dist/entities/message-transfer.js +2 -2
  116. package/dist/entities/model.d.ts +2 -2
  117. package/dist/entities/model.js +1 -1
  118. package/dist/entities/relationship.d.ts +4 -0
  119. package/dist/entities/relationship.js +4 -0
  120. package/dist/errors/reasons.js +44 -4
  121. package/dist/fetch/page.js +2 -1
  122. package/dist/index.d.ts +4 -3
  123. package/dist/index.js +4 -3
  124. package/dist/meetings/context-store.d.ts +2 -0
  125. package/dist/meetings/findings-rules.d.ts +4 -0
  126. package/dist/meetings/findings-rules.js +5 -2
  127. package/dist/meetings/mcp/index.d.ts +15 -15
  128. package/dist/meetings/result-items.d.ts +1 -0
  129. package/dist/meetings/result-items.js +1 -0
  130. package/dist/models/index.js +22 -5
  131. package/dist/runs/events.d.ts +11 -1
  132. package/dist/runs/events.js +3 -1
  133. package/dist/runs/log-attributes.js +4 -0
  134. package/dist/runs/log-events.js +2 -0
  135. package/dist/runs/recording.d.ts +3 -0
  136. package/dist/runs/recording.js +36 -12
  137. package/dist/runs/run.d.ts +12 -3
  138. package/dist/runs/run.js +32 -13
  139. package/dist/search/account-list.d.ts +6 -0
  140. package/dist/search/account-list.js +9 -3
  141. package/dist/search/groups.d.ts +68 -0
  142. package/dist/search/groups.js +172 -0
  143. package/dist/services/account-groups.d.ts +28 -0
  144. package/dist/services/account-groups.js +89 -0
  145. package/dist/services/archive.d.ts +7 -1
  146. package/dist/services/archive.js +19 -3
  147. package/dist/services/business-context.d.ts +113 -0
  148. package/dist/services/business-context.js +156 -0
  149. package/dist/services/communications.d.ts +50 -0
  150. package/dist/services/communications.js +140 -0
  151. package/dist/services/deal-context.d.ts +90 -0
  152. package/dist/services/deal-context.js +131 -0
  153. package/dist/services/deps.d.ts +2 -0
  154. package/dist/services/enrichment.d.ts +7 -2
  155. package/dist/services/enrichment.js +46 -5
  156. package/dist/services/events-search.js +2 -1
  157. package/dist/services/group-guard.d.ts +28 -0
  158. package/dist/services/group-guard.js +131 -0
  159. package/dist/services/index.d.ts +15 -2
  160. package/dist/services/index.js +9 -2
  161. package/dist/services/ingest.d.ts +12 -0
  162. package/dist/services/ingest.js +4 -0
  163. package/dist/services/link-scorers/chat-senders.js +39 -29
  164. package/dist/services/link-scorers/member-chats.js +4 -3
  165. package/dist/services/link-scorers/member-dialog.js +5 -7
  166. package/dist/services/link-scorers/scan.js +17 -8
  167. package/dist/services/link-scorers/shared.d.ts +6 -2
  168. package/dist/services/link-scorers/shared.js +6 -2
  169. package/dist/services/link-scorers/types.d.ts +2 -0
  170. package/dist/services/meaning-model.d.ts +7 -0
  171. package/dist/services/meaning-model.js +20 -0
  172. package/dist/services/meeting-context.d.ts +6 -1
  173. package/dist/services/meeting-context.js +12 -5
  174. package/dist/services/message-resolution.js +2 -3
  175. package/dist/services/messages-meaning.js +4 -5
  176. package/dist/services/messages-search.d.ts +5 -1
  177. package/dist/services/messages-search.js +1 -1
  178. package/dist/services/model-downloads.d.ts +1 -1
  179. package/dist/services/model-downloads.js +6 -4
  180. package/dist/services/money-context.d.ts +73 -0
  181. package/dist/services/money-context.js +77 -0
  182. package/dist/services/notes-search.d.ts +4 -1
  183. package/dist/services/notes-search.js +19 -7
  184. package/dist/services/organization-context.d.ts +80 -0
  185. package/dist/services/organization-context.js +154 -0
  186. package/dist/services/people.d.ts +22 -6
  187. package/dist/services/people.js +38 -8
  188. package/dist/services/person-business.d.ts +43 -0
  189. package/dist/services/person-business.js +67 -0
  190. package/dist/services/person-context.d.ts +9 -1
  191. package/dist/services/person-context.js +5 -3
  192. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  193. package/dist/services/proposals/kinds/identity-link.js +48 -0
  194. package/dist/services/proposals/kinds/orders.js +1 -1
  195. package/dist/services/proposals/registry.js +2 -0
  196. package/dist/services/search-kind.d.ts +12 -5
  197. package/dist/services/search-kind.js +49 -10
  198. package/dist/services/text-model-choice.js +1 -1
  199. package/dist/store/accounts.d.ts +18 -0
  200. package/dist/store/accounts.js +18 -3
  201. package/dist/store/damage.d.ts +43 -10
  202. package/dist/store/damage.js +119 -36
  203. package/dist/store/decisions.js +3 -1
  204. package/dist/store/evidence-findings.d.ts +14 -0
  205. package/dist/store/evidence-findings.js +2 -0
  206. package/dist/store/exports.d.ts +2 -1
  207. package/dist/store/identity-links.d.ts +92 -0
  208. package/dist/store/identity-links.js +6 -0
  209. package/dist/store/index.d.ts +11 -5
  210. package/dist/store/index.js +5 -2
  211. package/dist/store/journal.d.ts +10 -0
  212. package/dist/store/journal.js +33 -0
  213. package/dist/store/marks.d.ts +19 -1
  214. package/dist/store/marks.js +23 -1
  215. package/dist/store/migrations.d.ts +1 -1
  216. package/dist/store/migrations.js +35 -12
  217. package/dist/store/people.d.ts +22 -0
  218. package/dist/store/people.js +15 -1
  219. package/dist/store/recover.d.ts +34 -0
  220. package/dist/store/recover.js +188 -6
  221. package/dist/store/refill.d.ts +28 -0
  222. package/dist/store/refill.js +120 -0
  223. package/dist/store/sqlite/accounts.js +2 -0
  224. package/dist/store/sqlite/base-stages.d.ts +122 -0
  225. package/dist/store/sqlite/base-stages.js +443 -0
  226. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  227. package/dist/store/sqlite/base-suggest.js +62 -0
  228. package/dist/store/sqlite/business-contracts.js +10 -1
  229. package/dist/store/sqlite/clients.d.ts +7 -3
  230. package/dist/store/sqlite/clients.js +11 -7
  231. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  232. package/dist/store/sqlite/crm-settings.js +56 -13
  233. package/dist/store/sqlite/crm.d.ts +13 -1
  234. package/dist/store/sqlite/crm.js +20 -4
  235. package/dist/store/sqlite/deals.d.ts +33 -0
  236. package/dist/store/sqlite/deals.js +42 -4
  237. package/dist/store/sqlite/decision-requests.js +7 -3
  238. package/dist/store/sqlite/email-index.js +17 -15
  239. package/dist/store/sqlite/evidence-findings.js +29 -5
  240. package/dist/store/sqlite/findings-core.js +4 -2
  241. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  242. package/dist/store/sqlite/identity-link-rows.js +146 -0
  243. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  244. package/dist/store/sqlite/identity-proposals.js +234 -0
  245. package/dist/store/sqlite/knowledge.js +5 -3
  246. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  247. package/dist/store/sqlite/link-kinds.js +1 -0
  248. package/dist/store/sqlite/link-row.d.ts +6 -0
  249. package/dist/store/sqlite/link-row.js +35 -0
  250. package/dist/store/sqlite/link-source.d.ts +10 -0
  251. package/dist/store/sqlite/link-source.js +16 -0
  252. package/dist/store/sqlite/manifest.js +1 -0
  253. package/dist/store/sqlite/meeting-context-links.js +9 -6
  254. package/dist/store/sqlite/memories.js +9 -7
  255. package/dist/store/sqlite/mentions.d.ts +4 -1
  256. package/dist/store/sqlite/mentions.js +14 -9
  257. package/dist/store/sqlite/migrations.generated.js +8 -0
  258. package/dist/store/sqlite/note-index.js +9 -7
  259. package/dist/store/sqlite/notes.d.ts +2 -3
  260. package/dist/store/sqlite/notes.js +6 -29
  261. package/dist/store/sqlite/open-store.js +3 -0
  262. package/dist/store/sqlite/open.js +11 -2
  263. package/dist/store/sqlite/orders.d.ts +2 -0
  264. package/dist/store/sqlite/orders.js +9 -3
  265. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  266. package/dist/store/sqlite/organization-categories.js +34 -0
  267. package/dist/store/sqlite/organizations.d.ts +5 -1
  268. package/dist/store/sqlite/organizations.js +14 -4
  269. package/dist/store/sqlite/person-links.d.ts +19 -4
  270. package/dist/store/sqlite/person-links.js +49 -11
  271. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  272. package/dist/store/sqlite/person-match-scan.js +251 -0
  273. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  274. package/dist/store/sqlite/person-matcher.js +32 -0
  275. package/dist/store/sqlite/proposed-actions.js +6 -0
  276. package/dist/store/sqlite/record-matching.d.ts +2 -8
  277. package/dist/store/sqlite/record-matching.js +8 -40
  278. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  279. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  280. package/dist/store/sqlite/record-relationships.js +243 -0
  281. package/dist/store/sqlite/record-run.d.ts +5 -0
  282. package/dist/store/sqlite/record-run.js +62 -2
  283. package/dist/store/sqlite/record-writes.d.ts +1 -1
  284. package/dist/store/sqlite/record-writes.js +4 -2
  285. package/dist/store/sqlite/records.js +27 -2
  286. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  287. package/dist/store/sqlite/ref-accounts.js +117 -0
  288. package/dist/store/sqlite/ref-summaries.js +5 -1
  289. package/dist/store/sqlite/relation-list.d.ts +4 -1
  290. package/dist/store/sqlite/relation-list.js +20 -2
  291. package/dist/store/sqlite/relation-proposals.d.ts +18 -1
  292. package/dist/store/sqlite/relation-proposals.js +53 -11
  293. package/dist/store/sqlite/relation-roles.js +12 -6
  294. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  295. package/dist/store/sqlite/reported-relations.js +59 -18
  296. package/dist/store/sqlite/schema.d.ts +32 -0
  297. package/dist/store/sqlite/schema.js +3 -0
  298. package/dist/store/sqlite/transaction.d.ts +13 -0
  299. package/dist/store/sqlite/transaction.js +33 -15
  300. package/dist/store/store.d.ts +3 -0
  301. package/dist/store/store.js +5 -0
  302. package/dist/store/write-events.d.ts +18 -0
  303. package/dist/store/write-events.js +88 -0
  304. package/package.json +3 -3
  305. package/parity.json +11 -4
  306. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -9,6 +9,8 @@ export const providerErrorKey = (value) => typeof value === "string" && /^[A-Za-
9
9
  * ```
10
10
  */
11
11
  export const renderEvent = (event) => {
12
+ if (event.event === "store")
13
+ return `${MARK.store} ${event.operation.padEnd(16)} ${event.table} ${event.op} ${event.n}`;
12
14
  if (event.event === "warning") {
13
15
  const counts = Object.entries(event.counts ?? {}).map(([field, count]) => `${count} ${field}`);
14
16
  return [`${MARK.warning} ${(event.operation ?? "").padEnd(16)} ${event.code}`, ...counts, event.detail]
@@ -53,6 +55,6 @@ export const renderEvent = (event) => {
53
55
  }
54
56
  return `${MARK[event.event]} ${event.operation.padEnd(16)} ${parts.join(" ")}`.trimEnd();
55
57
  };
56
- const MARK = { request: "→", response: "←", cache: "•", warning: "!" };
58
+ const MARK = { request: "→", response: "←", cache: "•", warning: "!", store: "+" };
57
59
  const age = (ms) => (ms < 1000 ? `${ms}ms` : `${Math.round(ms / 1000)}s`);
58
60
  const size = (bytes) => (bytes < 1000 ? `${bytes} B` : `${(bytes / 1000).toFixed(1)} kB`);
@@ -24,6 +24,10 @@ const diagnostic = {
24
24
  detail: true,
25
25
  reason: true,
26
26
  ageMs: true,
27
+ kind: true,
28
+ table: true,
29
+ op: true,
30
+ n: true,
27
31
  };
28
32
  const send = {
29
33
  profile: true,
@@ -9,6 +9,7 @@ export const CORE_LOG_EVENTS = defineLogEvents([
9
9
  meaning: "a read was answered from what was kept, without asking the messenger",
10
10
  keys: ["operation", "reason"],
11
11
  },
12
+ { id: "store.write", meaning: "a committed write changed rows of one store table", keys: ["table", "op", "n"] },
12
13
  { id: "command.crashed", meaning: "a command failed on a bug; where, never what", keys: ["error_class", "frames"] },
13
14
  {
14
15
  id: "events.dropped",
@@ -32,4 +33,5 @@ export const DIAGNOSTIC_LOG_EVENTS = {
32
33
  response: "provider.response",
33
34
  warning: "client.warning",
34
35
  cache: "cache.answered",
36
+ store: "store.write",
35
37
  };
@@ -19,6 +19,7 @@ export interface RecordingOptions {
19
19
  runsDir?: string;
20
20
  keepDays?: number;
21
21
  keepSuccessDays?: number;
22
+ keepStoreDays?: number;
22
23
  maxBytes?: number;
23
24
  now?: () => Date;
24
25
  /** The caller's trace; otherwise the enclosing run's, otherwise `TRACEPARENT` from `env`. */
@@ -56,6 +57,8 @@ export declare const wasSettled: (error: unknown) => boolean;
56
57
  /** A run of a loop that never ends must not fill the disk: past these, events are counted by operation instead. */
57
58
  export declare const EVENTS_AT_MOST = 2000;
58
59
  export declare const EVENT_BYTES_AT_MOST: number;
60
+ /** Past this many, store events are summed by table and change and written as one each when the run ends. */
61
+ export declare const STORE_EVENTS_AT_MOST = 100;
59
62
  /**
60
63
  * Where a crash happened, not what it said: the class and up to ten frames as `function file:line`,
61
64
  * paths cut to the package's own (`framesOf`). **Never `message`** in an event — it can hold whatever the
@@ -3,7 +3,7 @@ import { isCliFailure, storeDamaged } from "../errors/failures.js";
3
3
  import { markStoreDamaged } from "../store/marks.js";
4
4
  import { storePath } from "../store/path.js";
5
5
  import { endpointTemplate, errorDetailOf, framesOf } from "./error-detail.js";
6
- import { providerErrorKey, renderEvent } from "./events.js";
6
+ import { providerErrorKey, renderEvent, } from "./events.js";
7
7
  import { DIAGNOSTIC_LOG_EVENTS } from "./log-events.js";
8
8
  import { logAttributes } from "./log-keys.js";
9
9
  import { newRunId, runsDirFor, startRun } from "./run.js";
@@ -62,6 +62,7 @@ export const startRecording = (options) => {
62
62
  },
63
63
  ...(options.keepDays === undefined ? {} : { keepDays: options.keepDays }),
64
64
  ...(options.keepSuccessDays === undefined ? {} : { keepSuccessDays: options.keepSuccessDays }),
65
+ ...(options.keepStoreDays === undefined ? {} : { keepStoreDays: options.keepStoreDays }),
65
66
  ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),
66
67
  now,
67
68
  ...extra,
@@ -71,6 +72,7 @@ export const startRecording = (options) => {
71
72
  const held = !run && options.keepFailed ? [] : undefined;
72
73
  const counted = { wire: 0, operation: 0 };
73
74
  let refused;
75
+ let wroteStore = false;
74
76
  const cap = capped();
75
77
  const requests = () => (counted.wire > 0 ? counted.wire : counted.operation);
76
78
  const events = (event) => {
@@ -78,6 +80,8 @@ export const startRecording = (options) => {
78
80
  counted[event.level === "wire" ? "wire" : "operation"] += 1;
79
81
  if (event.event === "response" && event.outcome === "error")
80
82
  refused = event;
83
+ if (event.event === "store")
84
+ wroteStore = true;
81
85
  if (options.trace)
82
86
  streams.diagnostic(options.format === "pretty" ? renderEvent(event) : JSON.stringify(logAttributes(event)));
83
87
  if (run)
@@ -99,13 +103,14 @@ export const startRecording = (options) => {
99
103
  events,
100
104
  succeed: async (answer) => {
101
105
  const partial = partialOutcome(answer);
102
- const kept = run ?? (partial && held ? keep(open({ startedAt })) : undefined);
106
+ const kept = run ?? ((partial || wroteStore) && held ? keep(open({ startedAt })) : undefined);
103
107
  if (kept)
104
108
  cap.close(kept);
105
109
  await kept?.finish(partial ? "partial" : "success", {
106
110
  requests: requests(),
107
111
  ...cap.dropped(),
108
112
  ...(partial ? { partial } : {}),
113
+ ...(!run && !partial && wroteStore ? { keptBecauseStore: true } : {}),
109
114
  });
110
115
  },
111
116
  fail: async (thrown) => {
@@ -142,26 +147,45 @@ const HELD_AT_MOST = 500;
142
147
  /** A run of a loop that never ends must not fill the disk: past these, events are counted by operation instead. */
143
148
  export const EVENTS_AT_MOST = 2000;
144
149
  export const EVENT_BYTES_AT_MOST = 1024 * 1024;
150
+ /** Past this many, store events are summed by table and change and written as one each when the run ends. */
151
+ export const STORE_EVENTS_AT_MOST = 100;
145
152
  const capped = () => {
146
153
  let lines = 0;
147
154
  let bytes = 0;
148
155
  let dropped = 0;
156
+ let stores = 0;
149
157
  const byOperation = {};
158
+ const summed = new Map();
159
+ const write = (run, event) => {
160
+ // The record's own envelope (time, ids of the run, resource) is about 200 bytes on top of its attributes.
161
+ const size = JSON.stringify(logAttributes(event)).length + 200;
162
+ if (lines >= EVENTS_AT_MOST || bytes + size > EVENT_BYTES_AT_MOST) {
163
+ dropped += 1;
164
+ const operation = "operation" in event && event.operation ? event.operation : event.event;
165
+ byOperation[operation] = (byOperation[operation] ?? 0) + 1;
166
+ return;
167
+ }
168
+ lines += 1;
169
+ bytes += size;
170
+ logEvent(run, event);
171
+ };
150
172
  return {
151
173
  log: (run, event) => {
152
- // The record's own envelope (time, ids of the run, resource) is about 200 bytes on top of its attributes.
153
- const size = JSON.stringify(logAttributes(event)).length + 200;
154
- if (lines >= EVENTS_AT_MOST || bytes + size > EVENT_BYTES_AT_MOST) {
155
- dropped += 1;
156
- const operation = "operation" in event && event.operation ? event.operation : event.event;
157
- byOperation[operation] = (byOperation[operation] ?? 0) + 1;
174
+ if (event.event === "store" && ++stores > STORE_EVENTS_AT_MOST) {
175
+ const key = `${event.table} ${event.op}`;
176
+ const sum = summed.get(key);
177
+ if (sum)
178
+ sum.n += event.n;
179
+ else
180
+ summed.set(key, { ...event });
158
181
  return;
159
182
  }
160
- lines += 1;
161
- bytes += size;
162
- logEvent(run, event);
183
+ write(run, event);
163
184
  },
164
185
  close: (run) => {
186
+ for (const sum of summed.values())
187
+ write(run, sum);
188
+ summed.clear();
165
189
  if (dropped > 0)
166
190
  run.logger.warn({ event: "events.dropped", dropped, counts: byOperation });
167
191
  },
@@ -178,7 +202,7 @@ const logEvent = (run, event) => {
178
202
  };
179
203
  if (event.event === "warning")
180
204
  run.logger.warn(record);
181
- else if (event.event !== "cache" && event.outcome === "error")
205
+ else if ((event.event === "request" || event.event === "response") && event.outcome === "error")
182
206
  run.logger.error(record);
183
207
  else
184
208
  run.logger.info(record);
@@ -43,10 +43,14 @@ export interface RunMetadata {
43
43
  providerError?: string;
44
44
  /** Written only because it failed: recording was not asked for. */
45
45
  keptBecauseFailed?: boolean;
46
+ /** Written only because it wrote the store, so its counts say what to fetch again after a damage. */
47
+ keptBecauseStore?: boolean;
46
48
  /** Every operation its events named, so a search by operation need not open them. */
47
49
  operations?: string[];
48
50
  /** Every `errorCode` and warning `code` its events carried, for the same reason. */
49
51
  codes?: string[];
52
+ /** Every table its store events wrote, for the same reason. */
53
+ tables?: string[];
50
54
  /** The caller's trace: the MCP client's, or the schedule's or job's that started it. */
51
55
  traceId?: string;
52
56
  /** The whole command with the program's name, `max messages list`; `command` stays the run's short name. */
@@ -77,6 +81,8 @@ export interface StartRunOptions {
77
81
  keepDays?: number;
78
82
  /** Successful runs older than this are removed sooner than the failures `keepDays` keeps. */
79
83
  keepSuccessDays?: number;
84
+ /** A successful run that wrote the store is kept this long, whatever `keepSuccessDays` says. */
85
+ keepStoreDays?: number;
80
86
  /** The runs folder's size limit in bytes: past it, the oldest successful runs go first, then the oldest days. */
81
87
  maxBytes?: number;
82
88
  /**
@@ -106,6 +112,7 @@ export interface Run {
106
112
  }
107
113
  export declare const KEEP_RUNS_FOR_DAYS = 30;
108
114
  export declare const KEEP_SUCCESSFUL_RUNS_FOR_DAYS = 7;
115
+ export declare const KEEP_STORE_RUNS_FOR_DAYS = 3;
109
116
  export declare const RUNS_SIZE_LIMIT_MB = 200;
110
117
  /** `<state dir>/runs` — never the cache directory: a cache is deleted to fix a cache, and a run cannot be rebuilt. */
111
118
  export declare const runsDirFor: (app: AppIdentity, env?: NodeJS.ProcessEnv) => string;
@@ -161,15 +168,17 @@ export declare const findRun: (runsDir: string, id: string) => {
161
168
  export declare const readEvents: (dir: string) => Record<string, unknown>[];
162
169
  /**
163
170
  * Removes every day older than `keepDays`, then the successful runs of every day older than `keepSuccessDays`, and
164
- * answers how many days went. Then, once a day, the folder is measured against `maxBytes`: successful runs go first,
165
- * oldest day first, then whole days, until it fits.
171
+ * answers how many days went. A success that wrote the store is kept for `keepStoreDays` instead when that is longer,
172
+ * and one kept only because it wrote the store goes after `keepStoreDays`. Then, once a day, the folder is measured
173
+ * against `maxBytes`: successful runs go first, oldest day first, then whole days, until it fits.
166
174
  *
167
175
  * A day at a time, by the directory name and the day's index, so no run has to be opened to decide — and a directory
168
176
  * that is not a date is left alone rather than guessed at.
169
177
  */
170
- export declare const pruneRuns: (runsDir: string, { keepDays, keepSuccessDays, maxBytes, now, }: {
178
+ export declare const pruneRuns: (runsDir: string, { keepDays, keepSuccessDays, keepStoreDays, maxBytes, now, }: {
171
179
  keepDays: number;
172
180
  keepSuccessDays?: number;
181
+ keepStoreDays?: number;
173
182
  maxBytes?: number;
174
183
  now: Date;
175
184
  }) => number;
package/dist/runs/run.js CHANGED
@@ -7,6 +7,7 @@ import { LOG_ATTRIBUTES } from "./log-attributes.js";
7
7
  import { fromLogAttributes, logAttributes, snakeLogger } from "./log-keys.js";
8
8
  export const KEEP_RUNS_FOR_DAYS = 30;
9
9
  export const KEEP_SUCCESSFUL_RUNS_FOR_DAYS = 7;
10
+ export const KEEP_STORE_RUNS_FOR_DAYS = 3;
10
11
  export const RUNS_SIZE_LIMIT_MB = 200;
11
12
  /** `<state dir>/runs` — never the cache directory: a cache is deleted to fix a cache, and a run cannot be rebuilt. */
12
13
  export const runsDirFor = (app, env = process.env) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "runs");
@@ -35,6 +36,7 @@ export const startRun = (options) => {
35
36
  pruneRuns(options.runsDir, {
36
37
  keepDays: options.keepDays ?? KEEP_RUNS_FOR_DAYS,
37
38
  keepSuccessDays: options.keepSuccessDays ?? KEEP_SUCCESSFUL_RUNS_FOR_DAYS,
39
+ keepStoreDays: options.keepStoreDays ?? KEEP_STORE_RUNS_FOR_DAYS,
38
40
  maxBytes: options.maxBytes ?? RUNS_SIZE_LIMIT_MB * 1024 * 1024,
39
41
  now: startedAt,
40
42
  });
@@ -79,10 +81,13 @@ export const startRun = (options) => {
79
81
  let finished = false;
80
82
  const operations = new Set();
81
83
  const codes = new Set();
84
+ const tables = new Set();
82
85
  const noted = (level) => (event, message) => {
83
- const { operation, errorCode, error_code, code } = event;
86
+ const { operation, errorCode, error_code, code, kind, table } = event;
84
87
  if (typeof operation === "string")
85
88
  operations.add(operation);
89
+ if (kind === "store" && typeof table === "string")
90
+ tables.add(table);
86
91
  for (const value of [errorCode, error_code, code])
87
92
  if (typeof value === "string")
88
93
  codes.add(value);
@@ -109,6 +114,7 @@ export const startRun = (options) => {
109
114
  durationMs: completedAt.getTime() - startedAt.getTime(),
110
115
  operations: [...operations].sort(),
111
116
  codes: [...codes].sort(),
117
+ ...(tables.size > 0 ? { tables: [...tables].sort() } : {}),
112
118
  };
113
119
  if (file || status !== "success") {
114
120
  opened();
@@ -285,20 +291,30 @@ const eventOf = (line) => {
285
291
  };
286
292
  /**
287
293
  * Removes every day older than `keepDays`, then the successful runs of every day older than `keepSuccessDays`, and
288
- * answers how many days went. Then, once a day, the folder is measured against `maxBytes`: successful runs go first,
289
- * oldest day first, then whole days, until it fits.
294
+ * answers how many days went. A success that wrote the store is kept for `keepStoreDays` instead when that is longer,
295
+ * and one kept only because it wrote the store goes after `keepStoreDays`. Then, once a day, the folder is measured
296
+ * against `maxBytes`: successful runs go first, oldest day first, then whole days, until it fits.
290
297
  *
291
298
  * A day at a time, by the directory name and the day's index, so no run has to be opened to decide — and a directory
292
299
  * that is not a date is left alone rather than guessed at.
293
300
  */
294
- export const pruneRuns = (runsDir, { keepDays, keepSuccessDays = keepDays, maxBytes, now, }) => {
301
+ export const pruneRuns = (runsDir, { keepDays, keepSuccessDays = keepDays, keepStoreDays = KEEP_STORE_RUNS_FOR_DAYS, maxBytes, now, }) => {
295
302
  const cutoff = day(new Date(now.getTime() - keepDays * DAY_MS));
296
- const successCutoff = day(new Date(now.getTime() - Math.min(keepSuccessDays, keepDays) * DAY_MS));
303
+ const before = (days) => day(new Date(now.getTime() - Math.min(days, keepDays) * DAY_MS));
304
+ const successCutoff = before(keepSuccessDays);
305
+ const storeCutoff = before(keepStoreDays);
306
+ const keptFor = (metadata) => metadata.keptBecauseStore
307
+ ? keepStoreDays
308
+ : metadata.operations?.includes(STORE_WRITE)
309
+ ? Math.max(keepSuccessDays, keepStoreDays)
310
+ : keepSuccessDays;
297
311
  let removed = 0;
298
312
  for (const date of days(runsDir)) {
299
313
  if (date >= cutoff) {
314
+ if (date < storeCutoff)
315
+ dropSuccesses(join(runsDir, date), STORE_RUNS_DROPPED, (metadata) => keptFor(metadata) <= keepStoreDays);
300
316
  if (date < successCutoff)
301
- dropSuccesses(join(runsDir, date));
317
+ dropSuccesses(join(runsDir, date), SUCCESSES_DROPPED, (metadata) => keptFor(metadata) <= keepSuccessDays);
302
318
  continue;
303
319
  }
304
320
  try {
@@ -314,20 +330,23 @@ export const pruneRuns = (runsDir, { keepDays, keepSuccessDays = keepDays, maxBy
314
330
  return removed;
315
331
  };
316
332
  const DAY_MS = 24 * 60 * 60 * 1000;
333
+ const STORE_WRITE = "store.write";
317
334
  const SUCCESSES_DROPPED = ".successes-dropped";
335
+ const STORE_RUNS_DROPPED = ".store-runs-dropped";
318
336
  const SIZE_CHECKED = ".size-checked";
319
- /** A day's successful runs, out of its index and off the disk; once per day, marked by a file beside them. */
320
- const dropSuccesses = (dayDir) => {
321
- const marker = join(dayDir, SUCCESSES_DROPPED);
337
+ /** A day's successful runs that `drops`, out of its index and off the disk; once per day and marker. */
338
+ const dropSuccesses = (dayDir, marker = SUCCESSES_DROPPED, drops = () => true) => {
339
+ const done = join(dayDir, marker);
322
340
  try {
323
- statSync(marker);
341
+ statSync(done);
324
342
  return;
325
343
  }
326
344
  catch { }
345
+ const dropped = (metadata) => metadata?.status === "success" && drops(metadata);
327
346
  try {
328
347
  const kept = [];
329
348
  for (const [id, metadata] of indexedRuns(dayDir)) {
330
- if (metadata.status === "success")
349
+ if (dropped(metadata))
331
350
  rmSync(join(dayDir, id), { recursive: true, force: true });
332
351
  else
333
352
  kept.push(JSON.stringify(runFileOf(metadata)));
@@ -335,11 +354,11 @@ const dropSuccesses = (dayDir) => {
335
354
  for (const entry of safeReaddir(dayDir)) {
336
355
  if (entry === INDEX || entry.startsWith("."))
337
356
  continue;
338
- if (readRun(join(dayDir, entry))?.status === "success")
357
+ if (dropped(readRun(join(dayDir, entry))))
339
358
  rmSync(join(dayDir, entry), { recursive: true, force: true });
340
359
  }
341
360
  writeSecurely(join(dayDir, INDEX), kept.map((line) => `${line}\n`).join(""), 0o600);
342
- writeFileSync(marker, "", { mode: 0o600 });
361
+ writeFileSync(done, "", { mode: 0o600 });
343
362
  }
344
363
  catch {
345
364
  // Tried again at the next run's start.
@@ -9,6 +9,7 @@ export declare const ACCOUNT_GROUPS_SETTING = "account_groups";
9
9
  export type AccountGroups = Record<string, string[]>;
10
10
  /** A bare `all` or `telegram` keeps meaning what it always did; a comma or a `:` makes it a list. */
11
11
  export declare const isAccountList: (value: string) => boolean;
12
+ export declare const isGroupName: (name: string) => boolean;
12
13
  export declare const groupName: (name: string) => string;
13
14
  /** What `config set account_groups.<name>` saves: the entries as written, so each app resolves its own profiles. */
14
15
  export declare const groupMembers: (value: string) => string[];
@@ -23,6 +24,8 @@ export interface ListContext {
23
24
  provider: Provider;
24
25
  command?: string;
25
26
  };
27
+ /** Under a group lock, the only accounts (by `keyOf`) a list may name; every other one resolves to nothing. */
28
+ only?: ReadonlySet<string>;
26
29
  }
27
30
  /**
28
31
  * An account as `--source` and a hit name it: a notes folder is `notes:<its id>`, never the store's ulid. The kind is
@@ -40,6 +43,9 @@ export interface ListedEntry {
40
43
  entry: string;
41
44
  accounts: ListedAccount[];
42
45
  }
46
+ export declare const keyOf: ({ provider, account }: AccountKey) => string;
47
+ export declare const sourceOf: ({ provider, account }: AccountKey) => string;
48
+ export declare const sameAs: (key: AccountKey) => (one: AccountKey) => boolean;
43
49
  /**
44
50
  * What `--source group:work,tg:tg3,max:Alice,email,notes:4` names, entry by entry, a group's members in its
45
51
  * place. An entry is a group, `provider:account` — the account's id, a profile of any app that recorded it, or
@@ -17,7 +17,8 @@ const itemsOf = (value) => {
17
17
  fail(`"${value}" has an empty entry — separate accounts with one comma`);
18
18
  return items;
19
19
  };
20
- export const groupName = (name) => GROUP_NAME.test(name) ? name : fail(`a group name is letters, digits, - and _ — not "${name}"`);
20
+ export const isGroupName = (name) => GROUP_NAME.test(name);
21
+ export const groupName = (name) => isGroupName(name) ? name : fail(`a group name is letters, digits, - and _ — not "${name}"`);
21
22
  /** What `config set account_groups.<name>` saves: the entries as written, so each app resolves its own profiles. */
22
23
  export const groupMembers = (value) => itemsOf(value).map((item) => item.toLowerCase().startsWith("group:")
23
24
  ? fail(`a group lists accounts, not other groups — "${item}"`)
@@ -145,7 +146,9 @@ const accountsOfWord = (word, held, context) => {
145
146
  return storedAs(held, { provider, account: "" });
146
147
  return held.filter((one) => one.provider === provider);
147
148
  };
148
- const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
149
+ export const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
150
+ export const sourceOf = ({ provider, account }) => `${provider}:${account}`;
151
+ export const sameAs = (key) => (one) => one.provider === key.provider && one.account === key.account;
149
152
  /**
150
153
  * What `--source group:work,tg:tg3,max:Alice,email,notes:4` names, entry by entry, a group's members in its
151
154
  * place. An entry is a group, `provider:account` — the account's id, a profile of any app that recorded it, or
@@ -188,9 +191,12 @@ export const entriesOfList = (value, context) => {
188
191
  };
189
192
  for (const item of itemsOf(value))
190
193
  entry(item);
194
+ const { only } = context;
191
195
  return entries.map(({ entry, accounts }) => ({
192
196
  entry,
193
- accounts: accounts.map(({ provider, account, kind, kinds }) => ({
197
+ accounts: accounts
198
+ .filter((one) => only === undefined || only.has(keyOf(one)))
199
+ .map(({ provider, account, kind, kinds }) => ({
194
200
  provider,
195
201
  account,
196
202
  kind,
@@ -0,0 +1,68 @@
1
+ import type { AccountKey } from "../store/store.js";
2
+ import { type AccountGroups, type ListContext } from "./account-list.js";
3
+ /** The default group: every account, never saved. Reading without a group reads it. */
4
+ export declare const ALL = "all";
5
+ /** memo's own notes: the owner's, so `search notes` reads them in every group, though no group lists them. */
6
+ export declare const OWNER_NOTES: AccountKey;
7
+ /** Words a source list already gives a meaning of its own, so no group may be saved under them. */
8
+ export declare const NOT_GROUP_NAMES: ReadonlySet<string>;
9
+ /** `setting`: a saved group lists it; `all`: the default group, which holds every account. */
10
+ export type GroupReason = "setting" | "all";
11
+ export interface GroupMember extends AccountKey {
12
+ /** Every saved entry that names it; its `provider:account` in `all`. */
13
+ entries: string[];
14
+ reason: GroupReason;
15
+ /** Every profile recorded for the account, as `<app> <profile>`. */
16
+ profiles: string[];
17
+ /** The other saved groups that hold it too: allowed, and shown so the owner sees it. */
18
+ also_in: string[];
19
+ }
20
+ /** A profile name another app's profile or a saved group shares, for an account not in that group: never applied. */
21
+ export interface GroupSuggestion {
22
+ group: string;
23
+ member: string;
24
+ because: string;
25
+ }
26
+ export interface GroupMembership {
27
+ /** The saved groups, then `all`. */
28
+ groups: Record<string, GroupMember[]>;
29
+ /** Each account in more than one saved group, with those groups. */
30
+ duplicates: {
31
+ member: string;
32
+ groups: string[];
33
+ }[];
34
+ suggested: GroupSuggestion[];
35
+ /** Saved entries that name no account. */
36
+ unresolved: string[];
37
+ }
38
+ /** A source-list context with who is in each group and why. */
39
+ export interface GroupContext extends ListContext {
40
+ membership: GroupMembership;
41
+ }
42
+ export declare const hasGroup: (groups: object, name: string) => boolean;
43
+ /**
44
+ * Who is in each group (WC-ACCT-13): a saved `account_groups.<name>` is its whole list, and `all`, never saved, is
45
+ * every account. One account may be in several groups. A profile's name never puts an account in a group; it is
46
+ * only `suggested`.
47
+ */
48
+ export declare const groupMembership: (context: ListContext) => GroupMembership;
49
+ /** Whether an account is in `group`; every account is in `all`. `context` is a `listContextOf`. */
50
+ export declare const inGroupOf: (context: GroupContext, group: string) => (key: AccountKey) => boolean;
51
+ /** The groups as a source list reads them: the saved entries as written, and `group:all` as every account. */
52
+ export declare const groupEntries: (saved: AccountGroups) => AccountGroups;
53
+ /** The group a run is scoped to, where it was named, and whether a lock pins it. */
54
+ export interface RunGroup {
55
+ name: string;
56
+ from: string;
57
+ locked: boolean;
58
+ }
59
+ export interface GroupRequest {
60
+ source?: string;
61
+ account?: string;
62
+ }
63
+ /**
64
+ * A run in a group reads only the group: no `--source` becomes `group:<name>`, a bare provider or kind keeps the
65
+ * group's accounts of it, and an account outside the group is refused, as is a write's `--account`. `context` is a
66
+ * `listContextOf`. Without a lock this is a convenience, not a boundary.
67
+ */
68
+ export declare const scopeToGroup: (run: RunGroup, request: GroupRequest, context: GroupContext) => GroupRequest;
@@ -0,0 +1,172 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { INTERNAL_NOTES } from "../domain/providers.js";
3
+ import { accountsOfList, isGroupName, keyOf, sameAs, sourceOf, } from "./account-list.js";
4
+ /** The default group: every account, never saved. Reading without a group reads it. */
5
+ export const ALL = "all";
6
+ /** memo's own notes: the owner's, so `search notes` reads them in every group, though no group lists them. */
7
+ export const OWNER_NOTES = { provider: "notes", account: INTERNAL_NOTES };
8
+ /** Words a source list already gives a meaning of its own, so no group may be saved under them. */
9
+ export const NOT_GROUP_NAMES = new Set([ALL, "bots"]);
10
+ export const hasGroup = (groups, name) => Object.hasOwn(groups, name);
11
+ const membersOf = (entries, context, unresolved) => {
12
+ const members = new Map();
13
+ for (const entry of entries)
14
+ try {
15
+ for (const { provider, account } of accountsOfList(entry, context)) {
16
+ const known = members.get(keyOf({ provider, account }));
17
+ if (known)
18
+ known.entries.push(entry);
19
+ else
20
+ members.set(keyOf({ provider, account }), {
21
+ provider,
22
+ account,
23
+ entries: [entry],
24
+ reason: "setting",
25
+ profiles: [],
26
+ also_in: [],
27
+ });
28
+ }
29
+ }
30
+ catch (error) {
31
+ // One stale entry must not break every read of every group; the group's own read still names it.
32
+ if (!(error instanceof CliError))
33
+ throw error;
34
+ unresolved.push(entry);
35
+ }
36
+ return [...members.values()];
37
+ };
38
+ /**
39
+ * Who is in each group (WC-ACCT-13): a saved `account_groups.<name>` is its whole list, and `all`, never saved, is
40
+ * every account. One account may be in several groups. A profile's name never puts an account in a group; it is
41
+ * only `suggested`.
42
+ */
43
+ export const groupMembership = (context) => {
44
+ const plain = { ...context, groups: {} };
45
+ const unresolved = [];
46
+ const groups = {};
47
+ for (const [name, entries] of Object.entries(context.groups))
48
+ if (name !== ALL)
49
+ groups[name] = membersOf(entries, plain, unresolved);
50
+ // Not accounts of anyone's: memo's own notes, and the row a fresh store lacks for the account running (id 0).
51
+ const system = [OWNER_NOTES, ...context.held.filter(({ id }) => id === 0)].map(keyOf);
52
+ const every = accountsOfList(ALL, plain)
53
+ .filter((one) => !system.includes(keyOf(one)))
54
+ .map(({ provider, account }) => ({
55
+ provider,
56
+ account,
57
+ entries: [sourceOf({ provider, account })],
58
+ reason: "all",
59
+ profiles: [],
60
+ also_in: [],
61
+ }));
62
+ const recorded = Object.entries(context.profiles).flatMap(([app, named]) => Object.entries(named).map(([profile, key]) => ({ app, profile, key })));
63
+ const holding = new Map();
64
+ for (const [name, members] of Object.entries(groups))
65
+ for (const one of members)
66
+ holding.set(keyOf(one), [...(holding.get(keyOf(one)) ?? []), name]);
67
+ for (const [name, members] of [...Object.entries(groups), [ALL, every]])
68
+ for (const one of members) {
69
+ one.profiles = recorded.filter(({ key }) => sameAs(key)(one)).map(({ app, profile }) => `${app} ${profile}`);
70
+ one.also_in = (holding.get(keyOf(one)) ?? []).filter((other) => other !== name);
71
+ }
72
+ const duplicates = [...holding.entries()]
73
+ .filter(([, names]) => names.length > 1)
74
+ .map(([key, names]) => ({ member: key.replace("\u0000", ":"), groups: names }));
75
+ // A name only one app uses, such as `default`, says nothing about which accounts belong together.
76
+ const shared = (app, profile) => hasGroup(context.groups, profile) || recorded.some((other) => other.app !== app && other.profile === profile);
77
+ const suggested = recorded
78
+ .filter(({ app, profile, key }) => isGroupName(profile) &&
79
+ !NOT_GROUP_NAMES.has(profile.toLowerCase()) &&
80
+ shared(app, profile) &&
81
+ !holding.get(keyOf(key))?.includes(profile))
82
+ .map(({ app, profile, key }) => ({
83
+ group: profile,
84
+ member: sourceOf(key),
85
+ because: `profile named ${profile} (${app} ${profile})`,
86
+ }));
87
+ return { groups: { ...groups, [ALL]: every }, duplicates, suggested, unresolved };
88
+ };
89
+ /** Whether an account is in `group`; every account is in `all`. `context` is a `listContextOf`. */
90
+ export const inGroupOf = (context, group) => (key) => group === ALL ||
91
+ (hasGroup(context.membership.groups, group) ? (context.membership.groups[group] ?? []) : []).some(sameAs(key));
92
+ /** The groups as a source list reads them: the saved entries as written, and `group:all` as every account. */
93
+ export const groupEntries = (saved) => ({
94
+ ...Object.fromEntries(Object.entries(saved).filter(([name]) => name !== ALL)),
95
+ [ALL]: [ALL],
96
+ });
97
+ const fail = (code, message, details) => {
98
+ throw new CliError(code, message, details);
99
+ };
100
+ const unknownGroup = (run, context) => {
101
+ const names = Object.keys(context.groups);
102
+ const unknown = run.from === "first word"
103
+ ? `"${run.name}" is neither a command nor a group`
104
+ : `no group "${run.name}" (${run.from})`;
105
+ const suggested = context.membership.suggested.filter(({ group }) => group === run.name);
106
+ const offer = suggested.length
107
+ ? `; profiles named ${run.name} suggest ${suggested.map(({ member }) => member).join(", ")}`
108
+ : "";
109
+ return fail("validation_error", `${unknown} — groups here: ${names.join(", ")}${offer}`, {
110
+ groups: names,
111
+ ...(suggested.length ? { suggested } : {}),
112
+ });
113
+ };
114
+ /**
115
+ * A run in a group reads only the group: no `--source` becomes `group:<name>`, a bare provider or kind keeps the
116
+ * group's accounts of it, and an account outside the group is refused, as is a write's `--account`. `context` is a
117
+ * `listContextOf`. Without a lock this is a convenience, not a boundary.
118
+ */
119
+ export const scopeToGroup = (run, request, context) => {
120
+ if (!hasGroup(context.groups, run.name))
121
+ unknownGroup(run, context);
122
+ const code = run.locked ? "permission_error" : "validation_error";
123
+ const why = run.locked
124
+ ? `this process is locked to group ${run.name} (${run.from})`
125
+ : `this run is in group ${run.name}`;
126
+ if (!context.membership.groups[run.name]?.length)
127
+ fail("validation_error", `group ${run.name} is empty`);
128
+ const inGroup = new Set(accountsOfList(`group:${run.name}`, context).map(keyOf));
129
+ const outside = (accounts) => accounts.filter((one) => !inGroup.has(keyOf(one)));
130
+ // Under a lock the context holds only the group, so a name outside it fails to resolve: that is the refusal.
131
+ const namedBy = (item) => {
132
+ try {
133
+ return accountsOfList(item, context);
134
+ }
135
+ catch (error) {
136
+ if (run.locked && error instanceof CliError)
137
+ return [];
138
+ throw error;
139
+ }
140
+ };
141
+ const scoped = {};
142
+ if (request.source === undefined)
143
+ scoped.source = `group:${run.name}`;
144
+ else {
145
+ const items = request.source.split(",").map((item) => item.trim());
146
+ if (items.some((item) => item.toLowerCase() === "all"))
147
+ fail(code, `${why} — --source all reads outside it`);
148
+ const kept = [];
149
+ let narrowed = false;
150
+ for (const item of items) {
151
+ const accounts = namedBy(item);
152
+ const away = outside(accounts);
153
+ if (item.includes(":") && (away.length || accounts.length === 0))
154
+ fail(code, `${why} — ${item} is outside it${away.length ? ` (${away.map(sourceOf).join(", ")})` : ""}`);
155
+ if (away.length)
156
+ narrowed = true;
157
+ for (const one of accounts)
158
+ if (inGroup.has(keyOf(one)))
159
+ kept.push(sourceOf(one));
160
+ }
161
+ if (kept.length === 0)
162
+ fail("validation_error", `${why} — --source ${request.source} names none of its accounts`);
163
+ scoped.source = narrowed ? [...new Set(kept)].join(",") : request.source;
164
+ }
165
+ if (request.account !== undefined) {
166
+ const accounts = namedBy(request.account);
167
+ if (accounts.length === 0 || outside(accounts).length)
168
+ fail(code, `${why} — --account ${request.account} is outside it`);
169
+ scoped.account = request.account;
170
+ }
171
+ return scoped;
172
+ };