@wirecat/cli-core 0.605.0 → 0.607.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 (260) hide show
  1. package/CHANGELOG.md +284 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +4 -1
  12. package/dist/cli/index.js +4 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/cli/store-settings.js +38 -4
  17. package/dist/crm/cli/csv.d.ts +23 -0
  18. package/dist/crm/cli/csv.js +135 -0
  19. package/dist/crm/cli/index.d.ts +1 -1
  20. package/dist/crm/cli/index.js +36 -22
  21. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  22. package/dist/crm/cli/pipeline-view.js +36 -0
  23. package/dist/crm/index.d.ts +2 -2
  24. package/dist/crm/index.js +1 -1
  25. package/dist/crm/source.d.ts +35 -5
  26. package/dist/crm/sync.d.ts +15 -7
  27. package/dist/crm/sync.js +169 -11
  28. package/dist/crm/writes.d.ts +6 -4
  29. package/dist/crm/writes.js +17 -13
  30. package/dist/documents.d.ts +2 -0
  31. package/dist/documents.js +2 -0
  32. package/dist/domain/business.d.ts +79 -0
  33. package/dist/domain/business.js +42 -0
  34. package/dist/domain/crm.d.ts +41 -2
  35. package/dist/domain/deals.d.ts +5 -2
  36. package/dist/domain/deals.js +5 -2
  37. package/dist/domain/finance.d.ts +2 -0
  38. package/dist/domain/finance.js +2 -2
  39. package/dist/domain/google-documents.d.ts +2 -0
  40. package/dist/domain/google-documents.js +3 -1
  41. package/dist/domain/money.d.ts +2 -0
  42. package/dist/domain/money.js +11 -3
  43. package/dist/domain/providers.d.ts +36 -1
  44. package/dist/domain/providers.js +69 -7
  45. package/dist/domain/record-fields.d.ts +42 -0
  46. package/dist/domain/record-fields.js +122 -0
  47. package/dist/domain/record-types.d.ts +489 -16
  48. package/dist/domain/record-types.js +374 -7
  49. package/dist/domain/records.d.ts +96 -5
  50. package/dist/domain/records.js +178 -32
  51. package/dist/domain/ref-summaries.js +5 -0
  52. package/dist/domain/references.d.ts +1 -1
  53. package/dist/domain/references.js +5 -0
  54. package/dist/domain/relations.d.ts +125 -0
  55. package/dist/domain/relations.js +107 -0
  56. package/dist/domain/vcard.d.ts +25 -0
  57. package/dist/domain/vcard.js +267 -0
  58. package/dist/entities/deal.d.ts +16 -2
  59. package/dist/entities/deal.js +5 -1
  60. package/dist/entities/index.d.ts +29 -13
  61. package/dist/entities/relationship.d.ts +8 -2
  62. package/dist/entities/relationship.js +8 -2
  63. package/dist/entities/task-results.d.ts +10 -10
  64. package/dist/errors/reasons.js +73 -2
  65. package/dist/fetch/addresses.d.ts +5 -0
  66. package/dist/fetch/addresses.js +76 -0
  67. package/dist/fetch/page.d.ts +64 -0
  68. package/dist/fetch/page.js +256 -0
  69. package/dist/index.d.ts +7 -4
  70. package/dist/index.js +6 -3
  71. package/dist/mail/cli/review.js +20 -6
  72. package/dist/mail/index.d.ts +1 -1
  73. package/dist/mail/marks.d.ts +10 -5
  74. package/dist/mail/marks.js +16 -8
  75. package/dist/mail/review.d.ts +5 -0
  76. package/dist/meetings/calendar-text.d.ts +1 -1
  77. package/dist/meetings/calendar-text.js +4 -0
  78. package/dist/meetings/event-store.d.ts +2 -2
  79. package/dist/search/account-list.d.ts +4 -0
  80. package/dist/search/account-list.js +19 -8
  81. package/dist/search/query.js +2 -2
  82. package/dist/services/events-search.js +2 -2
  83. package/dist/services/index.d.ts +1 -1
  84. package/dist/services/index.js +1 -1
  85. package/dist/services/ingest.d.ts +56 -8
  86. package/dist/services/ingest.js +95 -61
  87. package/dist/services/link-scorers/scan.js +2 -1
  88. package/dist/services/link-scorers/shared.js +2 -1
  89. package/dist/services/messages-search.js +3 -2
  90. package/dist/services/metadata.d.ts +1 -1
  91. package/dist/services/notes-search.js +1 -0
  92. package/dist/services/project-status/index.js +2 -1
  93. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  94. package/dist/services/proposals/kinds/contracts.js +9 -0
  95. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  96. package/dist/services/proposals/kinds/finance.js +14 -35
  97. package/dist/services/proposals/kinds/orders.js +7 -30
  98. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  99. package/dist/services/proposals/kinds/shared.js +34 -0
  100. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  101. package/dist/services/proposals/kinds/source-review.js +45 -0
  102. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  103. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  104. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  105. package/dist/services/proposals/kinds/transactions.js +10 -0
  106. package/dist/services/proposals/registry.js +9 -0
  107. package/dist/services/search-all-meetings.js +2 -2
  108. package/dist/services/search-all.js +4 -3
  109. package/dist/services/search-kind.js +3 -3
  110. package/dist/services/stored-project-gathering.js +4 -3
  111. package/dist/store/decisions.js +5 -1
  112. package/dist/store/exports.d.ts +1 -0
  113. package/dist/store/exports.js +1 -0
  114. package/dist/store/index.d.ts +20 -4
  115. package/dist/store/index.js +4 -0
  116. package/dist/store/people.js +1 -1
  117. package/dist/store/project-transfer/request.d.ts +4 -1
  118. package/dist/store/project-transfer/schema.d.ts +9 -2
  119. package/dist/store/project-transfer/schema.js +4 -0
  120. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  121. package/dist/store/source-review.d.ts +64 -0
  122. package/dist/store/source-review.js +7 -0
  123. package/dist/store/sqlite/accounts.d.ts +1 -1
  124. package/dist/store/sqlite/accounts.js +24 -1
  125. package/dist/store/sqlite/added-sources.d.ts +82 -0
  126. package/dist/store/sqlite/added-sources.js +237 -0
  127. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  128. package/dist/store/sqlite/business-contracts.js +182 -0
  129. package/dist/store/sqlite/calendar-events.js +7 -3
  130. package/dist/store/sqlite/calendar-forget.js +3 -0
  131. package/dist/store/sqlite/calendar.d.ts +21 -1
  132. package/dist/store/sqlite/calendar.js +27 -7
  133. package/dist/store/sqlite/chat-rekey.js +7 -0
  134. package/dist/store/sqlite/chats.d.ts +3 -1
  135. package/dist/store/sqlite/chats.js +15 -1
  136. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  137. package/dist/store/sqlite/crm-rows.js +195 -0
  138. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  139. package/dist/store/sqlite/crm-settings.js +80 -0
  140. package/dist/store/sqlite/crm.d.ts +42 -11
  141. package/dist/store/sqlite/crm.js +402 -196
  142. package/dist/store/sqlite/deals.d.ts +4 -8
  143. package/dist/store/sqlite/deals.js +8 -5
  144. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  145. package/dist/store/sqlite/emails.js +2 -0
  146. package/dist/store/sqlite/entity-types.d.ts +14 -9
  147. package/dist/store/sqlite/entity-types.js +4 -10
  148. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  149. package/dist/store/sqlite/evidence-signature.js +349 -0
  150. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  151. package/dist/store/sqlite/evidence-sources.js +7 -3
  152. package/dist/store/sqlite/facts.d.ts +7 -2
  153. package/dist/store/sqlite/facts.js +21 -5
  154. package/dist/store/sqlite/finance.d.ts +18 -105
  155. package/dist/store/sqlite/finance.js +100 -219
  156. package/dist/store/sqlite/involvement-queue.js +4 -3
  157. package/dist/store/sqlite/knowledge.d.ts +14 -4
  158. package/dist/store/sqlite/knowledge.js +108 -102
  159. package/dist/store/sqlite/labelled.d.ts +3 -0
  160. package/dist/store/sqlite/labelled.js +11 -0
  161. package/dist/store/sqlite/link-kinds.d.ts +4 -3
  162. package/dist/store/sqlite/link-kinds.js +6 -2
  163. package/dist/store/sqlite/manifest.js +7 -0
  164. package/dist/store/sqlite/memories.d.ts +24 -10
  165. package/dist/store/sqlite/memories.js +73 -19
  166. package/dist/store/sqlite/messages.js +2 -0
  167. package/dist/store/sqlite/migrations.generated.js +134 -0
  168. package/dist/store/sqlite/money-lines.d.ts +48 -0
  169. package/dist/store/sqlite/money-lines.js +76 -0
  170. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  171. package/dist/store/sqlite/money-transactions.js +295 -0
  172. package/dist/store/sqlite/notes.d.ts +14 -4
  173. package/dist/store/sqlite/notes.js +43 -31
  174. package/dist/store/sqlite/orders.d.ts +36 -6
  175. package/dist/store/sqlite/orders.js +126 -46
  176. package/dist/store/sqlite/organizations.d.ts +8 -0
  177. package/dist/store/sqlite/organizations.js +14 -0
  178. package/dist/store/sqlite/payment-facts.js +1 -1
  179. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  180. package/dist/store/sqlite/person-preparation.js +3 -2
  181. package/dist/store/sqlite/private-people.js +2 -0
  182. package/dist/store/sqlite/products.d.ts +78 -0
  183. package/dist/store/sqlite/products.js +131 -0
  184. package/dist/store/sqlite/project-transfer/records.js +39 -3
  185. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  186. package/dist/store/sqlite/project-transfer/snapshot.js +11 -3
  187. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  188. package/dist/store/sqlite/proposed-actions.js +24 -7
  189. package/dist/store/sqlite/providers.d.ts +0 -4
  190. package/dist/store/sqlite/providers.js +20 -2
  191. package/dist/store/sqlite/record-matching.d.ts +80 -0
  192. package/dist/store/sqlite/record-matching.js +264 -0
  193. package/dist/store/sqlite/record-projection.d.ts +89 -0
  194. package/dist/store/sqlite/record-projection.js +50 -0
  195. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  196. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  197. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  198. package/dist/store/sqlite/record-projectors-money.js +214 -0
  199. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  200. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  201. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  202. package/dist/store/sqlite/record-projectors.js +7 -67
  203. package/dist/store/sqlite/record-relations.d.ts +24 -0
  204. package/dist/store/sqlite/record-relations.js +92 -0
  205. package/dist/store/sqlite/record-remap.d.ts +12 -0
  206. package/dist/store/sqlite/record-remap.js +92 -0
  207. package/dist/store/sqlite/record-run.d.ts +71 -0
  208. package/dist/store/sqlite/record-run.js +179 -0
  209. package/dist/store/sqlite/record-settling.d.ts +9 -0
  210. package/dist/store/sqlite/record-settling.js +74 -0
  211. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  212. package/dist/store/sqlite/record-stamps.js +30 -0
  213. package/dist/store/sqlite/record-writes.d.ts +43 -0
  214. package/dist/store/sqlite/record-writes.js +307 -0
  215. package/dist/store/sqlite/records.d.ts +52 -42
  216. package/dist/store/sqlite/records.js +123 -353
  217. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  218. package/dist/store/sqlite/ref-summaries.js +60 -8
  219. package/dist/store/sqlite/refunds.d.ts +31 -0
  220. package/dist/store/sqlite/refunds.js +112 -0
  221. package/dist/store/sqlite/relation-list.d.ts +43 -0
  222. package/dist/store/sqlite/relation-list.js +133 -0
  223. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  224. package/dist/store/sqlite/relation-proposals.js +134 -10
  225. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  226. package/dist/store/sqlite/relation-reads.js +7 -0
  227. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  228. package/dist/store/sqlite/relation-roles.js +91 -0
  229. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  230. package/dist/store/sqlite/reported-relations.js +132 -0
  231. package/dist/store/sqlite/reviewed.d.ts +109 -0
  232. package/dist/store/sqlite/reviewed.js +173 -0
  233. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  234. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  235. package/dist/store/sqlite/schema/links.d.ts +360 -0
  236. package/dist/store/sqlite/schema/links.js +32 -0
  237. package/dist/store/sqlite/schema.d.ts +2769 -306
  238. package/dist/store/sqlite/schema.js +258 -25
  239. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  240. package/dist/store/sqlite/source-review-marks.js +143 -0
  241. package/dist/store/sqlite/source-review.d.ts +54 -0
  242. package/dist/store/sqlite/source-review.js +221 -0
  243. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  244. package/dist/store/sqlite/stage-amounts.js +23 -0
  245. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  246. package/dist/store/sqlite/subscriptions.js +294 -0
  247. package/dist/store/sqlite/text-input.d.ts +3 -0
  248. package/dist/store/sqlite/text-input.js +13 -0
  249. package/dist/store/sqlite/things.js +2 -9
  250. package/dist/store/sqlite/transaction.d.ts +15 -0
  251. package/dist/store/sqlite/transaction.js +57 -0
  252. package/dist/store/sqlite/wallets.d.ts +88 -0
  253. package/dist/store/sqlite/wallets.js +143 -0
  254. package/dist/store/store-errors.d.ts +1 -0
  255. package/dist/store/store-errors.js +45 -0
  256. package/dist/store/store.d.ts +19 -1
  257. package/dist/store/store.js +35 -6
  258. package/package.json +6 -3
  259. package/schemas/examples/records-business.jsonl +11 -0
  260. package/schemas/records-envelope.v1.schema.json +1160 -5
package/CHANGELOG.md CHANGED
@@ -5,7 +5,290 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
- ## Unreleased
8
+ ## 0.607.0 — 08.11.2026
9
+
10
+ ### Added
11
+
12
+ - **Phone data in the records envelope.** A `message` of kind `sms` becomes a chat and message, and an `event` of kind
13
+ `call` an event of the `calls` calendar (`event_type: call`, never busy), both in the one account the import names,
14
+ so `search all`, `events list event_type:call`, an account group and a person's context read them. The other side is
15
+ the `counterpart` person record, matched by phone or made; `events list person:` finds a call through it.
16
+ `envelopeOfVcard(text, { provider, account, batchId, region })` and `isVcard` turn a `.vcf` (2.1, 3.0, 4.0) into
17
+ persons and their organizations, and `ingestVcard` (`./services`) imports it. A number without a country code is
18
+ read only with `region`.
19
+ - **A provider may hold several kinds.** A provider entry takes `kinds` beside `kind` (its first), and search lanes
20
+ pick the accounts whose provider holds their kind (`holdsKind`, `kindsIn`). The seeded `phone` holds `messages` and
21
+ `events`. An entry with `kind` alone means what it meant; an older build reads the first kind only.
22
+ Entries of one name join their kinds, so registering an older shape never drops another build's. `imported`
23
+ marks a provider no sync writes; SMS and calls are taken only there (`record.provider-not-imported`), never into a
24
+ chat whose membership is not `imported` (`record.chat`), and an SMS moved to another thread is refused
25
+ (`record.moved`). A deleted SMS or call record tombstones its message or event, and
26
+ sending it again brings them back.
27
+ - **`deals list --format csv` and `leads list --format csv`: a page of deals or leads as a table for a spreadsheet.**
28
+ stdout carries the CSV (RFC 4180, CRLF) and nothing else; the way to the next page goes to stderr. The columns are
29
+ the built-in fields, `amount` and `currency` apart, then every CRM field by its label as `fields list` shows it — a
30
+ money field as `<label> amount` and `<label> currency`, a label two fields share told apart by its code.
31
+ `--json=a,b` beside it picks the columns, a CRM field as `provider_metadata.<code>`. A cell that would start a
32
+ formula (`=`, `+`, `-`, `@`, tab, CR) gets a leading `'`, a plain number excepted. `--jsonl`, a bare `--json`,
33
+ `--compact` and an agent's run are refused with `output.conflict`. `csvCell`, `csvRecords` and `writeCsv` are
34
+ exported from `@wirecat/cli-core/cli` for a CLI's own lists.
35
+
36
+ - **`pipelines show` in a CRM CLI is the pipeline's board.** Each stage now gives `items`, the deals or leads standing
37
+ in it, and `amounts`, their sum per currency with how many carry it. Nothing is converted, and an item with no amount
38
+ is counted but adds no sum. At a terminal it prints a table of the stages, then the open stages' sum and the won,
39
+ lost and win rate. The pipeline may be left out when the CRM account has only one; with several, the command lists
40
+ them as `name (pipeline:<id>)` and in `allowed` (`crm.pipeline-required`). `store.deals.pipeline` gives the same two
41
+ fields, counted from the rows its `since` keeps.
42
+
43
+ - **`appMcpCommand`'s `signedIn` hook gets the run's keyring** as a third argument, so `mcp check` reads a test's
44
+ `memoryKeyring()` and the CLI no longer captures it in a `preAction` hook of its own. A hook that throws, such as
45
+ on a locked keyring, counts as not signed in. A two-argument hook still works.
46
+ - **`ProfileTokenStore` in `@wirecat/cli-core/cli`: one API token per profile for a CLI that is not a messenger**,
47
+ so b24, beeline and cli-template drop their copies of `src/token.ts`. `<PREFIX>_TOKEN`, then the keyring entry
48
+ `token:<profile>` under the app's service, then a 0600 file; a moved run writes only a temporary
49
+ `<app>:<config folder>` entry. `write(profile, token, "file")` also forgets the keyring copy. `need(profile)`
50
+ throws the new reason `session.missing` (`authentication_error`, naming `session start`), the one "not signed in"
51
+ every token CLI gives; `signedIn(profile)` is `appMcpCommand`'s hook.
52
+ - **Evidence can carry the quote a memory or fact rests on, and every evidence link records what its source looked
53
+ like.** `store.memories.add` and `store.facts.add` take each piece of evidence as a reference, as before, or as
54
+ `{ ref, quote }` with up to 500 characters (`evidence.quote-length` otherwise); a quote the source's text does not
55
+ hold is refused (`evidence.quote-not-found`). The link's `metadata` keeps `{ v: 1, sig, rev, cited_rev, quote?,
56
+ checked_at }`, read from the source's columns and never its text, deletion included, so a later check can tell that
57
+ a cited source changed or went. Reads still return evidence as references. A project snapshot leaves the signature
58
+ behind and the restore signs each evidence link against the target store; a quote does not travel.
59
+ - **Memories and facts follow their sources.** `store.knowledge.checkSources({ limit })` walks the evidence links of
60
+ memories and facts, 500 a run by default, going on from where the last run stopped, and opens one
61
+ `memory_source_review` proposal per memory or fact whose source changed (`changed`), was deleted (`deleted`), or
62
+ cites a fact or memory that no longer holds (`outdated`, naming its replacement). A changed source that still says
63
+ the quoted words raises nothing. A source deleted for good, or a message tombstoned, opens a `deleted` review at once.
64
+ `store.knowledge.challenge(ref, { evidence, reason, by, suggestion? })` raises one as `contradicted`. The check
65
+ answers `{ checked, baselined, raised, refreshed, closed }` and never changes a status. Memory and fact reads carry
66
+ `sourceReview: { id, cause } | null`. The review is the owner's alone: `knowledge.decideSourceReview` or the
67
+ registry confirms it (still true; a memory is verified now) or rejects it (dismissed), and both sign its sources
68
+ again. Superseding, invalidating, reversing or rejecting the memory or fact closes its review as executed; removing
69
+ it erases its reviews. When a cited source is erased, every review naming it loses that reference and the words of
70
+ each challenge and suggestion that cited it.
71
+ - **`fetchPage(url)` in `@wirecat/cli-core/documents` reads one web page** for a link the owner adds by hand: `http`
72
+ or `https` only, 50 MiB, 30 s, at most 5 redirects followed by hand, no cookies or credentials. Every hop's name must
73
+ resolve to public addresses only, and the connection goes to the address that was checked, so a link cannot reach
74
+ this computer, the local network or a cloud metadata address, even by DNS rebinding or an IPv4-mapped form. The
75
+ reader is chosen by content type. Refusals carry `source.url-refused`, `source.url-status`, `source.url-timeout`,
76
+ `source.url-redirects`, `source.url-unreachable`, `source.too-large`, `source.unsupported`, `source.no-text`,
77
+ `source.unreadable` and `source.engine-missing`; a private Google document is `source.needs-sign-in`.
78
+ `isPublicAddress` is exported too. A redirect from `https` to `http` is refused, the reader is stopped at the same
79
+ 30 s, and the answer gives `requestedUrl` (the address to keep) beside `finalUrl` (never to be stored).
80
+ - **`store.notes.saveAddedSource` keeps a source the owner adds by hand**: pasted text, a file, or a page read from a
81
+ link, in the new `added` account. It is a document like a folder's, found by notes search, by `search all` and by
82
+ meaning. A repeat of the same file or text is the same document (`created: false`); a live folder or Drive document
83
+ with the same content is answered as `duplicateOf`, and only the new subjects are linked to it. `by` names who
84
+ adds it: an agent's subjects are linked unconfirmed. Only the text is kept unless the caller passes `keepCopy` with
85
+ the path of its copy (`kept: "text" | "copy"`). The account is no folder, so `saveFileNote` and `deleteFileNotes`
86
+ refuse it, and a folder file of the same content never joins an added source. `store.notes.addedAccount()` names
87
+ the account; `ADDED_PROVIDER` and `ADDED_ACCOUNT` are exported.
88
+ - **`store.notes.findAddedSource` and `addedSourceKeyOf` say what saving would find, writing nothing**, so a caller
89
+ that keeps a copy of a file writes it only when the source is new. **`store.notes.removeAddedSource(ref, "owner")`**
90
+ removes an added source the way a folder file's removal does and answers the path of its copy, if any.
91
+ - **Store version 57: business tables.** `store.products` (`product:<id>`, written directly, a line copies its
92
+ price), `store.contracts` (`contract:<id>`: an agent's or an import's is proposed only when it carries a value, and
93
+ only the owner changes the value of a confirmed one; the notice deadline is computed), `store.subscriptions`
94
+ (`subscription:<id>`, every price a row and a proposal of its own, `subscription_price:<id>`, never overwritten;
95
+ `currentPrice` is the confirmed one in force today), `store.wallets` (`wallet:<id>`, one currency each, the balance
96
+ computed from confirmed, booked transactions after the opening day, pending ones beside it; only the owner sets the
97
+ opening balance) and `store.transactions` (`transaction:<id>`, splits by category within the amount, a payment linked
98
+ only of the same currency, direction and amount, once). `minCompatible` stays 56, as version 56 set it.
99
+ - **Orders take lines, a direction, a contract and a deal.** With lines an order totals their sum (`order.total`);
100
+ `orders.addLine` and `orders.removeLine` change them, the owner on any order, an agent only on its own proposed one.
101
+ A `sale` makes the owner its supplier. `orders.add` and `orders.get` answer `OrderDetail` with `lines`.
102
+ - **Refunds.** `finance.addPayment({ refundOf })` writes a payment the other way that takes money back
103
+ (`finance.refund`, `finance.over-refund`, `finance.refunded`): it is confirmed only after its payment, goes back only
104
+ to an invoice its payment paid, never more than that payment gave it, and a refunded payment is not rejected.
105
+ Invoices and payments take a `contract` and a `subscription`; an invoice line may name a `product`.
106
+ - **Review kinds `contract`, `subscription`, `subscription_price` and `transaction`**, decided by the owner only, as
107
+ invoices are. Confirming a subscription confirms the prices proposed with it; a later price is its own proposal
108
+ (`subscription_price:<id>`). A bot changes only its own still-proposed rows; a confirmed one is the owner's.
109
+ - **`InvoiceLine.product`** names the product a line was priced from, and `OrderInput.supplierName` may be left out
110
+ of a sale. `signedMinorUnits` and a `formatDecimal` that prints negative amounts are exported.
111
+ - **New reasons:** `finance.refund`, `finance.over-refund`, `finance.refunded`; `order.total`, `order.line` (an order
112
+ keeps its last line), `order.no-line`, `order.lines`, `order.line-amount`, `order.currency`, `order.owner-only`;
113
+ `product.field`, `product.duplicate`, `product.ref`; `contract.field`, `contract.ref`; `subscription.field`,
114
+ `subscription.interval`, `subscription.price`, `subscription.no-price`, `subscription.ref`; `wallet.field`,
115
+ `wallet.number`, `wallet.ref`; `transaction.field`, `transaction.payment`, `transaction.ref`, `transaction.split`,
116
+ `transaction.no-split`.
117
+ - **The records envelope takes every business type.** Beside v1's five, `deal`, `lead`, `pipeline`, `order` (with
118
+ `lines`), `contract`, `subscription` (with `prices`), `product`, `wallet` and `transaction` (with `splits`), each with
119
+ typed `fields` and roles in `RECORD_TYPES`; `pnpm schema:envelope` writes the shipped JSON Schema from it. A relation
120
+ names a store entity by `ref` (`organization:12`), a relationship role carries `as` (`decision-maker`), `payment`
121
+ takes `refund_of`, a line names its `product` or `product_ref`, and `options.lines: "products"` reads an invoice
122
+ line's product. Money types are proposals of the bot `import`; deals and leads land on the row CRM sync writes for
123
+ the same account. A changed record re-proposes the import's own proposal while nobody else touched it, and is
124
+ flagged once the owner edited or decided it. See
125
+ [`docs/storage/records-envelope.md`](docs/storage/records-envelope.md).
126
+ - **Streaming JSONL.** `ingestLines(store, jsonlLines(stream), { account, dryRun, chunk, onIssue })` (`./services`)
127
+ writes per chunk as lines arrive; the receipt's lists keep 1000 entries and set `truncated`, the counts stay exact,
128
+ and `onIssue` (also on `ingest`) gets every refusal. A dry run is one transaction rolled back at the end: it holds
129
+ the write lock, and any other statement on the store handle meanwhile is refused (`store.dry-run`). A leading
130
+ byte-order mark is skipped; `envelopeOfText(text)` reads a file's text as JSON or JSONL.
131
+ - **Receipt `unmatched[{key, pointer, reason, candidates}]`** and a flagged entry's `reason` and `candidates`,
132
+ `store.records.match({ provider, account })`, `store.records.list({ unmatched })`, `SourceRecord.createdEntity` and
133
+ a relation's `ref` and `as`. The owner's `store.records.map` moves a record whose entity the import made, with the
134
+ account's records linked to it, and answers the old one as `unused`, beside the records it completed.
135
+ - **`options.phone_region`**: a person's phone without `+` is an identifier only when the envelope names this country
136
+ and the number is valid there; the `phone_countries` setting never decides it. Without it the number stays data and
137
+ the receipt lists it under `ignored` (`record.phone-region`).
138
+ - **An envelope deal's and lead's people stay as record relations** (with `as`) until imports report relationships to
139
+ the store; they no longer write the deal's person links.
140
+ - **`orders.revise(order, input)`** replaces an order's columns and lines: the owner on any order, a bot on its own
141
+ proposed one. New reasons `record.identifier`, `record.ambiguous`, `record.separated`, `record.phone-region` and
142
+ `store.dry-run`.
143
+ - **An example import, one synthetic customer end to end**, ships as
144
+ `@wirecat/cli-core/schemas/examples/records-business.jsonl`.
145
+
146
+ ### Changed — may break callers
147
+
148
+ - **`EntryEventType` has `call`**, and `events list event_type:` takes it. A switch over the kinds needs a branch.
149
+ - **`kindIn` and `ListedAccount.kind` name a provider's first kind only.** A provider may hold several (`kindsIn`,
150
+ `ListedAccount.kinds`, `holdsKind`); code that tests `kindIn(provider) === kind` misses the others.
151
+ - **`calendarAccounts`, `inSource(..., "events")` and `events list person:` now return phone accounts and calls**:
152
+ a phone account holds events, and a call's other side is found by its `related-to` link.
153
+ - **`run()` refuses `--offline` for a command annotated `offline: false`, or under a group that is**, before its
154
+ action and before the first-run questions: `permission_error`, reason `offline.refused`. A command's own
155
+ `--dry-run` still runs. cli-core's own such commands answered `validation_error` (`upgrade`, `topics`,
156
+ `chats inspect`, `chats send-as`) or `busy.offline` (`calendars busy`); they now all answer `offline.refused`, exit
157
+ code 5 instead of 2. `refuseOffline(command, service)` in `@wirecat/cli-core/cli` is the same refusal for a command
158
+ whose need depends on a flag, such as `session status --check`, so b24, beeline, gcal and cli-template drop theirs.
159
+ - **A cited source deleted for good leaves the citing evidence in place.** Removing a fact, memory, note, document,
160
+ calendar event, chat or account kept rows whose ids a later row could take, or deleted the links that cited them, so
161
+ a memory could lose a source without a trace or rest on someone else's text. Now each evidence link to the removed
162
+ row stays with no pointer and no quote, marked `gone`, and `sources` shows it `missing`; `memories.remove` and
163
+ `facts.remove` no longer count it among the links they removed. A message's tombstone drops quotes of it too. A
164
+ purged account or chat forgets evidence to every row it took, chats included, and a chat merge re-signs the
165
+ evidence it moves onto the kept chat and messages.
166
+ - **An agent can no longer retire what the owner stands behind**, even with `agent_decisions` on:
167
+ `memories.markStale` of a confirmed memory, and `facts.accept` of a correction that supersedes an accepted fact,
168
+ refuse an agent with `proposal.owner-only`. An agent that finds such a memory or fact wrong calls
169
+ `knowledge.challenge` with what contradicts it, and the owner decides the review. An agent allowed to decide may
170
+ still turn down another agent's proposed memory, and accept a correction of a fact that is only proposed.
171
+ - **An invoice's paid amount is net of confirmed refunds.** `paid`, `open`, the status, `openTotals` and the void check
172
+ read one figure, the confirmed allocations of payments less those of their refunds: an invoice refunded in full is
173
+ `issued` again and may be voided. An older memo computes paid gross; update memo before writing refunds.
174
+ - **A person, organization or project record is matched or made on import**, in every file, v1 files included. One
175
+ exact e-mail, E.164 phone, organization identifier or project key links it; none makes the entity (marked
176
+ `createdEntity`) with the record's identifiers; two or more leave it `unmatched` (`record.ambiguous`). A record
177
+ that waited for the owner's `records.map` is matched or made on its next import, so dry-run an old file before
178
+ importing it again. An organization's `email` identifier is kept under the provider `org-email`.
179
+ - **`store.records.write` is `store.records.run`**, taking an iterable of `{ index, record, errors? }` and answering
180
+ counts and capped lists instead of one outcome per record; `RecordOutcome` and `RecordsWritten` are gone. A
181
+ `SourceRecord` relation's `externalId` is `null` when it names a `ref`. `ingest` checks a record's fields against
182
+ its type's schema first, so a broken v1 invoice or payment field is refused with `record.invalid` at the field's
183
+ pointer.
184
+ - **A CRM contact identity escapes a `/` or `%`** in its account or id (`%2F`, `%25`), so two accounts never share
185
+ one; ids without them, every CRM's so far, keep their identity.
186
+
187
+ ### Fixed
188
+
189
+ - **A CRM field lookup's refusal names the option the name came from.** `fieldNamed`, `unknownField` and `optionOf`
190
+ take that option as a last argument, `--field` when left out. They always answered `param: "--field"`, so a CRM
191
+ CLI that looked up a field named in `--query` or `--json` pointed the caller at the wrong option.
192
+ - **`store.accounts.purge` deletes the account's documents too**, with their files, pieces, words and the links to
193
+ them; a notes folder, Drive or added account with documents no longer stops at them.
194
+
195
+ ## 0.606.0 — 08.11.2026
196
+
197
+ ### Added
198
+
199
+ - **Business relationships: `reports-to`, `customer-of` and `partner-of`, role lists, and a `standing` on every
200
+ relationship.** `knowledge.relate` takes a person reporting to a person, a person or organization buying from an
201
+ organization, and two partner organizations (stored once, the lower id first, whichever way they are named). A deal
202
+ or a lead may be a relationship's `from`, so its people are relationships too, and `influencer` joins the deal roles.
203
+ Each relationship answers `standing`: `confirmed`, `reported` (a source's, nobody confirmed it), `proposed` or
204
+ `ended`. The kinds, their ends and roles are one registry, `RELATIONS` (`src/domain/relations.ts`), exported with
205
+ `ORGANIZATION_ROLES`, `PROJECT_ROLES`, `standingOf` and `usableLink`.
206
+ - **`review --holder` gives each email the cursor and findings key that end the batch at it** (`email.cursor`,
207
+ `email.findings_key`). A reader that cuts the batch to fit, such as an agent's input, acknowledges the last email it
208
+ showed instead of the batch's end, so the mark never moves past mail it did not show. Held emails, older than
209
+ the mark, end the batch at the mark with a key of their own (`<holder>:<mark>-h<highest held id>`).
210
+ - **`@wirecat/cli-core/cli` exports `AGENT_INPUT_MAX_CHARS`**, the 60,000-character cut of an agent's input, so a
211
+ host that builds the input can stay under it and cut at its own boundaries.
212
+
213
+ - **Relationship links know the account that reported them, when they held, and their history (store version 56).**
214
+ `links` gains `account_id`, `starts_at`, `ends_at` and `deleted_at`; `link_revisions` keeps one row per change of a
215
+ relationship link (`added`, `changed`, `ended`, `confirmed`, `withdrawn`, `restored`, `rejected`, `removed`),
216
+ written by triggers, never for a change of `updated_at` alone and never for links of other kinds. A unique key on
217
+ relationship links (kind, ends, anchor, role, account) lets one pair hold several roles and keeps a source's claim
218
+ apart from the owner's; the migration folds duplicates onto the owner's row, keeps their metadata and re-points the
219
+ proposals that named a dropped row.
220
+
221
+ - **A CRM sync keeps the relationships the CRM reports, as a diff.** Contacts become `member-of` their companies (role
222
+ `contact`, the job title beside it), a deal's contacts keep their deal roles and its `assignee` is its `owner`, the
223
+ account's users are `member-of` its own companies as `employee` and, from the departments, `reports-to` their head.
224
+ What the CRM stops reporting is withdrawn, not deleted; a link the owner confirmed is never withdrawn, and one the
225
+ owner removed or rejected, role included, is not written again (`skipped_owner_rejected`). A deal that names a
226
+ contact not synced yet gets it on a later run. `CrmPerson.organizations`/`position`, `CrmItem.people[].primary`,
227
+ `CrmOrganization.own`/`type`, `CrmUser`, `CrmDepartment` and `CrmSource.users()`/`departments()` carry them, all
228
+ optional. The same diff is `store.relations.syncReported` for any source. The store settings
229
+ `crm.<provider>:<account>.links` (`reported` or `review`: new relationships wait as proposals) and
230
+ `crm.<provider>:<account>.company-types` (a company type means `customer-of`, `supplier` or `partner-of` the own
231
+ company) are offered by every CLI's `config`. `knowledge.setOwnOrganization` records the owner's own-company
232
+ mark, which no sync changes; `crmGapsOf` reads what the account's last sync could not list (`{ kind, reason, code?, scope?, message }`).
233
+ Every `CrmSource` call takes an optional `CrmCallContext`: `spend()` takes one budget unit per extra request and
234
+ stops the run as `partial` when it is spent; `gap()` reports what a call could not read without failing it.
235
+ - **A relationship keeps a job title and when it held.** `relate` and `updateRelation` take `position`, `startsAt`
236
+ and `endsAt` (UTC ms, the end after the start); relationships answer `position`, `startsAt` and `endsAt`.
237
+ `knowledge.endRelation(key, id, at, by)` ends one without removing it (standing `ended` from then); an agent's end
238
+ is a `relationship_update` proposal.
239
+ - **The owner adds his own roles to the organization, project and deal role lists.** `knowledge.roles(list)`,
240
+ `addRole(list, id, label?)` and `removeRole(list, id)`, kept in the store setting `relationships.roles.<list>`; a
241
+ role id is lowercase letters, digits and `-`. Built-in roles stay; a role a relationship still holds is not removed
242
+ (`relationship.role-in-use` with the count).
243
+ - **`knowledge.listRelations(filter)` filters and pages relationships and pending relationship proposals in SQL.**
244
+ By `kind`, `role`, `standing`, `from`, `to`, `about` (both ways, each row with `direction` and the inverse label),
245
+ `at`, `includeEnded`, `accounts` (a source's rows only from these; the owner's always) and `deniedKinds`; `limit`
246
+ and `page` with `hasMore`. Each row says its `source` (`link` or `proposal`) and `custom` for a stored role off its
247
+ list.
248
+
249
+ ### Changed — may break callers
250
+
251
+ - **Store version 56 raises `minCompatible` to 56: a build from before it refuses the store and asks to be upgraded.**
252
+ A build that knows no account on a link would write a CRM's people as the owner's again, or fail on the new unique
253
+ key. Bump every CLI the same day as this release.
254
+
255
+ - **A person's role on an organization, a project, a deal or a lead must be one of that relationship's roles.**
256
+ `relate` and `updateRelation` refuse any other with `relationship.role-unknown`, naming the roles it takes; a role
257
+ between other ends stays free text, and roles already stored are read as they are. `member-of` now joins only to an
258
+ organization or a project. What to do: map a free-text role to the closest listed one (a job title goes in
259
+ `metadata.position`, never in the role); memo's `author`, `lead` and `cto` examples and tests need it.
260
+ - **`KnowledgeRelation.standing` and the `relationship` entity's `standing` are required.** A caller that builds one
261
+ by hand adds it; `standingOf` derives it from the link.
262
+ - **A CRM's deal and lead people are `confirmed: false`, `standing: reported` (store version 56).** They were stored
263
+ confirmed, as if the owner had said so. They still count wherever confirmed relationships count (`usableLink`), and
264
+ a deal still lists them; a view that reads `confirmed: false` as "proposed" (memo's relationships list) should read
265
+ `standing` instead.
266
+ - **The owner's change to a relationship a CRM reported overrides it.** The first `updateRelation`, `endRelation` or
267
+ confirmed `relationship_update` on a reported link makes one owner link that overrides it (`metadata.overrides`);
268
+ later changes change that link in place. Reads show the override instead of the CRM's row, which its sync keeps
269
+ diffing; removing the override shows the CRM's row again. A role is checked against the current role lists when a
270
+ proposal is approved, and a role a pending proposal holds counts as in use.
271
+ - **`relate` with a role the pair does not hold yet makes a second relationship**, since one pair may hold several
272
+ roles; without a role it answers the pair's link as before. `updateRelation` to a role the pair already holds is
273
+ refused with `relationship.exists`.
274
+ - **Removing any relationship leaves a rejected proposal**, so neither a scan nor a source's sync brings it back; it
275
+ was so only for a link to a project or a suggestion.
276
+ - **A memory written as `proposed` with `supersedes` no longer retires the old one until it is confirmed**, the
277
+ owner's included. `store.memories.add` and `confirm` refuse superseding a memory that is already superseded
278
+ (`memory.already-superseded`), so two corrections of one memory cannot both stand. drive-cli writes every memory
279
+ `proposed`, so its `memories add --supersedes` now retires the old memory only when that memory's correction is
280
+ confirmed.
281
+
282
+ ### Fixed
283
+
284
+ - **The person a CRM contact or user makes takes its name.** Joined to the mail contact of its address first, it was
285
+ left with no name.
286
+ - **A holder's batch of held emails only no longer reuses the findings key of the run that set the mark**, which
287
+ refused its staging (`key-used`): it takes `-h<highest held id>`.
288
+ - **An agent's correction no longer retires the memory it corrects.** `store.memories.add({ supersedes })` marked the
289
+ old memory `superseded` as soon as the new one was written, even while the new one only waited as proposed. Now
290
+ `confirm` of the correction retires it; rejecting or removing the correction leaves it as it was. Retiring a
291
+ confirmed memory is the owner's alone, whatever `agent_decisions` says.
9
292
 
10
293
  ## 0.605.0 — 07.11.2026
11
294
 
@@ -2,6 +2,7 @@ export type { CalendarAccessRole, CalendarInput, EntryAttachment, EntryAttachmen
2
2
  export { expandSeries, localMoment, unexpandable } from "./expand.js";
3
3
  export { type CalendarFeeds, FEED_LIMITS, FEED_PREFIX, type FeedLimits, type FeedRecord, type FeedRegistry, type FeedSyncStats, type FeedsSyncReport, feedAddress, fetchFeed, icsFeeds, isFeedCalendar, readFeed, syncWithFeeds, } from "./feeds.js";
4
4
  export { type IcsEvent, type IcsOverride, type IcsRead, type IcsSkip, readIcs, writeIcs } from "./ics.js";
5
+ export { accountsMeta } from "./reads.js";
5
6
  export { repeatRule } from "./recurrence.js";
6
7
  export type { BusyTimes, CalendarExpander, CalendarSource, CalendarSourceTraits, ChangePage, ChangeResult, FreeBusyRequest, SearchPage, SyncWindow, } from "./source.js";
7
8
  export { type CalendarCursor, type CalendarSyncOptions, type CalendarSyncReport, type CalendarSyncResult, calendarStatus, calendarSyncWindow, type PendingRound, parseCalendarCursor, syncCalendars, } from "./sync.js";
@@ -1,6 +1,7 @@
1
1
  export { expandSeries, localMoment, unexpandable } from "./expand.js";
2
2
  export { FEED_LIMITS, FEED_PREFIX, feedAddress, fetchFeed, icsFeeds, isFeedCalendar, readFeed, syncWithFeeds, } from "./feeds.js";
3
3
  export { readIcs, writeIcs } from "./ics.js";
4
+ export { accountsMeta } from "./reads.js";
4
5
  export { repeatRule } from "./recurrence.js";
5
6
  export { calendarStatus, calendarSyncWindow, parseCalendarCursor, syncCalendars, } from "./sync.js";
6
7
  export { CALENDAR_WRITE_DEFAULTS, CALENDAR_WRITE_KEYS, calendarConflict, EVENTS_DELETE_SERIES_KEY, EVENTS_NOTIFY_KEY, EVENTS_REMIND_HOOK_KEY, } from "./writer.js";
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { dateRange, dayBoundary, queryError, queryFieldsOf, } from "@wirecat/cli-base/query";
3
3
  import { LIST_QUERY_GUIDE, listQuery, nativeTermLists, negatableOf, typedQuery, } from "../cli/list-query.js";
4
+ import { isImportedProvider } from "../domain/providers.js";
4
5
  import { event, eventChange, eventItem, listed, } from "../meetings/index.js";
5
6
  import { entriesOfList, fitting } from "../search/account-list.js";
6
7
  import { listContextOf } from "../services/search-kind.js";
@@ -78,6 +79,7 @@ export const EVENT_TYPES = [
78
79
  "working-location",
79
80
  "birthday",
80
81
  "from-mail",
82
+ "call",
81
83
  ];
82
84
  const oneSided = (field, example) => (node) => {
83
85
  if (node.operator !== "range" || node.upper !== "*")
@@ -481,6 +483,9 @@ export const sourceAccounts = async (messages, running, source, command) => {
481
483
  export const accountsMeta = async (store, accounts, skipped, now) => {
482
484
  const issues = [...skipped];
483
485
  for (const { id, key } of accounts) {
486
+ // An import's calls are all it has: no sync could be behind on them.
487
+ if (isImportedProvider(key.provider))
488
+ continue;
484
489
  const { items } = await calendarStatus(store, id, { profile: nameOf(key), now });
485
490
  if (items.length === 0)
486
491
  issues.push({ code: "not_found", reason: "calendar.unsynced", source: nameOf(key) });
@@ -1,3 +1,4 @@
1
+ import type { KeyringStore } from "@wirecat/cli-base";
1
2
  import type { Command } from "commander";
2
3
  import type { AppServerOptions } from "../mcp/app-server.js";
3
4
  import type { AppIdentity } from "../ports/app.js";
@@ -12,8 +13,11 @@ export interface AppMcpOptions {
12
13
  skill?: URL;
13
14
  /** What the CLI alone knows stops a command for a profile, such as an OAuth grant without the scope. */
14
15
  availability?: AppServerOptions["availability"];
15
- /** Whether the profile can reach the service, read from disk; left out, `mcp check` does not say. */
16
- signedIn?: (profile: string, env: NodeJS.ProcessEnv) => boolean;
16
+ /**
17
+ * Whether the profile can reach the service, read from disk with the run's keyring (a test's `memoryKeyring()`);
18
+ * left out, `mcp check` does not say. A throw, such as a locked keyring, counts as not signed in.
19
+ */
20
+ signedIn?: (profile: string, env: NodeJS.ProcessEnv, keyring: KeyringStore | undefined) => boolean;
17
21
  }
18
22
  /**
19
23
  * `mcp serve | revoke | server | config | add | check` for a CLI that is not a messenger — the same commands, flags
@@ -1,4 +1,4 @@
1
- import { baseContext } from "./context.js";
1
+ import { baseContext, environmentOf } from "./context.js";
2
2
  import { mcpGroup } from "./messenger/mcp-command.js";
3
3
  import { refuseUnknownPermissionKeys } from "./permission-keys.js";
4
4
  /**
@@ -43,7 +43,16 @@ export const appMcpCommand = (app, configuration, options) => {
43
43
  untrusted: options.untrusted,
44
44
  });
45
45
  },
46
- signedIn: (_self, profile, env) => options.signedIn?.(profile, env),
46
+ signedIn: (self, profile, env) => {
47
+ if (!options.signedIn)
48
+ return undefined;
49
+ try {
50
+ return options.signedIn(profile, env, environmentOf(self).keyring);
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ },
47
56
  };
48
57
  return mcpGroup(host);
49
58
  };
@@ -0,0 +1,10 @@
1
+ import type { Streams } from "@wirecat/cli-base";
2
+ /**
3
+ * One cell as RFC 4180 writes it, safe to open in a spreadsheet: text that would start a formula gets a leading `'`,
4
+ * since every cell may be what someone else typed into the CRM.
5
+ */
6
+ export declare const csvCell: (value: unknown) => string;
7
+ /** A header and its rows as RFC 4180 records, without line ends; the header is guarded like any cell. */
8
+ export declare const csvRecords: (header: readonly string[], rows: readonly (readonly unknown[])[]) => string[];
9
+ /** The table on stdout and nothing else, every record ending in CRLF. */
10
+ export declare const writeCsv: (streams: Pick<Streams, "data">, header: readonly string[], rows: readonly (readonly unknown[])[]) => void;
@@ -0,0 +1,22 @@
1
+ /** A number a spreadsheet reads as a number; it cannot be a formula, so a leading minus stays. */
2
+ const NUMBER = /^-?\d+(\.\d+)?$/;
3
+ /** What a spreadsheet reads as the start of a formula (OWASP's CSV injection list). */
4
+ const FORMULA = /^[=+\-@\t\r]/;
5
+ /**
6
+ * One cell as RFC 4180 writes it, safe to open in a spreadsheet: text that would start a formula gets a leading `'`,
7
+ * since every cell may be what someone else typed into the CRM.
8
+ */
9
+ export const csvCell = (value) => {
10
+ if (value === null || value === undefined)
11
+ return "";
12
+ const text = String(value);
13
+ const safe = FORMULA.test(text) && !NUMBER.test(text) ? `'${text}` : text;
14
+ return /[",\r\n]/.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
15
+ };
16
+ /** A header and its rows as RFC 4180 records, without line ends; the header is guarded like any cell. */
17
+ export const csvRecords = (header, rows) => [header, ...rows].map((row) => row.map(csvCell).join(","));
18
+ /** The table on stdout and nothing else, every record ending in CRLF. */
19
+ export const writeCsv = (streams, header, rows) => {
20
+ // `data` adds the "\n" itself, so the last record's CRLF needs only its "\r".
21
+ streams.data(`${csvRecords(header, rows).join("\r\n")}\r`);
22
+ };
@@ -1,6 +1,16 @@
1
1
  import type { Command } from "commander";
2
2
  import { type AppIdentity } from "../ports/app.js";
3
3
  import { type CommandPermissions } from "./permission-keys.js";
4
+ /**
5
+ * Refuses `--offline` for a command that needs the service: call it where the need depends on a flag, such as
6
+ * `session status --check`. A command that always needs it is annotated `offline: false`, and `run()` refuses it.
7
+ */
8
+ export declare const refuseOffline: (command: Command, service: string) => void;
9
+ /**
10
+ * Refuses `--offline` before anything runs when the command, or a group above it, is annotated `offline: false`. A
11
+ * command's own `--dry-run` passes: it answers without the service.
12
+ */
13
+ export declare const refuseOfflineCommand: (action: Command, app: AppIdentity, offline: boolean, preview: boolean) => void;
4
14
  type Resolve = (flags: object, options: {
5
15
  env: NodeJS.ProcessEnv;
6
16
  needsProfile: false;
@@ -11,6 +11,25 @@ import { withAgentLevels } from "./context.js";
11
11
  import { changesMessenger } from "./effects.js";
12
12
  import { refuseUnknownPermissionKeys } from "./permission-keys.js";
13
13
  import { NONE_NAMED, settingsFor } from "./settings.js";
14
+ /**
15
+ * Refuses `--offline` for a command that needs the service: call it where the need depends on a flag, such as
16
+ * `session status --check`. A command that always needs it is annotated `offline: false`, and `run()` refuses it.
17
+ */
18
+ export const refuseOffline = (command, service) => {
19
+ if (command.optsWithGlobals().offline)
20
+ throw new CliError("permission_error", `this needs ${service}; leave out --offline`, { reason: "offline.refused" });
21
+ };
22
+ /**
23
+ * Refuses `--offline` before anything runs when the command, or a group above it, is annotated `offline: false`. A
24
+ * command's own `--dry-run` passes: it answers without the service.
25
+ */
26
+ export const refuseOfflineCommand = (action, app, offline, preview) => {
27
+ if (!offline || preview)
28
+ return;
29
+ for (let command = action; command; command = command.parent)
30
+ if (metaOf(command).offline === false)
31
+ throw new CliError("permission_error", `\`${[app.command, ...commandPathOf(action)].join(" ")}\` needs the service, not the local copy; leave out --offline`, { reason: "offline.refused" });
32
+ };
14
33
  /**
15
34
  * Refuses a change on the messenger the read-only lock or the profile's level stops, before anything connects
16
35
  * (SEC-62). The send guard would refuse it too, but only after the command connected and found its chat. The journal
@@ -1,5 +1,5 @@
1
1
  export { AI_ENTRIES, AI_SETTING_KEYS, type AISettings, resolveAISettings } from "../analysis/settings.js";
2
- export type { AgentCli, AgentInput } from "../background/schedules.js";
2
+ export { AGENT_INPUT_MAX_CHARS, type AgentCli, type AgentInput } from "../background/schedules.js";
3
3
  export { parseDuration } from "../domain/duration.js";
4
4
  export { openOf, PROFILE_PLACEHOLDER, type ProfilesFor, type RefOpen, type RefSummary, refLabel, } from "../domain/ref-summaries.js";
5
5
  export { botTemplate } from "../entities/list-results.js";
@@ -69,9 +69,11 @@ export { loadSnakeCaseConfig } from "./config-keys.js";
69
69
  export { type AgentRun, type BaseContext, type BaseEnvironment, baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, } from "./context.js";
70
70
  export { addContractInfo, type ContractEvidenceOptions, contractEvidence } from "./contract-evidence.js";
71
71
  export { sharedCommandTemplate } from "./contract-templates.js";
72
+ export { csvCell, csvRecords, writeCsv } from "./csv.js";
72
73
  export { type Closeable, withDeadline } from "./deadline.js";
73
74
  export { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
74
75
  export { DISCOVERY_DESCRIPTIONS } from "./discovery-descriptions.js";
76
+ export { refuseOffline } from "./early-refusal.js";
75
77
  export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, writesNewFileOnlyWith, } from "./effects.js";
76
78
  export { type CliEntry, type EntryContext, type EntryIo, openBrowser, startCli } from "./entry.js";
77
79
  export { type AnswerOutput, answerSchema, type Body, type ItemBody, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, type ListBody, type ListInput, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
@@ -119,6 +121,7 @@ export { writeNewFile } from "./new-file.js";
119
121
  export { positiveCount, window, withPaging } from "./paging.js";
120
122
  export { type CommandPermissions, type ConditionalKey, commandPathKey, commandPermissions, knownBeside, knownPermissionKeys, type PermissionKeyOf, type PermissionKeySource, refuseUnknownPermissionKeys, unknownPermissionIssues, unknownPermissionKeys, } from "./permission-keys.js";
121
123
  export { asFirstWord, commandWords, liftProfile, profileFree, refuseCommandName, rootOf, takesProfile, usableProfileName, } from "./profile.js";
124
+ export { ProfileTokenStore, type ProfileTokenStoreOptions, type TokenStorage } from "./profile-token.js";
122
125
  export { createProgram, type ProgramDefinition, type ProgramOptions, type RunOptions, run } from "./program.js";
123
126
  export { type ProjectTextHints, projectAnswerParts, projectCutoffTime, projectEvidenceText, projectWindowOf, withSyncCommands, } from "./project-evidence.js";
124
127
  export { type ProjectStatusHints, type ProjectStatusItem, projectStatusAnswer, projectStatusRow, projectStatusSchema, projectStatusText, } from "./project-status.js";
package/dist/cli/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { AI_ENTRIES, AI_SETTING_KEYS, resolveAISettings } from "../analysis/settings.js";
2
+ export { AGENT_INPUT_MAX_CHARS } from "../background/schedules.js";
2
3
  export { parseDuration } from "../domain/duration.js";
3
4
  export { openOf, PROFILE_PLACEHOLDER, refLabel, } from "../domain/ref-summaries.js";
4
5
  export { botTemplate } from "../entities/list-results.js";
@@ -60,9 +61,11 @@ export { loadSnakeCaseConfig } from "./config-keys.js";
60
61
  export { baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, } from "./context.js";
61
62
  export { addContractInfo, contractEvidence } from "./contract-evidence.js";
62
63
  export { sharedCommandTemplate } from "./contract-templates.js";
64
+ export { csvCell, csvRecords, writeCsv } from "./csv.js";
63
65
  export { withDeadline } from "./deadline.js";
64
66
  export { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
65
67
  export { DISCOVERY_DESCRIPTIONS } from "./discovery-descriptions.js";
68
+ export { refuseOffline } from "./early-refusal.js";
66
69
  export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, writesNewFileOnlyWith, } from "./effects.js";
67
70
  export { openBrowser, startCli } from "./entry.js";
68
71
  export { answerSchema, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
@@ -108,6 +111,7 @@ export { writeNewFile } from "./new-file.js";
108
111
  export { positiveCount, window, withPaging } from "./paging.js";
109
112
  export { commandPathKey, commandPermissions, knownBeside, knownPermissionKeys, refuseUnknownPermissionKeys, unknownPermissionIssues, unknownPermissionKeys, } from "./permission-keys.js";
110
113
  export { asFirstWord, commandWords, liftProfile, profileFree, refuseCommandName, rootOf, takesProfile, usableProfileName, } from "./profile.js";
114
+ export { ProfileTokenStore } from "./profile-token.js";
111
115
  export { createProgram, run } from "./program.js";
112
116
  export { projectAnswerParts, projectCutoffTime, projectEvidenceText, projectWindowOf, withSyncCommands, } from "./project-evidence.js";
113
117
  export { projectStatusAnswer, projectStatusRow, projectStatusSchema, projectStatusText, } from "./project-status.js";
@@ -0,0 +1,29 @@
1
+ import { type CredentialSource, type KeyringStore, type StoredCredential } from "@wirecat/cli-base";
2
+ import { type AppIdentity } from "../ports/app.js";
3
+ export type TokenStorage = "keyring" | "file";
4
+ export interface ProfileTokenStoreOptions {
5
+ app: AppIdentity;
6
+ env?: NodeJS.ProcessEnv;
7
+ keyring?: KeyringStore;
8
+ /** Where the one warning about an unreachable keyring goes; stderr when left out. */
9
+ warn?: (message: string) => void;
10
+ }
11
+ /**
12
+ * One API token per profile for a CLI that is not a messenger: `<PREFIX>_TOKEN`, then the keyring entry
13
+ * `token:<profile>` under the app's own service, then a 0600 file (WC-SECR-4). A run with moved folders reads the
14
+ * owner's entry and never replaces or deletes it: it writes a temporary `<app>:<config folder>` entry instead
15
+ * (WC-SECR-24, cli-base `Credentials`).
16
+ */
17
+ export declare class ProfileTokenStore {
18
+ #private;
19
+ readonly variable: string;
20
+ constructor({ app, env, keyring, warn }: ProfileTokenStoreOptions);
21
+ read(profile: string): StoredCredential | undefined;
22
+ /** `file` also forgets the keyring copy, so a later read cannot find the token the owner asked to keep elsewhere. */
23
+ write(profile: string, token: string, storage?: TokenStorage): CredentialSource;
24
+ remove(profile: string): CredentialSource[];
25
+ /** The profile's token, or the one "not signed in" refusal every token CLI gives, naming the command to fix it. */
26
+ need(profile: string): string;
27
+ /** For `appMcpCommand`'s `signedIn`: a keyring that cannot be read counts as not signed in. */
28
+ signedIn(profile: string): boolean;
29
+ }
@@ -0,0 +1,65 @@
1
+ import { CliError, Credentials, isMovedRun, resolvePaths, } from "@wirecat/cli-base";
2
+ import { envName } from "../ports/app.js";
3
+ /**
4
+ * One API token per profile for a CLI that is not a messenger: `<PREFIX>_TOKEN`, then the keyring entry
5
+ * `token:<profile>` under the app's own service, then a 0600 file (WC-SECR-4). A run with moved folders reads the
6
+ * owner's entry and never replaces or deletes it: it writes a temporary `<app>:<config folder>` entry instead
7
+ * (WC-SECR-24, cli-base `Credentials`).
8
+ */
9
+ export class ProfileTokenStore {
10
+ variable;
11
+ #app;
12
+ #options;
13
+ #credentials;
14
+ constructor({ app, env = process.env, keyring, warn }) {
15
+ const where = { appName: app.appName, prefix: app.envPrefix, env };
16
+ this.#app = app;
17
+ this.variable = envName(app, "TOKEN");
18
+ this.#options = {
19
+ configDir: resolvePaths(where).config,
20
+ service: app.appName,
21
+ envVar: this.variable,
22
+ isolated: isMovedRun(where),
23
+ env,
24
+ ...(keyring ? { keyring } : {}),
25
+ warn: warn ?? ((message) => process.stderr.write(`${message}\n`)),
26
+ };
27
+ this.#credentials = new Credentials(this.#options);
28
+ }
29
+ read(profile) {
30
+ return this.#credentials.read(accountOf(profile));
31
+ }
32
+ /** `file` also forgets the keyring copy, so a later read cannot find the token the owner asked to keep elsewhere. */
33
+ write(profile, token, storage = "keyring") {
34
+ if (storage === "keyring")
35
+ return this.#credentials.write(accountOf(profile), token, { signIn: true });
36
+ const kept = new Credentials({ ...this.#options, storage: "file" }).write(accountOf(profile), token);
37
+ try {
38
+ new Credentials({ ...this.#options, storage: "keyring" }).remove(accountOf(profile));
39
+ }
40
+ catch {
41
+ // No keyring on this computer: there is no copy to forget.
42
+ }
43
+ return kept;
44
+ }
45
+ remove(profile) {
46
+ return this.#credentials.remove(accountOf(profile));
47
+ }
48
+ /** The profile's token, or the one "not signed in" refusal every token CLI gives, naming the command to fix it. */
49
+ need(profile) {
50
+ const stored = this.read(profile);
51
+ if (stored)
52
+ return stored.secret;
53
+ throw new CliError("authentication_error", `profile ${profile} is not signed in — run \`${this.#app.command} ${profile} session start\``, { reason: "session.missing" });
54
+ }
55
+ /** For `appMcpCommand`'s `signedIn`: a keyring that cannot be read counts as not signed in. */
56
+ signedIn(profile) {
57
+ try {
58
+ return this.read(profile) !== undefined;
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ }
64
+ }
65
+ const accountOf = (profile) => `token:${profile}`;