@codespar/cli 0.17.0 → 0.18.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 (480) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/templates/bills-agent/README.md +1 -1
  4. package/templates/bills-agent/agents/bills-agent/AGENTS.md +1 -1
  5. package/templates/bills-agent/agents/bills-agent/CLAUDE.md +1 -1
  6. package/templates/bills-agent/agents/bills-agent/README.md +6 -5
  7. package/templates/bills-agent/agents/bills-agent/src/modules/embedded-consent.ts +5 -4
  8. package/templates/bills-agent/packages/agent-core/README.md +14 -1
  9. package/templates/bills-agent/packages/agent-core/package.json +1 -1
  10. package/templates/bills-agent/packages/agent-core/src/agent.ts +39 -1
  11. package/templates/bills-agent/packages/agent-core/src/api/charge-rail.ts +54 -34
  12. package/templates/bills-agent/packages/agent-core/src/api/client.ts +28 -5
  13. package/templates/bills-agent/packages/agent-core/src/api/mandate-status.ts +28 -12
  14. package/templates/bills-agent/packages/agent-core/src/api/rail.ts +62 -26
  15. package/templates/bills-agent/packages/agent-core/src/api/sandbox-payer.ts +3 -18
  16. package/templates/bills-agent/packages/agent-core/src/approval.ts +14 -2
  17. package/templates/bills-agent/packages/agent-core/src/bundle.ts +35 -3
  18. package/templates/bills-agent/packages/agent-core/src/channels.ts +49 -3
  19. package/templates/bills-agent/packages/agent-core/src/check.ts +25 -2
  20. package/templates/bills-agent/packages/agent-core/src/engine.ts +235 -46
  21. package/templates/bills-agent/packages/agent-core/src/hash.ts +57 -1
  22. package/templates/bills-agent/packages/agent-core/src/index.ts +2 -0
  23. package/templates/bills-agent/packages/agent-core/src/quote.ts +50 -0
  24. package/templates/bills-agent/packages/agent-core/src/rail.ts +89 -4
  25. package/templates/bills-agent/packages/agent-core/src/receipt-chain.ts +270 -0
  26. package/templates/bills-agent/packages/agent-core/src/receipt-verification.ts +194 -18
  27. package/templates/bills-agent/packages/agent-core/src/revocation.ts +1 -1
  28. package/templates/bills-agent/packages/agent-core/src/state-machine.ts +10 -1
  29. package/templates/bills-agent/packages/agent-core/src/stubs/mandate-status.ts +4 -3
  30. package/templates/bills-agent/packages/agent-core/src/stubs/rail.ts +100 -32
  31. package/templates/bills-agent/packages/agent-core/src/tools.ts +17 -6
  32. package/templates/bills-agent/packages/agent-core/src/types.ts +54 -1
  33. package/templates/bills-agent/packages/agent-core/test/approval-seal.test.ts +233 -0
  34. package/templates/bills-agent/packages/agent-core/test/attempt-replay.test.ts +265 -0
  35. package/templates/bills-agent/packages/agent-core/test/composition.test.ts +204 -0
  36. package/templates/bills-agent/packages/agent-core/test/fixtures/production-receipt-keys.json +1 -0
  37. package/templates/bills-agent/packages/agent-core/test/helpers.ts +4 -1
  38. package/templates/bills-agent/packages/agent-core/test/mandate-status.test.ts +85 -9
  39. package/templates/bills-agent/packages/agent-core/test/quote.test.ts +198 -0
  40. package/templates/bills-agent/packages/agent-core/test/receipt-chain.test.ts +220 -0
  41. package/templates/bills-agent/packages/agent-core/test/receipt-read-verification.test.ts +197 -0
  42. package/templates/bills-agent/packages/agent-core/test/receivables.test.ts +103 -3
  43. package/templates/bills-agent/packages/agent-runtime/README.md +12 -0
  44. package/templates/bills-agent/packages/agent-runtime/src/adversarial.ts +32 -2
  45. package/templates/bills-agent/packages/agent-runtime/src/channels/types.ts +53 -4
  46. package/templates/bills-agent/packages/agent-runtime/src/channels/whatsapp/cloud-api.ts +123 -22
  47. package/templates/bills-agent/packages/agent-runtime/src/channels/whatsapp/emulator.ts +30 -20
  48. package/templates/bills-agent/packages/agent-runtime/src/channels/whatsapp/index.ts +146 -21
  49. package/templates/bills-agent/packages/agent-runtime/src/channels/whatsapp/open.ts +40 -3
  50. package/templates/bills-agent/packages/agent-runtime/src/channels/whatsapp/run.ts +8 -1
  51. package/templates/bills-agent/packages/agent-runtime/src/channels/whatsapp/session.ts +16 -2
  52. package/templates/bills-agent/packages/agent-runtime/src/commands/poll-whatsapp.ts +70 -20
  53. package/templates/bills-agent/packages/agent-runtime/src/commands/poll.ts +2 -1
  54. package/templates/bills-agent/packages/agent-runtime/src/commands/resume.ts +8 -2
  55. package/templates/bills-agent/packages/agent-runtime/src/commands/start-whatsapp.ts +3 -0
  56. package/templates/bills-agent/packages/agent-runtime/src/commands/start.ts +6 -3
  57. package/templates/bills-agent/packages/agent-runtime/src/commands/verify.ts +239 -38
  58. package/templates/bills-agent/packages/agent-runtime/src/commands/webhook.ts +3 -2
  59. package/templates/bills-agent/packages/agent-runtime/src/index.ts +1 -0
  60. package/templates/bills-agent/packages/agent-runtime/src/inspect.ts +5 -1
  61. package/templates/bills-agent/packages/agent-runtime/src/kit.ts +25 -2
  62. package/templates/bills-agent/packages/agent-runtime/src/scenarios.ts +8 -2
  63. package/templates/bills-agent/packages/agent-runtime/src/setup.ts +13 -3
  64. package/templates/bills-agent/packages/agent-runtime/src/terminal.ts +127 -18
  65. package/templates/bills-agent/packages/agent-runtime/test/verify-cli.test.ts +211 -9
  66. package/templates/bills-agent/packages/agent-runtime/test/whatsapp-cloud-api.test.ts +45 -0
  67. package/templates/bills-agent/packages/agent-runtime/test/whatsapp-session.test.ts +32 -0
  68. package/templates/bills-agent/packages/agent-runtime/test/whatsapp-status-replies.test.ts +182 -0
  69. package/templates/checkout-agent/LICENSE +21 -0
  70. package/templates/checkout-agent/README.md +28 -0
  71. package/templates/checkout-agent/_gitignore +10 -0
  72. package/templates/checkout-agent/agents/checkout-agent/.env.example +5 -0
  73. package/templates/checkout-agent/agents/checkout-agent/AGENTS.md +20 -0
  74. package/templates/checkout-agent/agents/checkout-agent/CLAUDE.md +20 -0
  75. package/templates/checkout-agent/agents/checkout-agent/README.md +94 -0
  76. package/templates/checkout-agent/agents/checkout-agent/SYSTEM_PROMPT.md +36 -0
  77. package/templates/checkout-agent/agents/checkout-agent/agent.yaml +30 -0
  78. package/templates/checkout-agent/agents/checkout-agent/channels/whatsapp/README.md +28 -0
  79. package/templates/checkout-agent/agents/checkout-agent/channels/whatsapp/pedido-beatriz.json +11 -0
  80. package/templates/checkout-agent/agents/checkout-agent/channels/whatsapp/pedido-marina-retomada.json +10 -0
  81. package/templates/checkout-agent/agents/checkout-agent/channels/whatsapp/pedido-marina.json +11 -0
  82. package/templates/checkout-agent/agents/checkout-agent/channels/whatsapp/templates.json +49 -0
  83. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/beneficiary-swap-human.json +12 -0
  84. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/beneficiary-swap.json +11 -0
  85. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/beneficiary-swap.transcript.jsonl +5 -0
  86. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/coupon-unknown.json +13 -0
  87. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/coupon-unknown.transcript.jsonl +4 -0
  88. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/exfiltration.json +26 -0
  89. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/exfiltration.transcript.jsonl +3 -0
  90. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/false-authority.json +11 -0
  91. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/false-authority.transcript.jsonl +5 -0
  92. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/fractioning.json +12 -0
  93. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/fractioning.transcript.jsonl +5 -0
  94. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/model-total.json +13 -0
  95. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/model-total.transcript.jsonl +5 -0
  96. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/payment-claimed.json +15 -0
  97. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/payment-claimed.transcript.jsonl +7 -0
  98. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/price-injected.json +12 -0
  99. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/price-injected.transcript.jsonl +5 -0
  100. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/prompt-injection.json +13 -0
  101. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/prompt-injection.transcript.jsonl +4 -0
  102. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/quantity-swapped-human.json +16 -0
  103. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/quantity-swapped-human.transcript.jsonl +9 -0
  104. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/quantity-swapped.json +15 -0
  105. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/quantity-swapped.transcript.jsonl +8 -0
  106. package/templates/checkout-agent/agents/checkout-agent/evals/adversarial/webhook-replay.json +11 -0
  107. package/templates/checkout-agent/agents/checkout-agent/evals/eval.yaml +11 -0
  108. package/templates/checkout-agent/agents/checkout-agent/guardrails.json +25 -0
  109. package/templates/checkout-agent/agents/checkout-agent/mandate.example.json +28 -0
  110. package/templates/checkout-agent/agents/checkout-agent/package.json +33 -0
  111. package/templates/checkout-agent/agents/checkout-agent/runbook.md +19 -0
  112. package/templates/checkout-agent/agents/checkout-agent/scenarios/beneficiary-not-allowed.json +42 -0
  113. package/templates/checkout-agent/agents/checkout-agent/scenarios/beneficiary-not-allowed.transcript.jsonl +4 -0
  114. package/templates/checkout-agent/agents/checkout-agent/scenarios/cap-exceeded.json +32 -0
  115. package/templates/checkout-agent/agents/checkout-agent/scenarios/cap-exceeded.transcript.jsonl +4 -0
  116. package/templates/checkout-agent/agents/checkout-agent/scenarios/cart-recomposed.json +61 -0
  117. package/templates/checkout-agent/agents/checkout-agent/scenarios/cart-recomposed.transcript.jsonl +9 -0
  118. package/templates/checkout-agent/agents/checkout-agent/scenarios/cart-replaced.json +61 -0
  119. package/templates/checkout-agent/agents/checkout-agent/scenarios/cart-replaced.transcript.jsonl +9 -0
  120. package/templates/checkout-agent/agents/checkout-agent/scenarios/charge-expired.json +36 -0
  121. package/templates/checkout-agent/agents/checkout-agent/scenarios/charge-expired.transcript.jsonl +6 -0
  122. package/templates/checkout-agent/agents/checkout-agent/scenarios/coupon-unknown.json +23 -0
  123. package/templates/checkout-agent/agents/checkout-agent/scenarios/coupon-unknown.transcript.jsonl +4 -0
  124. package/templates/checkout-agent/agents/checkout-agent/scenarios/escalated-above-threshold.json +72 -0
  125. package/templates/checkout-agent/agents/checkout-agent/scenarios/escalated-above-threshold.transcript.jsonl +9 -0
  126. package/templates/checkout-agent/agents/checkout-agent/scenarios/happy-path.json +15 -0
  127. package/templates/checkout-agent/agents/checkout-agent/scenarios/happy-path.transcript.jsonl +6 -0
  128. package/templates/checkout-agent/agents/checkout-agent/scenarios/item-unavailable.json +23 -0
  129. package/templates/checkout-agent/agents/checkout-agent/scenarios/item-unavailable.transcript.jsonl +3 -0
  130. package/templates/checkout-agent/agents/checkout-agent/scenarios/mandate-revoked.json +42 -0
  131. package/templates/checkout-agent/agents/checkout-agent/scenarios/mandate-revoked.transcript.jsonl +12 -0
  132. package/templates/checkout-agent/agents/checkout-agent/scenarios/nfse-failed.json +14 -0
  133. package/templates/checkout-agent/agents/checkout-agent/scenarios/nfse-failed.transcript.jsonl +9 -0
  134. package/templates/checkout-agent/agents/checkout-agent/scenarios/payment-claimed.json +34 -0
  135. package/templates/checkout-agent/agents/checkout-agent/scenarios/payment-claimed.transcript.jsonl +7 -0
  136. package/templates/checkout-agent/agents/checkout-agent/scenarios/price-injected.json +33 -0
  137. package/templates/checkout-agent/agents/checkout-agent/scenarios/price-injected.transcript.jsonl +4 -0
  138. package/templates/checkout-agent/agents/checkout-agent/scenarios/prompt-injection.json +32 -0
  139. package/templates/checkout-agent/agents/checkout-agent/scenarios/prompt-injection.transcript.jsonl +4 -0
  140. package/templates/checkout-agent/agents/checkout-agent/src/catalog.ts +92 -0
  141. package/templates/checkout-agent/agents/checkout-agent/src/kit.ts +338 -0
  142. package/templates/checkout-agent/agents/checkout-agent/src/modules/bolepix-receivables.ts +179 -0
  143. package/templates/checkout-agent/agents/checkout-agent/src/modules/nfse-invoice.ts +374 -0
  144. package/templates/checkout-agent/agents/checkout-agent/src/modules/storefront-cart.ts +220 -0
  145. package/templates/checkout-agent/agents/checkout-agent/src/pricing.ts +297 -0
  146. package/templates/checkout-agent/agents/checkout-agent/test/adversarial.test.ts +117 -0
  147. package/templates/checkout-agent/agents/checkout-agent/test/check.test.ts +67 -0
  148. package/templates/checkout-agent/agents/checkout-agent/test/cli.test.ts +169 -0
  149. package/templates/checkout-agent/agents/checkout-agent/test/fixtures/order-marina.transcript.jsonl +5 -0
  150. package/templates/checkout-agent/agents/checkout-agent/test/fixtures/ordered-marina-awaiting-payer.transcript.jsonl +6 -0
  151. package/templates/checkout-agent/agents/checkout-agent/test/fixtures/tap-falar-agora-marina.transcript.jsonl +2 -0
  152. package/templates/checkout-agent/agents/checkout-agent/test/nfse.test.ts +170 -0
  153. package/templates/checkout-agent/agents/checkout-agent/test/pricing.test.ts +138 -0
  154. package/templates/checkout-agent/agents/checkout-agent/test/scenarios.test.ts +113 -0
  155. package/templates/checkout-agent/agents/checkout-agent/test/whatsapp.test.ts +171 -0
  156. package/templates/checkout-agent/agents/checkout-agent/tools.json +68 -0
  157. package/templates/checkout-agent/agents/checkout-agent/tsconfig.json +10 -0
  158. package/templates/checkout-agent/package.json +38 -0
  159. package/templates/checkout-agent/packages/agent-core/README.md +34 -0
  160. package/templates/checkout-agent/packages/agent-core/package.json +24 -0
  161. package/templates/checkout-agent/packages/agent-core/src/agent.ts +163 -0
  162. package/templates/checkout-agent/packages/agent-core/src/api/charge-rail.ts +195 -0
  163. package/templates/checkout-agent/packages/agent-core/src/api/client.ts +76 -0
  164. package/templates/checkout-agent/packages/agent-core/src/api/mandate-status.ts +74 -0
  165. package/templates/checkout-agent/packages/agent-core/src/api/rail.ts +153 -0
  166. package/templates/checkout-agent/packages/agent-core/src/api/sandbox-payer.ts +43 -0
  167. package/templates/checkout-agent/packages/agent-core/src/approval.ts +135 -0
  168. package/templates/checkout-agent/packages/agent-core/src/bundle.ts +191 -0
  169. package/templates/checkout-agent/packages/agent-core/src/channels.ts +186 -0
  170. package/templates/checkout-agent/packages/agent-core/src/check.ts +276 -0
  171. package/templates/checkout-agent/packages/agent-core/src/clock.ts +42 -0
  172. package/templates/checkout-agent/packages/agent-core/src/engine.ts +1074 -0
  173. package/templates/checkout-agent/packages/agent-core/src/escalate.ts +85 -0
  174. package/templates/checkout-agent/packages/agent-core/src/events.ts +40 -0
  175. package/templates/checkout-agent/packages/agent-core/src/guardrails.ts +45 -0
  176. package/templates/checkout-agent/packages/agent-core/src/hash.ts +118 -0
  177. package/templates/checkout-agent/packages/agent-core/src/ids.ts +10 -0
  178. package/templates/checkout-agent/packages/agent-core/src/index.ts +34 -0
  179. package/templates/checkout-agent/packages/agent-core/src/mandate.ts +100 -0
  180. package/templates/checkout-agent/packages/agent-core/src/manifest.ts +76 -0
  181. package/templates/checkout-agent/packages/agent-core/src/providers/anthropic.ts +76 -0
  182. package/templates/checkout-agent/packages/agent-core/src/providers/replay.ts +63 -0
  183. package/templates/checkout-agent/packages/agent-core/src/providers/types.ts +39 -0
  184. package/templates/checkout-agent/packages/agent-core/src/quote.ts +50 -0
  185. package/templates/checkout-agent/packages/agent-core/src/rail.ts +186 -0
  186. package/templates/checkout-agent/packages/agent-core/src/receipt-chain.ts +270 -0
  187. package/templates/checkout-agent/packages/agent-core/src/receipt-verification.ts +577 -0
  188. package/templates/checkout-agent/packages/agent-core/src/revocation.ts +30 -0
  189. package/templates/checkout-agent/packages/agent-core/src/secrets.ts +30 -0
  190. package/templates/checkout-agent/packages/agent-core/src/state/store.ts +307 -0
  191. package/templates/checkout-agent/packages/agent-core/src/state-machine.ts +157 -0
  192. package/templates/checkout-agent/packages/agent-core/src/stubs/charge-rail.ts +195 -0
  193. package/templates/checkout-agent/packages/agent-core/src/stubs/mandate-status.ts +58 -0
  194. package/templates/checkout-agent/packages/agent-core/src/stubs/rail.ts +209 -0
  195. package/templates/checkout-agent/packages/agent-core/src/tools.ts +66 -0
  196. package/templates/checkout-agent/packages/agent-core/src/types.ts +187 -0
  197. package/templates/checkout-agent/packages/agent-core/test/approval-seal.test.ts +233 -0
  198. package/templates/checkout-agent/packages/agent-core/test/approval.test.ts +117 -0
  199. package/templates/checkout-agent/packages/agent-core/test/attempt-replay.test.ts +265 -0
  200. package/templates/checkout-agent/packages/agent-core/test/bundle.test.ts +85 -0
  201. package/templates/checkout-agent/packages/agent-core/test/clock.test.ts +25 -0
  202. package/templates/checkout-agent/packages/agent-core/test/composition.test.ts +204 -0
  203. package/templates/checkout-agent/packages/agent-core/test/engine.test.ts +596 -0
  204. package/templates/checkout-agent/packages/agent-core/test/escalate.test.ts +42 -0
  205. package/templates/checkout-agent/packages/agent-core/test/fixtures/production-receipt-keys.json +1 -0
  206. package/templates/checkout-agent/packages/agent-core/test/fixtures/staging-receipt-keys.json +18 -0
  207. package/templates/checkout-agent/packages/agent-core/test/fixtures/staging-receipt.json +24 -0
  208. package/templates/checkout-agent/packages/agent-core/test/helpers.ts +142 -0
  209. package/templates/checkout-agent/packages/agent-core/test/mandate-status.test.ts +229 -0
  210. package/templates/checkout-agent/packages/agent-core/test/manifest.test.ts +45 -0
  211. package/templates/checkout-agent/packages/agent-core/test/quote.test.ts +198 -0
  212. package/templates/checkout-agent/packages/agent-core/test/receipt-chain.test.ts +220 -0
  213. package/templates/checkout-agent/packages/agent-core/test/receipt-read-verification.test.ts +197 -0
  214. package/templates/checkout-agent/packages/agent-core/test/receipt-verification.test.ts +316 -0
  215. package/templates/checkout-agent/packages/agent-core/test/receivables.test.ts +416 -0
  216. package/templates/checkout-agent/packages/agent-core/test/secrets.test.ts +28 -0
  217. package/templates/checkout-agent/packages/agent-core/test/state-machine.test.ts +67 -0
  218. package/templates/checkout-agent/packages/agent-core/test/transitions.type-test.ts +59 -0
  219. package/templates/checkout-agent/packages/agent-core/tsconfig.json +10 -0
  220. package/templates/checkout-agent/packages/agent-runtime/README.md +80 -0
  221. package/templates/checkout-agent/packages/agent-runtime/bin.mjs +32 -0
  222. package/templates/checkout-agent/packages/agent-runtime/package.json +23 -0
  223. package/templates/checkout-agent/packages/agent-runtime/src/adversarial.ts +199 -0
  224. package/templates/checkout-agent/packages/agent-runtime/src/agent.ts +68 -0
  225. package/templates/checkout-agent/packages/agent-runtime/src/channels/contact.ts +13 -0
  226. package/templates/checkout-agent/packages/agent-runtime/src/channels/index.ts +72 -0
  227. package/templates/checkout-agent/packages/agent-runtime/src/channels/rules.ts +120 -0
  228. package/templates/checkout-agent/packages/agent-runtime/src/channels/types.ts +173 -0
  229. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/cloud-api.ts +459 -0
  230. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/emulator.ts +216 -0
  231. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/evidence.ts +109 -0
  232. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/index.ts +350 -0
  233. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/open.ts +180 -0
  234. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/present.ts +47 -0
  235. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/run.ts +120 -0
  236. package/templates/checkout-agent/packages/agent-runtime/src/channels/whatsapp/session.ts +127 -0
  237. package/templates/checkout-agent/packages/agent-runtime/src/cli.ts +98 -0
  238. package/templates/checkout-agent/packages/agent-runtime/src/commands/check.ts +15 -0
  239. package/templates/checkout-agent/packages/agent-runtime/src/commands/decide.ts +63 -0
  240. package/templates/checkout-agent/packages/agent-runtime/src/commands/eval.ts +58 -0
  241. package/templates/checkout-agent/packages/agent-runtime/src/commands/inspect.ts +100 -0
  242. package/templates/checkout-agent/packages/agent-runtime/src/commands/poll-whatsapp.ts +367 -0
  243. package/templates/checkout-agent/packages/agent-runtime/src/commands/poll.ts +145 -0
  244. package/templates/checkout-agent/packages/agent-runtime/src/commands/reconcile.ts +42 -0
  245. package/templates/checkout-agent/packages/agent-runtime/src/commands/rerun.ts +86 -0
  246. package/templates/checkout-agent/packages/agent-runtime/src/commands/resume.ts +49 -0
  247. package/templates/checkout-agent/packages/agent-runtime/src/commands/start-whatsapp.ts +134 -0
  248. package/templates/checkout-agent/packages/agent-runtime/src/commands/start.ts +248 -0
  249. package/templates/checkout-agent/packages/agent-runtime/src/commands/verify.ts +330 -0
  250. package/templates/checkout-agent/packages/agent-runtime/src/commands/webhook.ts +40 -0
  251. package/templates/checkout-agent/packages/agent-runtime/src/default-kit.ts +83 -0
  252. package/templates/checkout-agent/packages/agent-runtime/src/index.ts +13 -0
  253. package/templates/checkout-agent/packages/agent-runtime/src/inspect.ts +801 -0
  254. package/templates/checkout-agent/packages/agent-runtime/src/kit.ts +229 -0
  255. package/templates/checkout-agent/packages/agent-runtime/src/poll.ts +105 -0
  256. package/templates/checkout-agent/packages/agent-runtime/src/scenarios.ts +274 -0
  257. package/templates/checkout-agent/packages/agent-runtime/src/setup.ts +239 -0
  258. package/templates/checkout-agent/packages/agent-runtime/src/terminal.ts +263 -0
  259. package/templates/checkout-agent/packages/agent-runtime/src/webhook.ts +131 -0
  260. package/templates/checkout-agent/packages/agent-runtime/test/inspect.test.ts +336 -0
  261. package/templates/checkout-agent/packages/agent-runtime/test/verify-cli.test.ts +329 -0
  262. package/templates/checkout-agent/packages/agent-runtime/test/whatsapp-cloud-api.test.ts +277 -0
  263. package/templates/checkout-agent/packages/agent-runtime/test/whatsapp-evidence.test.ts +94 -0
  264. package/templates/checkout-agent/packages/agent-runtime/test/whatsapp-rules.test.ts +174 -0
  265. package/templates/checkout-agent/packages/agent-runtime/test/whatsapp-session.test.ts +167 -0
  266. package/templates/checkout-agent/packages/agent-runtime/test/whatsapp-status-replies.test.ts +182 -0
  267. package/templates/checkout-agent/packages/agent-runtime/tsconfig.json +9 -0
  268. package/templates/checkout-agent/scripts/whatsapp-emulator.mjs +84 -0
  269. package/templates/checkout-agent/tsconfig.base.json +16 -0
  270. package/templates/checkout-agent/vitest.config.ts +12 -0
  271. package/templates/collections-agent/README.md +6 -1
  272. package/templates/collections-agent/agents/collections-agent/README.md +12 -8
  273. package/templates/collections-agent/agents/collections-agent/channels/whatsapp/README.md +8 -0
  274. package/templates/collections-agent/agents/collections-agent/channels/whatsapp/acordo-1042-retomada.json +10 -0
  275. package/templates/collections-agent/agents/collections-agent/channels/whatsapp/templates.json +27 -1
  276. package/templates/collections-agent/agents/collections-agent/src/kit.ts +2 -0
  277. package/templates/collections-agent/agents/collections-agent/src/modules/bolepix-receivables.ts +12 -2
  278. package/templates/collections-agent/agents/collections-agent/test/ambiguous-charge.test.ts +55 -0
  279. package/templates/collections-agent/agents/collections-agent/test/fixtures/tap-emitir-nova-1042.transcript.jsonl +2 -0
  280. package/templates/collections-agent/agents/collections-agent/test/whatsapp-poll.test.ts +12 -6
  281. package/templates/collections-agent/agents/collections-agent/test/whatsapp-status-replies.test.ts +148 -0
  282. package/templates/collections-agent/agents/collections-agent/test/whatsapp.test.ts +5 -0
  283. package/templates/collections-agent/package.json +1 -0
  284. package/templates/collections-agent/packages/agent-core/README.md +14 -1
  285. package/templates/collections-agent/packages/agent-core/package.json +1 -1
  286. package/templates/collections-agent/packages/agent-core/src/agent.ts +39 -1
  287. package/templates/collections-agent/packages/agent-core/src/api/charge-rail.ts +54 -34
  288. package/templates/collections-agent/packages/agent-core/src/api/client.ts +28 -5
  289. package/templates/collections-agent/packages/agent-core/src/api/mandate-status.ts +28 -12
  290. package/templates/collections-agent/packages/agent-core/src/api/rail.ts +62 -26
  291. package/templates/collections-agent/packages/agent-core/src/api/sandbox-payer.ts +3 -18
  292. package/templates/collections-agent/packages/agent-core/src/approval.ts +14 -2
  293. package/templates/collections-agent/packages/agent-core/src/bundle.ts +35 -3
  294. package/templates/collections-agent/packages/agent-core/src/channels.ts +49 -3
  295. package/templates/collections-agent/packages/agent-core/src/check.ts +25 -2
  296. package/templates/collections-agent/packages/agent-core/src/engine.ts +235 -46
  297. package/templates/collections-agent/packages/agent-core/src/hash.ts +57 -1
  298. package/templates/collections-agent/packages/agent-core/src/index.ts +2 -0
  299. package/templates/collections-agent/packages/agent-core/src/quote.ts +50 -0
  300. package/templates/collections-agent/packages/agent-core/src/rail.ts +89 -4
  301. package/templates/collections-agent/packages/agent-core/src/receipt-chain.ts +270 -0
  302. package/templates/collections-agent/packages/agent-core/src/receipt-verification.ts +194 -18
  303. package/templates/collections-agent/packages/agent-core/src/revocation.ts +1 -1
  304. package/templates/collections-agent/packages/agent-core/src/state-machine.ts +10 -1
  305. package/templates/collections-agent/packages/agent-core/src/stubs/mandate-status.ts +4 -3
  306. package/templates/collections-agent/packages/agent-core/src/stubs/rail.ts +100 -32
  307. package/templates/collections-agent/packages/agent-core/src/tools.ts +17 -6
  308. package/templates/collections-agent/packages/agent-core/src/types.ts +54 -1
  309. package/templates/collections-agent/packages/agent-core/test/approval-seal.test.ts +233 -0
  310. package/templates/collections-agent/packages/agent-core/test/attempt-replay.test.ts +265 -0
  311. package/templates/collections-agent/packages/agent-core/test/composition.test.ts +204 -0
  312. package/templates/collections-agent/packages/agent-core/test/fixtures/production-receipt-keys.json +1 -0
  313. package/templates/collections-agent/packages/agent-core/test/helpers.ts +4 -1
  314. package/templates/collections-agent/packages/agent-core/test/mandate-status.test.ts +85 -9
  315. package/templates/collections-agent/packages/agent-core/test/quote.test.ts +198 -0
  316. package/templates/collections-agent/packages/agent-core/test/receipt-chain.test.ts +220 -0
  317. package/templates/collections-agent/packages/agent-core/test/receipt-read-verification.test.ts +197 -0
  318. package/templates/collections-agent/packages/agent-core/test/receivables.test.ts +103 -3
  319. package/templates/collections-agent/packages/agent-runtime/README.md +12 -0
  320. package/templates/collections-agent/packages/agent-runtime/src/adversarial.ts +32 -2
  321. package/templates/collections-agent/packages/agent-runtime/src/channels/types.ts +53 -4
  322. package/templates/collections-agent/packages/agent-runtime/src/channels/whatsapp/cloud-api.ts +123 -22
  323. package/templates/collections-agent/packages/agent-runtime/src/channels/whatsapp/emulator.ts +30 -20
  324. package/templates/collections-agent/packages/agent-runtime/src/channels/whatsapp/index.ts +146 -21
  325. package/templates/collections-agent/packages/agent-runtime/src/channels/whatsapp/open.ts +40 -3
  326. package/templates/collections-agent/packages/agent-runtime/src/channels/whatsapp/run.ts +8 -1
  327. package/templates/collections-agent/packages/agent-runtime/src/channels/whatsapp/session.ts +16 -2
  328. package/templates/collections-agent/packages/agent-runtime/src/commands/poll-whatsapp.ts +70 -20
  329. package/templates/collections-agent/packages/agent-runtime/src/commands/poll.ts +2 -1
  330. package/templates/collections-agent/packages/agent-runtime/src/commands/resume.ts +8 -2
  331. package/templates/collections-agent/packages/agent-runtime/src/commands/start-whatsapp.ts +3 -0
  332. package/templates/collections-agent/packages/agent-runtime/src/commands/start.ts +6 -3
  333. package/templates/collections-agent/packages/agent-runtime/src/commands/verify.ts +239 -38
  334. package/templates/collections-agent/packages/agent-runtime/src/commands/webhook.ts +3 -2
  335. package/templates/collections-agent/packages/agent-runtime/src/index.ts +1 -0
  336. package/templates/collections-agent/packages/agent-runtime/src/inspect.ts +5 -1
  337. package/templates/collections-agent/packages/agent-runtime/src/kit.ts +25 -2
  338. package/templates/collections-agent/packages/agent-runtime/src/scenarios.ts +8 -2
  339. package/templates/collections-agent/packages/agent-runtime/src/setup.ts +13 -3
  340. package/templates/collections-agent/packages/agent-runtime/src/terminal.ts +127 -18
  341. package/templates/collections-agent/packages/agent-runtime/test/verify-cli.test.ts +211 -9
  342. package/templates/collections-agent/packages/agent-runtime/test/whatsapp-cloud-api.test.ts +45 -0
  343. package/templates/collections-agent/packages/agent-runtime/test/whatsapp-session.test.ts +32 -0
  344. package/templates/collections-agent/packages/agent-runtime/test/whatsapp-status-replies.test.ts +182 -0
  345. package/templates/collections-agent/scripts/whatsapp-emulator.mjs +84 -0
  346. package/templates/hello-agent/README.md +1 -1
  347. package/templates/hello-agent/packages/agent-core/README.md +14 -1
  348. package/templates/hello-agent/packages/agent-core/package.json +1 -1
  349. package/templates/hello-agent/packages/agent-core/src/agent.ts +39 -1
  350. package/templates/hello-agent/packages/agent-core/src/api/charge-rail.ts +54 -34
  351. package/templates/hello-agent/packages/agent-core/src/api/client.ts +28 -5
  352. package/templates/hello-agent/packages/agent-core/src/api/mandate-status.ts +28 -12
  353. package/templates/hello-agent/packages/agent-core/src/api/rail.ts +62 -26
  354. package/templates/hello-agent/packages/agent-core/src/api/sandbox-payer.ts +3 -18
  355. package/templates/hello-agent/packages/agent-core/src/approval.ts +14 -2
  356. package/templates/hello-agent/packages/agent-core/src/bundle.ts +35 -3
  357. package/templates/hello-agent/packages/agent-core/src/channels.ts +49 -3
  358. package/templates/hello-agent/packages/agent-core/src/check.ts +25 -2
  359. package/templates/hello-agent/packages/agent-core/src/engine.ts +235 -46
  360. package/templates/hello-agent/packages/agent-core/src/hash.ts +57 -1
  361. package/templates/hello-agent/packages/agent-core/src/index.ts +2 -0
  362. package/templates/hello-agent/packages/agent-core/src/quote.ts +50 -0
  363. package/templates/hello-agent/packages/agent-core/src/rail.ts +89 -4
  364. package/templates/hello-agent/packages/agent-core/src/receipt-chain.ts +270 -0
  365. package/templates/hello-agent/packages/agent-core/src/receipt-verification.ts +194 -18
  366. package/templates/hello-agent/packages/agent-core/src/revocation.ts +1 -1
  367. package/templates/hello-agent/packages/agent-core/src/state-machine.ts +10 -1
  368. package/templates/hello-agent/packages/agent-core/src/stubs/mandate-status.ts +4 -3
  369. package/templates/hello-agent/packages/agent-core/src/stubs/rail.ts +100 -32
  370. package/templates/hello-agent/packages/agent-core/src/tools.ts +17 -6
  371. package/templates/hello-agent/packages/agent-core/src/types.ts +54 -1
  372. package/templates/hello-agent/packages/agent-core/test/approval-seal.test.ts +233 -0
  373. package/templates/hello-agent/packages/agent-core/test/attempt-replay.test.ts +265 -0
  374. package/templates/hello-agent/packages/agent-core/test/composition.test.ts +204 -0
  375. package/templates/hello-agent/packages/agent-core/test/fixtures/production-receipt-keys.json +1 -0
  376. package/templates/hello-agent/packages/agent-core/test/helpers.ts +4 -1
  377. package/templates/hello-agent/packages/agent-core/test/mandate-status.test.ts +85 -9
  378. package/templates/hello-agent/packages/agent-core/test/quote.test.ts +198 -0
  379. package/templates/hello-agent/packages/agent-core/test/receipt-chain.test.ts +220 -0
  380. package/templates/hello-agent/packages/agent-core/test/receipt-read-verification.test.ts +197 -0
  381. package/templates/hello-agent/packages/agent-core/test/receivables.test.ts +103 -3
  382. package/templates/hello-agent/packages/agent-runtime/README.md +12 -0
  383. package/templates/hello-agent/packages/agent-runtime/src/adversarial.ts +32 -2
  384. package/templates/hello-agent/packages/agent-runtime/src/channels/types.ts +53 -4
  385. package/templates/hello-agent/packages/agent-runtime/src/channels/whatsapp/cloud-api.ts +123 -22
  386. package/templates/hello-agent/packages/agent-runtime/src/channels/whatsapp/emulator.ts +30 -20
  387. package/templates/hello-agent/packages/agent-runtime/src/channels/whatsapp/index.ts +146 -21
  388. package/templates/hello-agent/packages/agent-runtime/src/channels/whatsapp/open.ts +40 -3
  389. package/templates/hello-agent/packages/agent-runtime/src/channels/whatsapp/run.ts +8 -1
  390. package/templates/hello-agent/packages/agent-runtime/src/channels/whatsapp/session.ts +16 -2
  391. package/templates/hello-agent/packages/agent-runtime/src/commands/poll-whatsapp.ts +70 -20
  392. package/templates/hello-agent/packages/agent-runtime/src/commands/poll.ts +2 -1
  393. package/templates/hello-agent/packages/agent-runtime/src/commands/resume.ts +8 -2
  394. package/templates/hello-agent/packages/agent-runtime/src/commands/start-whatsapp.ts +3 -0
  395. package/templates/hello-agent/packages/agent-runtime/src/commands/start.ts +6 -3
  396. package/templates/hello-agent/packages/agent-runtime/src/commands/verify.ts +239 -38
  397. package/templates/hello-agent/packages/agent-runtime/src/commands/webhook.ts +3 -2
  398. package/templates/hello-agent/packages/agent-runtime/src/index.ts +1 -0
  399. package/templates/hello-agent/packages/agent-runtime/src/inspect.ts +5 -1
  400. package/templates/hello-agent/packages/agent-runtime/src/kit.ts +25 -2
  401. package/templates/hello-agent/packages/agent-runtime/src/scenarios.ts +8 -2
  402. package/templates/hello-agent/packages/agent-runtime/src/setup.ts +13 -3
  403. package/templates/hello-agent/packages/agent-runtime/src/terminal.ts +127 -18
  404. package/templates/hello-agent/packages/agent-runtime/test/verify-cli.test.ts +211 -9
  405. package/templates/hello-agent/packages/agent-runtime/test/whatsapp-cloud-api.test.ts +45 -0
  406. package/templates/hello-agent/packages/agent-runtime/test/whatsapp-session.test.ts +32 -0
  407. package/templates/hello-agent/packages/agent-runtime/test/whatsapp-status-replies.test.ts +182 -0
  408. package/templates/kits.lock.json +29 -6
  409. package/templates/supplier-payments-agent/README.md +1 -1
  410. package/templates/supplier-payments-agent/agents/supplier-payments-agent/AGENTS.md +1 -1
  411. package/templates/supplier-payments-agent/agents/supplier-payments-agent/CLAUDE.md +1 -1
  412. package/templates/supplier-payments-agent/agents/supplier-payments-agent/README.md +11 -9
  413. package/templates/supplier-payments-agent/agents/supplier-payments-agent/src/kit.ts +1 -1
  414. package/templates/supplier-payments-agent/agents/supplier-payments-agent/src/modules/batch-payout.ts +67 -20
  415. package/templates/supplier-payments-agent/agents/supplier-payments-agent/test/batch.test.ts +504 -5
  416. package/templates/supplier-payments-agent/packages/agent-core/README.md +14 -1
  417. package/templates/supplier-payments-agent/packages/agent-core/package.json +1 -1
  418. package/templates/supplier-payments-agent/packages/agent-core/src/agent.ts +39 -1
  419. package/templates/supplier-payments-agent/packages/agent-core/src/api/charge-rail.ts +54 -34
  420. package/templates/supplier-payments-agent/packages/agent-core/src/api/client.ts +28 -5
  421. package/templates/supplier-payments-agent/packages/agent-core/src/api/mandate-status.ts +28 -12
  422. package/templates/supplier-payments-agent/packages/agent-core/src/api/rail.ts +62 -26
  423. package/templates/supplier-payments-agent/packages/agent-core/src/api/sandbox-payer.ts +3 -18
  424. package/templates/supplier-payments-agent/packages/agent-core/src/approval.ts +14 -2
  425. package/templates/supplier-payments-agent/packages/agent-core/src/bundle.ts +35 -3
  426. package/templates/supplier-payments-agent/packages/agent-core/src/channels.ts +49 -3
  427. package/templates/supplier-payments-agent/packages/agent-core/src/check.ts +25 -2
  428. package/templates/supplier-payments-agent/packages/agent-core/src/engine.ts +235 -46
  429. package/templates/supplier-payments-agent/packages/agent-core/src/hash.ts +57 -1
  430. package/templates/supplier-payments-agent/packages/agent-core/src/index.ts +2 -0
  431. package/templates/supplier-payments-agent/packages/agent-core/src/quote.ts +50 -0
  432. package/templates/supplier-payments-agent/packages/agent-core/src/rail.ts +89 -4
  433. package/templates/supplier-payments-agent/packages/agent-core/src/receipt-chain.ts +270 -0
  434. package/templates/supplier-payments-agent/packages/agent-core/src/receipt-verification.ts +194 -18
  435. package/templates/supplier-payments-agent/packages/agent-core/src/revocation.ts +1 -1
  436. package/templates/supplier-payments-agent/packages/agent-core/src/state-machine.ts +10 -1
  437. package/templates/supplier-payments-agent/packages/agent-core/src/stubs/mandate-status.ts +4 -3
  438. package/templates/supplier-payments-agent/packages/agent-core/src/stubs/rail.ts +100 -32
  439. package/templates/supplier-payments-agent/packages/agent-core/src/tools.ts +17 -6
  440. package/templates/supplier-payments-agent/packages/agent-core/src/types.ts +54 -1
  441. package/templates/supplier-payments-agent/packages/agent-core/test/approval-seal.test.ts +233 -0
  442. package/templates/supplier-payments-agent/packages/agent-core/test/attempt-replay.test.ts +265 -0
  443. package/templates/supplier-payments-agent/packages/agent-core/test/composition.test.ts +204 -0
  444. package/templates/supplier-payments-agent/packages/agent-core/test/fixtures/production-receipt-keys.json +1 -0
  445. package/templates/supplier-payments-agent/packages/agent-core/test/helpers.ts +4 -1
  446. package/templates/supplier-payments-agent/packages/agent-core/test/mandate-status.test.ts +85 -9
  447. package/templates/supplier-payments-agent/packages/agent-core/test/quote.test.ts +198 -0
  448. package/templates/supplier-payments-agent/packages/agent-core/test/receipt-chain.test.ts +220 -0
  449. package/templates/supplier-payments-agent/packages/agent-core/test/receipt-read-verification.test.ts +197 -0
  450. package/templates/supplier-payments-agent/packages/agent-core/test/receivables.test.ts +103 -3
  451. package/templates/supplier-payments-agent/packages/agent-runtime/README.md +12 -0
  452. package/templates/supplier-payments-agent/packages/agent-runtime/src/adversarial.ts +32 -2
  453. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/types.ts +53 -4
  454. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/whatsapp/cloud-api.ts +123 -22
  455. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/whatsapp/emulator.ts +30 -20
  456. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/whatsapp/index.ts +146 -21
  457. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/whatsapp/open.ts +40 -3
  458. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/whatsapp/run.ts +8 -1
  459. package/templates/supplier-payments-agent/packages/agent-runtime/src/channels/whatsapp/session.ts +16 -2
  460. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/poll-whatsapp.ts +70 -20
  461. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/poll.ts +2 -1
  462. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/resume.ts +8 -2
  463. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/start-whatsapp.ts +3 -0
  464. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/start.ts +6 -3
  465. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/verify.ts +239 -38
  466. package/templates/supplier-payments-agent/packages/agent-runtime/src/commands/webhook.ts +3 -2
  467. package/templates/supplier-payments-agent/packages/agent-runtime/src/index.ts +1 -0
  468. package/templates/supplier-payments-agent/packages/agent-runtime/src/inspect.ts +5 -1
  469. package/templates/supplier-payments-agent/packages/agent-runtime/src/kit.ts +25 -2
  470. package/templates/supplier-payments-agent/packages/agent-runtime/src/scenarios.ts +8 -2
  471. package/templates/supplier-payments-agent/packages/agent-runtime/src/setup.ts +13 -3
  472. package/templates/supplier-payments-agent/packages/agent-runtime/src/terminal.ts +127 -18
  473. package/templates/supplier-payments-agent/packages/agent-runtime/test/verify-cli.test.ts +211 -9
  474. package/templates/supplier-payments-agent/packages/agent-runtime/test/whatsapp-cloud-api.test.ts +45 -0
  475. package/templates/supplier-payments-agent/packages/agent-runtime/test/whatsapp-session.test.ts +32 -0
  476. package/templates/supplier-payments-agent/packages/agent-runtime/test/whatsapp-status-replies.test.ts +182 -0
  477. package/templates/bills-agent/packages/agent-runtime/test/whatsapp-emulator.integration.test.ts +0 -204
  478. package/templates/collections-agent/packages/agent-runtime/test/whatsapp-emulator.integration.test.ts +0 -204
  479. package/templates/hello-agent/packages/agent-runtime/test/whatsapp-emulator.integration.test.ts +0 -204
  480. package/templates/supplier-payments-agent/packages/agent-runtime/test/whatsapp-emulator.integration.test.ts +0 -204
@@ -0,0 +1,416 @@
1
+ /**
2
+ * The receivable side of the core (collections-agent): a charge is ISSUED,
3
+ * not settled, when the rail accepts it; the execution stays `executing`
4
+ * until the payer acts, and closes from a lookup (the poll) or from a
5
+ * `commerce.charge.*` event (the webhook). Never twice, never on prose.
6
+ */
7
+ import { mkdtempSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { describe, expect, it } from "vitest";
11
+ import { CodeSparChargeRail, outcomeOf, type ChargeView } from "../src/api/charge-rail.js";
12
+ import { createCodeSparClient } from "../src/api/client.js";
13
+ import { hmacSigner } from "../src/approval.js";
14
+ import { ProofBundle } from "../src/bundle.js";
15
+ import { ExecutionEngine, type EngineDeps, type PolicyExtension } from "../src/engine.js";
16
+ import type { PaymentRail, RailPayment } from "../src/rail.js";
17
+ import { itemsHash } from "../src/hash.js";
18
+ import { StateStore } from "../src/state/store.js";
19
+ import { LocalMandateStatusStub } from "../src/stubs/mandate-status.js";
20
+ import { StubChargeRail, type StubChargeRailOptions } from "../src/stubs/charge-rail.js";
21
+ import { testGuardrails, testManifest, testMandate } from "./helpers.js";
22
+
23
+ const DEBTOR = "11144477735";
24
+ const OTHER = "22233344450";
25
+
26
+ function receivables(options: { mode?: "human" | "mandate"; rail?: StubChargeRailOptions; policyExtension?: PolicyExtension; dir?: string; dispatchTo?: PaymentRail } = {}) {
27
+ const dir = options.dir ?? mkdtempSync(join(tmpdir(), "agent-core-recv-"));
28
+ let now = new Date("2026-09-23T18:00:00Z");
29
+ const clock = () => now;
30
+ const store = new StateStore(join(dir, "state.db"));
31
+ const gate = new LocalMandateStatusStub(store, clock);
32
+ const rail = new StubChargeRail(store, { clock, ...(options.rail ?? {}) });
33
+ const bundle = new ProofBundle(join(dir, "runs"), "run_recv");
34
+ const mode = options.mode ?? "mandate";
35
+ const deps: EngineDeps = {
36
+ store,
37
+ rail: options.dispatchTo ?? rail,
38
+ status: gate,
39
+ signer: hmacSigner("test", Buffer.alloc(32, 2)),
40
+ manifest: testManifest({ name: "collections-agent", escalate_above: {}, maturity: { "bolepix-receivables": "sandbox" } }),
41
+ guardrails: testGuardrails({ approval: mode, escalate_above: {} }),
42
+ mandate: testMandate({
43
+ agent_id: "collections-agent",
44
+ purpose: "cobranca",
45
+ merchant_pin_kind: "document",
46
+ merchant_allowlist: [DEBTOR, OTHER],
47
+ beneficiaries: [{ alias: "acordo-1", name: "Joana Devedora", payee: DEBTOR }],
48
+ }),
49
+ bundle,
50
+ mode,
51
+ runId: "run_recv",
52
+ onBehalfOf: "merchant_demo",
53
+ clock,
54
+ policyExtension: options.policyExtension,
55
+ };
56
+ const engine = new ExecutionEngine(deps);
57
+ return { dir, store, rail, bundle, engine, setNow: (d: Date) => (now = d) };
58
+ }
59
+
60
+ describe("a receivable is accepted, then settled by the payer", () => {
61
+ it("execute leaves the execution executing (awaiting_settlement) with the instrument; two looks later it is settled with the charge as receipt", async () => {
62
+ const h = receivables();
63
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 108000, due_date: "2026-09-30", description: "acordo 1042, a vista" }] });
64
+ if (!d.ok) throw new Error("refused");
65
+ expect(d.execution.state).toBe("approved");
66
+ expect(d.execution.items[0]?.due_date).toBe("2026-09-30");
67
+
68
+ const issued = await h.engine.execute(d.execution.id);
69
+ expect(issued.state).toBe("executing");
70
+ expect(issued.reason).toBe("awaiting_settlement");
71
+ expect(issued.outcomes[0]).toMatchObject({ status: "accepted", instrument: { payable: false, status: "PROCESSING" } });
72
+ expect(h.store.getOutbox(issued.idempotency_key)!.status).toBe("sent");
73
+
74
+ const registered = await h.engine.reconcile(issued.id);
75
+ expect(registered.state).toBe("executing");
76
+ expect(registered.outcomes[0]?.instrument).toMatchObject({ payable: true, status: "PENDING" });
77
+ expect(registered.outcomes[0]?.instrument?.pix_copy_paste).toContain("br.gov.bcb.pix");
78
+
79
+ const paid = await h.engine.reconcile(issued.id);
80
+ expect(paid.state).toBe("settled");
81
+ expect(paid.history.map((t) => t.to)).toEqual(["approved", "executing", "settled"]);
82
+ expect(paid.outcomes[0]).toMatchObject({ status: "settled", receipt_id: paid.outcomes[0]!.transaction_id });
83
+ expect(h.store.getOutbox(issued.idempotency_key)!.status).toBe("done");
84
+ expect(h.bundle.listReceipts()).toHaveLength(1);
85
+ const events = h.bundle.readEvents();
86
+ expect(events.filter((e) => e["type"] === "commerce.charge.paid")).toHaveLength(1);
87
+ expect(events.filter((e) => e["type"] === "charge.instrument").map((e) => (e["payload"] as { payable: boolean }).payable)).toEqual([false, true]);
88
+ // A third look changes nothing and issues nothing.
89
+ expect((await h.engine.reconcile(issued.id)).state).toBe("settled");
90
+ expect(h.rail.issueCount).toBe(1);
91
+ });
92
+
93
+ it("a receivable nobody pays closes failed with charge_expired, never settled", async () => {
94
+ const h = receivables({ rail: { payer: "expires" } });
95
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 50000, due_date: "2026-09-25" }] });
96
+ if (!d.ok) throw new Error("refused");
97
+ const issued = await h.engine.execute(d.execution.id);
98
+ await h.engine.reconcile(issued.id);
99
+ const closed = await h.engine.reconcile(issued.id);
100
+ expect(closed.state).toBe("failed");
101
+ expect(closed.reason).toBe("charge_expired");
102
+ expect(h.bundle.listReceipts()).toHaveLength(0);
103
+ expect(h.store.getOutbox(issued.idempotency_key)!.status).toBe("failed");
104
+ });
105
+
106
+ it("the poll logs an observed state once, however many times it sees it", async () => {
107
+ const h = receivables({ rail: { payer: "never" } });
108
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 50000, due_date: "2026-09-25" }] });
109
+ if (!d.ok) throw new Error("refused");
110
+ const issued = await h.engine.execute(d.execution.id);
111
+ for (let i = 0; i < 5; i += 1) await h.engine.reconcile(issued.id);
112
+ const events = h.store.listEvents({ execution_id: issued.id });
113
+ // Five looks, one observed state (PENDING, payable): one line. The instrument log names the two states the charge went through.
114
+ expect(events.filter((e) => e.type === "rail.reconcile")).toHaveLength(1);
115
+ expect(events.filter((e) => e.type === "charge.instrument")).toHaveLength(2);
116
+ expect(events.filter((e) => e.type === "execution.awaiting_settlement")).toHaveLength(1);
117
+ });
118
+
119
+ it("killed after the issuance and resumed: one charge, one settlement", async () => {
120
+ const h = receivables();
121
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 50000, due_date: "2026-09-25" }] });
122
+ if (!d.ok) throw new Error("refused");
123
+ let died = false;
124
+ const flaky = receivables({ dir: h.dir, rail: { afterDispatch: () => { died = true; throw new Error("killed"); } } });
125
+ await expect(flaky.engine.execute(d.execution.id)).rejects.toThrow("killed");
126
+ expect(died).toBe(true);
127
+ // The row says executing and the outbox says sent: resume reconciles, never re-issues.
128
+ const again = receivables({ dir: h.dir });
129
+ const stuck = again.store.getExecution(d.execution.id)!;
130
+ expect(stuck.state).toBe("executing");
131
+ const first = await again.engine.resumePending(stuck.id);
132
+ expect(first.state).toBe("executing");
133
+ expect(first.outcomes[0]?.status).toBe("accepted");
134
+ const settled = await again.engine.reconcile(stuck.id);
135
+ expect(settled.state).toBe("settled");
136
+ expect(again.rail.issueCount).toBe(0);
137
+ expect((again.store as unknown as { db: { prepare(sql: string): { get(): { n: number } } } }).db.prepare("SELECT COUNT(*) AS n FROM stub_rail_attempts").get().n).toBe(1);
138
+ });
139
+
140
+ it("an instalment agreement is N receivables; the execution settles when every parcel is paid", async () => {
141
+ const h = receivables();
142
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 40000, due_date: "2026-09-30" }, { payee: "acordo-1", amount: 40000, due_date: "2026-10-30" }, { payee: "acordo-1", amount: 40000, due_date: "2026-11-30" }] });
143
+ if (!d.ok) throw new Error("refused");
144
+ expect(d.execution.total).toBe(120000);
145
+ const issued = await h.engine.execute(d.execution.id);
146
+ expect(issued.outcomes.map((o) => o.status)).toEqual(["accepted", "accepted", "accepted"]);
147
+ expect(h.rail.issueCount).toBe(3);
148
+ const a2 = issued.outcomes[2]!.attempt_id;
149
+ h.rail.decide(a2, "never");
150
+ await h.engine.reconcile(issued.id);
151
+ const partly = await h.engine.reconcile(issued.id);
152
+ expect(partly.state).toBe("executing");
153
+ expect(partly.outcomes.map((o) => o.status)).toEqual(["settled", "settled", "accepted"]);
154
+ h.rail.decide(a2, "pays");
155
+ const done = await h.engine.reconcile(issued.id);
156
+ expect(done.state).toBe("settled");
157
+ expect(h.bundle.listReceipts()).toHaveLength(3);
158
+ });
159
+ });
160
+
161
+ describe("the webhook path: commerce.charge.* by attempt id or by the rail's charge id", () => {
162
+ it("paid twice settles once; paid before created is fine; expired after paid moves nothing", async () => {
163
+ const h = receivables({ rail: { payer: "never" } });
164
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 50000, due_date: "2026-09-25" }] });
165
+ if (!d.ok) throw new Error("refused");
166
+ const issued = await h.engine.execute(d.execution.id);
167
+ const chargeId = issued.outcomes[0]!.transaction_id!;
168
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_paid_1", type: "commerce.charge.paid", transaction_id: chargeId })).toEqual({ applied: true, reason: "settled" });
169
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_paid_1", type: "commerce.charge.paid", transaction_id: chargeId })).toEqual({ applied: false, reason: "duplicate event id" });
170
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_created_late", type: "commerce.charge.created", transaction_id: chargeId })).toMatchObject({ applied: false });
171
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_paid_2", type: "commerce.charge.paid", transaction_id: chargeId })).toMatchObject({ applied: false, reason: "execution already settled" });
172
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_expired_late", type: "commerce.charge.expired", transaction_id: chargeId })).toMatchObject({ applied: false, reason: "execution already settled" });
173
+ const settled = h.store.getExecution(issued.id)!;
174
+ expect(settled.state).toBe("settled");
175
+ expect(settled.outcomes[0]).toMatchObject({ status: "settled", transaction_id: chargeId, receipt_id: chargeId });
176
+ expect(h.store.listEvents({ execution_id: issued.id }).filter((e) => e.type === "execution.transition" && (e.payload as { to: string }).to === "settled")).toHaveLength(1);
177
+ // The settlement came by event, so the bundle holds no receipt yet; collectReceipts fetches it once.
178
+ expect(h.bundle.listReceipts()).toHaveLength(0);
179
+ expect(await h.engine.collectReceipts(issued.id)).toEqual([chargeId]);
180
+ expect(await h.engine.collectReceipts(issued.id)).toEqual([]);
181
+ expect(h.bundle.listReceipts()).toHaveLength(1);
182
+ });
183
+
184
+ it("expired by event closes failed with charge_expired; a later paid for the same charge moves nothing", async () => {
185
+ const h = receivables({ rail: { payer: "never" } });
186
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 50000, due_date: "2026-09-25" }] });
187
+ if (!d.ok) throw new Error("refused");
188
+ const issued = await h.engine.execute(d.execution.id);
189
+ const attempt = issued.outcomes[0]!.attempt_id;
190
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_exp", type: "commerce.charge.expired", attempt_id: attempt })).toEqual({ applied: true, reason: "failed" });
191
+ expect(h.store.getExecution(issued.id)!.reason).toBe("charge_expired");
192
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_paid_after", type: "commerce.charge.paid", attempt_id: attempt })).toMatchObject({ applied: false });
193
+ });
194
+
195
+ it("an event naming a charge this kit never issued is not applied", () => {
196
+ const h = receivables();
197
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_x", type: "commerce.charge.paid", transaction_id: "chg_someone_elses" })).toEqual({ applied: false, reason: "unknown attempt" });
198
+ expect(h.engine.ingestExternalEvent({ event_id: "evt_y", type: "commerce.charge.paid" })).toMatchObject({ applied: false });
199
+ });
200
+ });
201
+
202
+ describe("the kit's envelope runs at every gate, and only tightens", () => {
203
+ const envelope: PolicyExtension = (execution) => {
204
+ const principal = 120000;
205
+ if (execution.total < principal * 0.85) return { reason: "outside_envelope", detail: `total ${execution.total} is below the floor of ${principal * 0.85} (15% off ${principal})` };
206
+ return undefined;
207
+ };
208
+
209
+ it("a proposal below the discount floor is denied at draft, even in human mode", async () => {
210
+ const h = receivables({ mode: "human", policyExtension: envelope });
211
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 1000, due_date: "2026-09-30" }] });
212
+ if (!d.ok) throw new Error("refused");
213
+ expect(d.execution.state).toBe("denied");
214
+ expect(d.execution.reason).toBe("outside_envelope");
215
+ });
216
+
217
+ it("a debtor without an open agreement is not a payee: denied in mandate, blocked for the human, never approvable", async () => {
218
+ const h = receivables({ mode: "human", policyExtension: envelope });
219
+ const d = await h.engine.draft({ items: [{ payee: "99988877766", amount: 120000, due_date: "2026-09-30" }] });
220
+ if (!d.ok) throw new Error("refused");
221
+ expect(d.execution.state).toBe("awaiting_approval");
222
+ expect(d.execution.blocking_reasons).toEqual(["beneficiary_not_allowed"]);
223
+ expect(h.engine.approve(d.execution.id, { id: "usr_operator", channel: "terminal" }).state).toBe("denied");
224
+ });
225
+
226
+ it("the due date is part of the items_hash: moving it after approval is another charge", () => {
227
+ const a = itemsHash([{ beneficiary: "x", payee: DEBTOR, amount: 100, currency: "BRL", due_date: "2026-09-30" }]);
228
+ const b = itemsHash([{ beneficiary: "x", payee: DEBTOR, amount: 100, currency: "BRL", due_date: "2026-10-30" }]);
229
+ const c = itemsHash([{ beneficiary: "x", payee: DEBTOR, amount: 100, currency: "BRL" }]);
230
+ expect(a).not.toBe(b);
231
+ expect(a).not.toBe(c);
232
+ });
233
+ });
234
+
235
+ describe("outcomeOf: the API's charge view, mapped by fields and never by prose", () => {
236
+ const base: ChargeView = {
237
+ id: "chg_1",
238
+ status: "PENDING",
239
+ local_status: "pending",
240
+ status_conflict: false,
241
+ method: "boleto",
242
+ currency: "BRL",
243
+ amount: 1080.5,
244
+ amount_minor: 108050,
245
+ due_date: "2026-09-30",
246
+ payable: true,
247
+ boleto_bar_code: "1".repeat(44),
248
+ boleto_bank_line: "2".repeat(47),
249
+ pix_copy_paste: "000201...",
250
+ credit_correlation_armed: true,
251
+ payment_in_flight: false,
252
+ settlement: null,
253
+ issuance_unconfirmed: false,
254
+ };
255
+ it("maps the five states", () => {
256
+ expect(outcomeOf(base)).toMatchObject({ status: "accepted", transaction_id: "chg_1", instrument: { payable: true, status: "PENDING", pix_copy_paste: "000201..." } });
257
+ expect(outcomeOf({ ...base, status: "PROCESSING", payable: false, pix_copy_paste: null })).toMatchObject({ status: "accepted", instrument: { payable: false } });
258
+ expect(outcomeOf({ ...base, local_status: "settled", status: "CONFIRMED", settlement: "confirmed" })).toMatchObject({ status: "settled", transaction_id: "chg_1", receipt_id: "chg_1", money_moved: false });
259
+ expect(outcomeOf({ ...base, local_status: "expired", status: "CANCELLED" })).toMatchObject({ status: "failed", code: "charge_expired" });
260
+ expect(outcomeOf({ ...base, status: "EXPIRED" })).toMatchObject({ status: "failed", code: "charge_expired" });
261
+ expect(outcomeOf({ ...base, status: "CANCELLED" })).toMatchObject({ status: "failed", code: "charge_cancelled" });
262
+ expect(outcomeOf({ ...base, id: null, issuance_unconfirmed: true })).toEqual({ status: "in_flight" });
263
+ });
264
+ it("a payment notified and not yet credited is still accepted: nothing settles on a notification", () => {
265
+ expect(outcomeOf({ ...base, payment_in_flight: true, settlement: "pending" })).toMatchObject({ status: "accepted" });
266
+ });
267
+ });
268
+
269
+ describe("CodeSparChargeRail: what crosses the wire on a create", () => {
270
+ it("sends consumer_id, method boleto, due_date, the attempt id as idempotency_key and the amount in major units; refuses without a consumer", async () => {
271
+ const { CodeSparChargeRail } = await import("../src/api/charge-rail.js");
272
+ const calls: Array<{ path: string; body: Record<string, unknown> }> = [];
273
+ const api = {
274
+ post: async (path: string, opts: { body: Record<string, unknown> }) => {
275
+ calls.push({ path, body: opts.body });
276
+ return { id: "chg_wire_1", status: "PROCESSING", local_status: "pending", status_conflict: false, method: "boleto", currency: "BRL", amount: 1080, amount_minor: 108000, due_date: "2026-09-30", payable: false, boleto_bar_code: null, boleto_bank_line: null, pix_copy_paste: null, credit_correlation_armed: false, payment_in_flight: false, settlement: null, issuance_unconfirmed: false };
277
+ },
278
+ get: async () => { throw new Error("not called"); },
279
+ };
280
+ const rail = new CodeSparChargeRail(api as never);
281
+ const base = { attempt_id: "att_x_0", mandate_id: "pol_1", amount_minor: 108000, currency: "BRL", payee: DEBTOR, beneficiary: "Joana Ribeiro", purpose: "cobranca", agent_id: "collections-agent", description: "Acordo #1042 - parcela 1/1", due_date: "2026-09-30", actor: { type: "agent" as const, agent: "collections-agent@0.1.0", on_behalf_of: "merchant_demo_loja" } };
282
+ expect(await rail.pay(base)).toMatchObject({ status: "failed", code: "consumer_id_required" });
283
+ expect(calls).toHaveLength(0);
284
+ const out = await rail.pay({ ...base, consumer_id: "merchant_demo_loja" });
285
+ expect(out).toMatchObject({ status: "accepted", transaction_id: "chg_wire_1", instrument: { payable: false, status: "PROCESSING" } });
286
+ expect(calls[0]).toEqual({ path: "/v1/charges", body: { consumer_id: "merchant_demo_loja", amount: 1080, currency: "BRL", method: "boleto", description: "Acordo #1042 - parcela 1/1", buyer: { name: "Joana Ribeiro", document: DEBTOR }, due_date: "2026-09-30", idempotency_key: "att_x_0" } });
287
+ });
288
+ });
289
+
290
+ describe("paySandboxCharge: the SDK's typed call to the payer route", () => {
291
+ it("posts to /v1/test/charges/{id}/pay with the key, the project header and the amount; refuses a live key before any request", async () => {
292
+ const { paySandboxCharge } = await import("../src/api/sandbox-payer.js");
293
+ const seen: Array<{ url: string; init: RequestInit }> = [];
294
+ const realFetch = globalThis.fetch;
295
+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
296
+ seen.push({ url: String(url), init: init ?? {} });
297
+ return new Response(JSON.stringify({ charge_id: "chg_1", status: "paid", local_status: "settled", simulated: true, settled_against: "sandbox_fixture", money_moved: false, quoted_minor: 1000, paid_minor: 1000, payment: "full", idempotent_replay: false }), { status: 200, headers: { "content-type": "application/json" } });
298
+ }) as typeof fetch;
299
+ try {
300
+ const live = await paySandboxCharge({ apiKey: ["csk", "live", "0000000000"].join("_") }, "chg_1").catch((e: Error) => e);
301
+ expect(live).toBeInstanceOf(Error);
302
+ expect(seen).toHaveLength(0);
303
+ const out = await paySandboxCharge({ apiKey: "csk_test_unit_0000", baseUrl: "https://api.example.test/", projectId: "prj_1" }, "chg_1", 1000);
304
+ expect(out).toMatchObject({ ok: true, state: { charge_id: "chg_1", status: "paid", simulated: true, money_moved: false } });
305
+ expect(seen[0]?.url).toBe("https://api.example.test/v1/test/charges/chg_1/pay");
306
+ const headers = new Headers(seen[0]?.init.headers);
307
+ expect(headers.get("authorization")).toBe("Bearer csk_test_unit_0000");
308
+ expect(headers.get("x-codespar-project")).toBe("prj_1");
309
+ expect(headers.get("content-type")).toBe("application/json");
310
+ expect(seen[0]?.init.body).toBe(JSON.stringify({ amount_minor: 1000 }));
311
+ const bare = await paySandboxCharge({ apiKey: "csk_test_unit_0000", baseUrl: "https://api.example.test/", projectId: "prj_1" }, "chg_1");
312
+ expect(bare).toMatchObject({ ok: true });
313
+ expect(seen[1]?.init.body).toBe("{}");
314
+ } finally {
315
+ globalThis.fetch = realFetch;
316
+ }
317
+ });
318
+ });
319
+
320
+ describe("CodeSparChargeRail.read: a 409 is branched on its code, never on the status alone", () => {
321
+ const VIEW = { id: "chg_409", status: "PROCESSING", local_status: "pending", status_conflict: false, method: "boleto", currency: "BRL", amount: 1080, amount_minor: 108000, due_date: "2026-09-30", payable: false, boleto_bar_code: null, boleto_bank_line: null, pix_copy_paste: null, credit_correlation_armed: false, payment_in_flight: false, settlement: null, issuance_unconfirmed: false };
322
+
323
+ /** The real client over a stubbed fetch: the create answers `VIEW`, every read answers `readAnswer`. */
324
+ function wired(readAnswer: { status: number; body?: unknown }) {
325
+ const seen: Array<{ method: string; path: string }> = [];
326
+ const fetchStub = (async (url: string | URL | Request, init?: RequestInit) => {
327
+ const { pathname } = new URL(String(url));
328
+ const method = init?.method ?? "GET";
329
+ seen.push({ method, path: pathname });
330
+ const answer = method === "POST" ? { status: 200, body: VIEW } : readAnswer;
331
+ return new Response(answer.body === undefined ? "" : JSON.stringify(answer.body), { status: answer.status, headers: { "content-type": "application/json" } });
332
+ }) as typeof fetch;
333
+ return { seen, fetchStub, rail: new CodeSparChargeRail(createCodeSparClient({ apiKey: "csk_test_unit_0000", baseUrl: "https://api.example.test/" })) };
334
+ }
335
+
336
+ async function withFetch<T>(fetchStub: typeof fetch, run: () => Promise<T>): Promise<T> {
337
+ const realFetch = globalThis.fetch;
338
+ globalThis.fetch = fetchStub;
339
+ try {
340
+ return await run();
341
+ } finally {
342
+ globalThis.fetch = realFetch;
343
+ }
344
+ }
345
+
346
+ const payment: RailPayment = { attempt_id: "att_409_0", mandate_id: "pol_1", amount_minor: 108000, currency: "BRL", payee: DEBTOR, purpose: "cobranca", agent_id: "collections-agent", consumer_id: "merchant_demo", due_date: "2026-09-30", actor: { type: "agent", agent: "collections-agent@0.1.0", on_behalf_of: "merchant_demo" } };
347
+ const conflict = (code: string) => ({ status: 409, body: { error: { code, message: "conflict" }, request_id: null } });
348
+
349
+ it("issuance_unconfirmed is the one 409 that means still issuing: in_flight, and the key is not read after the id", async () => {
350
+ const w = wired(conflict("issuance_unconfirmed"));
351
+ expect(await withFetch(w.fetchStub, () => w.rail.lookup(payment.attempt_id, payment, "chg_409"))).toEqual({ status: "in_flight" });
352
+ expect(w.seen).toEqual([{ method: "GET", path: "/v1/charges/chg_409" }]);
353
+ });
354
+
355
+ it("charge_reference_ambiguous is terminal for the reference: failed with that code, by the id and by the key, and never polled as in flight", async () => {
356
+ const byId = wired(conflict("charge_reference_ambiguous"));
357
+ const outById = await withFetch(byId.fetchStub, () => byId.rail.lookup(payment.attempt_id, payment, "chg_409"));
358
+ expect(outById).toMatchObject({ status: "failed", code: "charge_reference_ambiguous", message: expect.stringContaining("by the charge id") });
359
+ expect(byId.seen).toEqual([{ method: "GET", path: "/v1/charges/chg_409" }]);
360
+
361
+ const byKey = wired(conflict("charge_reference_ambiguous"));
362
+ const outByKey = await withFetch(byKey.fetchStub, () => byKey.rail.lookup(payment.attempt_id, payment));
363
+ expect(outByKey).toMatchObject({ status: "failed", code: "charge_reference_ambiguous", message: expect.stringContaining(payment.attempt_id) });
364
+ expect(byKey.seen).toEqual([{ method: "GET", path: `/v1/charges/${payment.attempt_id}` }]);
365
+ });
366
+
367
+ it("a 409 with a code this kit does not read, or with no code at all, is a failure and not in_flight", async () => {
368
+ const unknown = wired(conflict("charge_conflict_new_kind"));
369
+ expect(await withFetch(unknown.fetchStub, () => unknown.rail.lookup(payment.attempt_id, payment, "chg_409"))).toMatchObject({ status: "failed", code: "charge_conflict_new_kind", message: expect.stringContaining("not read as a charge still issuing") });
370
+ const bare = wired({ status: 409 });
371
+ const out = await withFetch(bare.fetchStub, () => bare.rail.lookup(payment.attempt_id, payment, "chg_409"));
372
+ expect(out).toMatchObject({ status: "failed" });
373
+ expect(out).not.toEqual({ status: "in_flight" });
374
+ });
375
+
376
+ it("through the engine: an issued receivable whose read turns ambiguous closes failed (charge_reference_ambiguous), instead of staying executing", async () => {
377
+ const w = wired(conflict("charge_reference_ambiguous"));
378
+ const h = receivables({ dispatchTo: w.rail });
379
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 108000, due_date: "2026-09-30", description: "acordo 1042, a vista" }] });
380
+ if (!d.ok) throw new Error("refused");
381
+ const issued = await withFetch(w.fetchStub, () => h.engine.execute(d.execution.id));
382
+ expect(issued).toMatchObject({ state: "executing", reason: "awaiting_settlement" });
383
+ const closed = await withFetch(w.fetchStub, () => h.engine.reconcile(issued.id));
384
+ expect(closed.state).toBe("failed");
385
+ expect(closed.reason).toBe("charge_reference_ambiguous");
386
+ expect(closed.history.at(-1)).toMatchObject({ from: "executing", to: "failed", reason: "charge_reference_ambiguous" });
387
+ });
388
+
389
+ it("reconcile, never reissue: resume and reconcile send nothing for it, and a new charge to the same payee is refused before it reaches the API", async () => {
390
+ const w = wired(conflict("charge_reference_ambiguous"));
391
+ const h = receivables({ dispatchTo: w.rail });
392
+ const d = await h.engine.draft({ items: [{ payee: "acordo-1", amount: 108000, due_date: "2026-09-30" }] });
393
+ if (!d.ok) throw new Error("refused");
394
+ const issued = await withFetch(w.fetchStub, () => h.engine.execute(d.execution.id));
395
+ const closed = await withFetch(w.fetchStub, () => h.engine.reconcile(issued.id));
396
+ expect(closed.reason).toBe("charge_reference_ambiguous");
397
+ const creates = () => w.seen.filter((r) => r.method === "POST" && r.path === "/v1/charges").length;
398
+ expect(creates()).toBe(1);
399
+ const requestsBefore = w.seen.length;
400
+
401
+ // `resume` walks `executing` only, and both entry points return a terminal execution untouched.
402
+ expect(h.engine.list({ state: "executing" })).toHaveLength(0);
403
+ expect(await withFetch(w.fetchStub, () => h.engine.resumePending(closed.id))).toMatchObject({ state: "failed", reason: "charge_reference_ambiguous" });
404
+ expect(await withFetch(w.fetchStub, () => h.engine.reconcile(closed.id))).toMatchObject({ state: "failed", reason: "charge_reference_ambiguous" });
405
+ expect(w.seen.length).toBe(requestsBefore);
406
+
407
+ // The same debt asked for again: denied at draft, nothing sent.
408
+ const again = await withFetch(w.fetchStub, () => h.engine.draft({ items: [{ payee: "acordo-1", amount: 108000, due_date: "2026-10-15" }] }));
409
+ expect(again).toMatchObject({ ok: true, execution: { state: "denied", reason: "charge_reference_ambiguous" } });
410
+ expect(creates()).toBe(1);
411
+
412
+ // Another payee is not held up by it.
413
+ const other = await withFetch(w.fetchStub, () => h.engine.draft({ items: [{ payee: OTHER, amount: 5000, due_date: "2026-09-30" }] }));
414
+ expect(other).toMatchObject({ ok: true, execution: { state: "approved" } });
415
+ });
416
+ });
@@ -0,0 +1,28 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createCodeSparClient } from "../src/api/client.js";
3
+ import { assertTestKey, isTestKey, NotATestKeyError, redactKey } from "../src/secrets.js";
4
+
5
+ // Built at runtime so the secret scan (which refuses key-shaped literals) stays honest about this file.
6
+ const TEST = ["csk", "test", "0123456789abcdef"].join("_");
7
+ const LIVE = ["csk", "live", "0123456789"].join("_");
8
+
9
+ describe("sandbox by construction", () => {
10
+ it("accepts only csk_test_ keys", () => {
11
+ expect(isTestKey(TEST)).toBe(true);
12
+ expect(isTestKey(LIVE)).toBe(false);
13
+ expect(isTestKey("csk_test_")).toBe(false);
14
+ expect(isTestKey(undefined)).toBe(false);
15
+ expect(() => assertTestKey(LIVE)).toThrow(NotATestKeyError);
16
+ });
17
+
18
+ it("refuses to build an API client with a live key, before any network", () => {
19
+ expect(() => createCodeSparClient({ apiKey: LIVE })).toThrow(NotATestKeyError);
20
+ expect(() => createCodeSparClient({ apiKey: undefined })).toThrow(NotATestKeyError);
21
+ expect(createCodeSparClient({ apiKey: TEST })).toBeDefined();
22
+ });
23
+
24
+ it("redacts keys for logs", () => {
25
+ expect(redactKey(TEST)).toBe("csk_test_…cdef");
26
+ expect(redactKey(TEST)).not.toContain("0123456789");
27
+ });
28
+ });
@@ -0,0 +1,67 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { canTransition, IllegalTransitionError, isTerminal, transition, TRANSITIONS, type Execution } from "../src/state-machine.js";
3
+ import type { Actor } from "../src/types.js";
4
+
5
+ const actor: Actor = { type: "agent", agent: "bills-agent@0.1.0", on_behalf_of: "usr_test" };
6
+
7
+ function drafted(): Execution<"drafted"> {
8
+ return {
9
+ id: "exe_1",
10
+ run_id: "run_1",
11
+ state: "drafted",
12
+ mode: "human",
13
+ actor,
14
+ items: [],
15
+ total: 0,
16
+ currency: "BRL",
17
+ items_hash: "sha256:x",
18
+ mandate: { id: "mdt_1", version: 1 },
19
+ idempotency_key: "idk_1",
20
+ blocking_reasons: [],
21
+ outcomes: [],
22
+ history: [],
23
+ created_at: "2026-09-23T10:00:00.000Z",
24
+ updated_at: "2026-09-23T10:00:00.000Z",
25
+ };
26
+ }
27
+
28
+ describe("section 4.1: closed state machine", () => {
29
+ it("has exactly the table of the spec plus the 4.2 return and the 4.7 exits", () => {
30
+ expect(TRANSITIONS).toEqual({
31
+ drafted: ["awaiting_approval", "approved", "denied", "expired"],
32
+ awaiting_approval: ["approved", "denied", "expired"],
33
+ approved: ["executing", "awaiting_approval", "denied", "expired"],
34
+ executing: ["settled", "failed"],
35
+ settled: [],
36
+ failed: [],
37
+ denied: [],
38
+ expired: [],
39
+ });
40
+ });
41
+
42
+ it("walks the happy path and appends every step to history", () => {
43
+ const at = "2026-09-23T10:01:00.000Z";
44
+ const a = transition(drafted(), "awaiting_approval", { at, actor });
45
+ const b = transition(a, "approved", { at, actor });
46
+ const c = transition(b, "executing", { at, actor });
47
+ const d = transition(c, "settled", { at, actor });
48
+ expect(d.state).toBe("settled");
49
+ expect(d.history.map((h) => h.to)).toEqual(["awaiting_approval", "approved", "executing", "settled"]);
50
+ expect(isTerminal(d.state)).toBe(true);
51
+ });
52
+
53
+ it("refuses a transition outside the table at runtime even when the types were bypassed", () => {
54
+ const settled = { ...drafted(), state: "settled" as const };
55
+ expect(() => transition(settled as unknown as Execution<"drafted">, "awaiting_approval", { at: "x", actor })).toThrow(IllegalTransitionError);
56
+ expect(canTransition("executing", "denied")).toBe(false);
57
+ expect(canTransition("drafted", "executing")).toBe(false);
58
+ expect(canTransition("settled", "failed")).toBe(false);
59
+ });
60
+
61
+ it("terminal states have no exits", () => {
62
+ for (const s of ["settled", "failed", "denied", "expired"] as const) {
63
+ expect(TRANSITIONS[s]).toEqual([]);
64
+ expect(isTerminal(s)).toBe(true);
65
+ }
66
+ });
67
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Section 15: "a transition outside section 4.1 does not compile". This
3
+ * file is compiled by `npm run typecheck`; every `@ts-expect-error` below
4
+ * is a transition the table forbids. If one of them ever compiles, tsc
5
+ * reports an unused directive and the check fails.
6
+ */
7
+ import { transition, type Execution } from "../src/state-machine.js";
8
+ import type { Actor } from "../src/types.js";
9
+
10
+ declare const actor: Actor;
11
+ declare const at: string;
12
+ declare const drafted: Execution<"drafted">;
13
+ declare const awaiting: Execution<"awaiting_approval">;
14
+ declare const approved: Execution<"approved">;
15
+ declare const executing: Execution<"executing">;
16
+ declare const settled: Execution<"settled">;
17
+ declare const failed: Execution<"failed">;
18
+ declare const denied: Execution<"denied">;
19
+ declare const expired: Execution<"expired">;
20
+
21
+ // Allowed, for contrast.
22
+ transition(drafted, "awaiting_approval", { at, actor });
23
+ transition(drafted, "approved", { at, actor });
24
+ transition(drafted, "denied", { at, actor });
25
+ transition(awaiting, "approved", { at, actor });
26
+ transition(approved, "executing", { at, actor });
27
+ transition(approved, "awaiting_approval", { at, actor });
28
+ transition(executing, "settled", { at, actor });
29
+ transition(executing, "failed", { at, actor });
30
+
31
+ // The model cannot skip the core: nothing goes straight to executing.
32
+ // @ts-expect-error drafted -> executing is not in the table
33
+ transition(drafted, "executing", { at, actor });
34
+ // @ts-expect-error awaiting_approval -> executing is not in the table
35
+ transition(awaiting, "executing", { at, actor });
36
+ // @ts-expect-error drafted -> settled is not in the table
37
+ transition(drafted, "settled", { at, actor });
38
+ // @ts-expect-error awaiting_approval -> settled is not in the table
39
+ transition(awaiting, "settled", { at, actor });
40
+
41
+ // Executing closes only by the rail's event.
42
+ // @ts-expect-error executing -> denied is not in the table
43
+ transition(executing, "denied", { at, actor });
44
+ // @ts-expect-error executing -> expired is not in the table
45
+ transition(executing, "expired", { at, actor });
46
+ // @ts-expect-error executing -> approved is not in the table
47
+ transition(executing, "approved", { at, actor });
48
+
49
+ // Terminal states have no exits. Repeating does not reopen.
50
+ // @ts-expect-error settled is terminal
51
+ transition(settled, "executing", { at, actor });
52
+ // @ts-expect-error failed is terminal
53
+ transition(failed, "executing", { at, actor });
54
+ // @ts-expect-error denied is terminal
55
+ transition(denied, "approved", { at, actor });
56
+ // @ts-expect-error expired is terminal
57
+ transition(expired, "awaiting_approval", { at, actor });
58
+ // @ts-expect-error settled is terminal
59
+ transition(settled, "settled", { at, actor });
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "."
5
+ },
6
+ "include": [
7
+ "src/**/*.ts",
8
+ "test/**/*.ts"
9
+ ]
10
+ }