@fantastic.dev/better-stripe 0.45.1 → 0.46.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 (99) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/MIGRATION.md +6 -4
  3. package/README.md +8 -6
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +46 -0
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +23 -0
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +46 -0
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +23 -0
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/connect/refundSync.d.ts +32 -0
  13. package/dist/client/connect/refundSync.d.ts.map +1 -0
  14. package/dist/client/connect/refundSync.js +61 -0
  15. package/dist/client/connect/refundSync.js.map +1 -0
  16. package/dist/client/connect/refundSyncValidation.d.ts +16 -0
  17. package/dist/client/connect/refundSyncValidation.d.ts.map +1 -0
  18. package/dist/client/connect/refundSyncValidation.js +87 -0
  19. package/dist/client/connect/refundSyncValidation.js.map +1 -0
  20. package/dist/client/index.d.ts +30 -0
  21. package/dist/client/index.d.ts.map +1 -1
  22. package/dist/client/index.js +5 -0
  23. package/dist/client/index.js.map +1 -1
  24. package/dist/component/_generated/api.d.ts +12 -0
  25. package/dist/component/_generated/api.d.ts.map +1 -1
  26. package/dist/component/_generated/api.js.map +1 -1
  27. package/dist/component/_generated/component.d.ts +67 -0
  28. package/dist/component/_generated/component.d.ts.map +1 -1
  29. package/dist/component/connect/mutations.d.ts.map +1 -1
  30. package/dist/component/connect/mutations.js +2 -53
  31. package/dist/component/connect/mutations.js.map +1 -1
  32. package/dist/component/connect/refundWrites.d.ts +6 -0
  33. package/dist/component/connect/refundWrites.d.ts.map +1 -0
  34. package/dist/component/connect/refundWrites.js +56 -0
  35. package/dist/component/connect/refundWrites.js.map +1 -0
  36. package/dist/component/earnings/triggers.d.ts +46 -0
  37. package/dist/component/earnings/triggers.d.ts.map +1 -1
  38. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  39. package/dist/component/refundHistory/originalSeller.d.ts +1 -1
  40. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
  41. package/dist/component/refundHistory/originalSeller.js.map +1 -1
  42. package/dist/component/refundSync/helpers.d.ts +43 -0
  43. package/dist/component/refundSync/helpers.d.ts.map +1 -0
  44. package/dist/component/refundSync/helpers.js +71 -0
  45. package/dist/component/refundSync/helpers.js.map +1 -0
  46. package/dist/component/refundSync/mutations.d.ts +56 -0
  47. package/dist/component/refundSync/mutations.d.ts.map +1 -0
  48. package/dist/component/refundSync/mutations.js +113 -0
  49. package/dist/component/refundSync/mutations.js.map +1 -0
  50. package/dist/component/refundSync/queries.d.ts +12 -0
  51. package/dist/component/refundSync/queries.d.ts.map +1 -0
  52. package/dist/component/refundSync/queries.js +10 -0
  53. package/dist/component/refundSync/queries.js.map +1 -0
  54. package/dist/component/refundSync/routing.d.ts +8 -0
  55. package/dist/component/refundSync/routing.d.ts.map +1 -0
  56. package/dist/component/refundSync/routing.js +42 -0
  57. package/dist/component/refundSync/routing.js.map +1 -0
  58. package/dist/component/refundSync/schema.d.ts +25 -0
  59. package/dist/component/refundSync/schema.d.ts.map +1 -0
  60. package/dist/component/refundSync/schema.js +15 -0
  61. package/dist/component/refundSync/schema.js.map +1 -0
  62. package/dist/component/refundSync/validators.d.ts +164 -0
  63. package/dist/component/refundSync/validators.d.ts.map +1 -0
  64. package/dist/component/refundSync/validators.js +32 -0
  65. package/dist/component/refundSync/validators.js.map +1 -0
  66. package/dist/component/schema.d.ts +23 -0
  67. package/dist/component/schema.js +2 -0
  68. package/dist/component/schema.js.map +1 -1
  69. package/docs/affiliate-clawbacks.md +3 -3
  70. package/docs/architecture/component-extraction.md +415 -0
  71. package/docs/architecture/durable-execution.md +200 -0
  72. package/docs/architecture/recovery-workflow.md +69 -0
  73. package/docs/balance-funding-state.md +114 -0
  74. package/docs/balance-funding-workflow.md +53 -0
  75. package/docs/example-balance-funding-cutover.md +94 -0
  76. package/docs/example-recovery-cutover.md +21 -0
  77. package/docs/processing-cost-reconciliation.md +23 -0
  78. package/docs/refund-context.md +54 -0
  79. package/docs/release-handoff.md +196 -0
  80. package/docs/releasing.md +41 -0
  81. package/package.json +12 -2
  82. package/src/client/connect/refundSync.test.ts +239 -0
  83. package/src/client/connect/refundSync.transport.test.ts +396 -0
  84. package/src/client/connect/refundSync.ts +125 -0
  85. package/src/client/connect/refundSyncValidation.ts +120 -0
  86. package/src/client/index.ts +19 -0
  87. package/src/component/_generated/api.ts +12 -0
  88. package/src/component/_generated/component.ts +100 -0
  89. package/src/component/connect/mutations.ts +2 -67
  90. package/src/component/connect/refundWrites.ts +76 -0
  91. package/src/component/refundHistory/originalSeller.ts +4 -1
  92. package/src/component/refundSync/helpers.ts +99 -0
  93. package/src/component/refundSync/mutations.ts +131 -0
  94. package/src/component/refundSync/queries.ts +10 -0
  95. package/src/component/refundSync/refund-sync.test.ts +255 -0
  96. package/src/component/refundSync/routing.ts +55 -0
  97. package/src/component/refundSync/schema.ts +19 -0
  98. package/src/component/refundSync/validators.ts +35 -0
  99. package/src/component/schema.ts +2 -0
@@ -0,0 +1,415 @@
1
+ # Component extraction and durable execution contracts
2
+
3
+ Status: accepted design record. The implementation and cross-domain acceptance
4
+ suite have merged. The proposal sections below preserve the design
5
+ history reviewed against main `e9994a9`; their illustrative signatures are not
6
+ an export inventory. Use the [release handoff](../release-handoff.md) and linked
7
+ domain guides for the implemented APIs, defaults and migration boundaries.
8
+
9
+ ## Ownership decision
10
+
11
+ BetterStripe owns reusable Stripe protocols, provider verification, immutable
12
+ financial allocations, recovery reservations and durable operation state. The
13
+ host authenticates callers and selects business policy before invoking them.
14
+ Opaque host identifiers never imply authorization.
15
+
16
+ | Workstream | Package responsibility | Host responsibility |
17
+ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
18
+ | Balance funding | Persist restoration settings, serialize a subscription operation, apply and verify provider changes | Authorize subscription/account, capture consent, choose enable/disable |
19
+ | Recovery preparation | Atomically reserve a bounded batch and seal when complete | Select same-currency scope, source and debit/credit policy |
20
+ | Settlement/recovery execution | Resume original allocations, reconcile provider receipts, finish existing ledgers | Select recipients, rates, eligible sales and uncollectible policy |
21
+ | Processing costs | Verify original funding provenance, calculate an explicitly selected liability policy, reconcile claim revisions | Decide who owes retained processing/dispute costs |
22
+ | Catalog, portal and accounts | Typed Stripe calls, lookup-key adoption, scoped cache refresh, capability normalization | Tier names, product allowlists, proration/cancellation policy, merchant eligibility |
23
+ | Reporting and scheduling | Bounded component readers and operation status | User/store joins, entitlements, referral attribution, projections and cron cadence |
24
+
25
+ Do not copy `storeSales`, `sellerCosts`, `storePlanCatalog` or `users` into the
26
+ component. Keep host IDs as strings only where needed for correlation. Never
27
+ parse `example:store:*`, role names or tier names in package code. Existing
28
+ settlement, transfer and cost-recovery tables remain the money ledger. A
29
+ workflow journal records execution progress, not a second balance.
30
+
31
+ ## Public contract conventions
32
+
33
+ New methods live on domain clients and take `ctx` plus a validated options
34
+ object. Existing `costRecovery` methods and stateless `prepareBalanceFunding`
35
+ and `setBalanceFunding` remain available during migration. New orchestration
36
+ methods must not silently change their behavior or automatically enable preview
37
+ features. The following signatures specify the interfaces to implement.
38
+ Referenced existing types retain their definitions in the linked source files
39
+ below.
40
+
41
+ ```ts
42
+ type OperationScope = {
43
+ accountId: string;
44
+ scopeKey: string; // Host-selected opaque correlation key.
45
+ };
46
+ type OperationRef = OperationScope & {
47
+ operationId: string; // Durable, unique within this component installation.
48
+ version: number; // Positive safe integer, not a queue attempt count.
49
+ };
50
+ type Unavailable =
51
+ | {
52
+ status: "not_ready";
53
+ reason: "provider_pending" | "fee_pending" | "history_incomplete";
54
+ retryable: true;
55
+ }
56
+ | {
57
+ status: "conflict";
58
+ reason: "scope_busy" | "revision_changed" | "identity_changed";
59
+ retryable: false;
60
+ }
61
+ | {
62
+ status: "rejected";
63
+ reason: "invalid_scope" | "unsupported_source" | "policy_invalid";
64
+ retryable: false;
65
+ };
66
+ type OperationStatus = OperationRef & {
67
+ state:
68
+ "pending" | "running" | "unknown" | "succeeded" | "failed" | "canceled";
69
+ cancelRequested: boolean;
70
+ failureCode?: string; // Safe package code, never a raw provider message.
71
+ };
72
+ ```
73
+
74
+ The shared outcomes workstream owns shared outcomes and adapters for existing
75
+ readiness types. Preserve existing result shapes; add explicit conversions where
76
+ needed. A caller handles `scope_busy` by reading the active operation, and
77
+ `revision_changed` by reading fresh state and asking policy to decide. They
78
+ never trigger blind action retries. Provider transport errors retain their
79
+ identity internally. A provider write with an uncertain outcome moves the
80
+ operation to `unknown`; it is not a successful, rejected or canceled money
81
+ movement. Exhausted bounded history stays unknown.
82
+
83
+ The additive SDK adapters return `FinancialOutcome<T>`, with ready data in
84
+ `value`, and preserve existing reader result shapes. The shared
85
+ `FinancialUnavailable` contract extends the examples above with terminal
86
+ `payment_not_payable` and `currency_mismatch` reasons. It also exposes
87
+ `unknown/provider_outcome_unknown` and `unknown/history_incomplete`, both
88
+ nonretryable. Unknown writes require reconciliation, including after bounded
89
+ history exhaustion. The pure retry decision accepts only validated pending
90
+ outcomes and explicit limits. See [financial readiness](../read-contracts.md#financial-readiness-and-bounded-retries).
91
+
92
+ Derive account, subscription, invoice and source identities on the server.
93
+ Validate complete immutable arguments on every replay, including currency,
94
+ target, provider version and policy snapshot. Status/cancel lookups must match
95
+ the saved account and scope; an operation ID alone never selects a foreign
96
+ scope. All amounts and revisions use checked safe integers. A missing fee is not
97
+ zero. Reject mixed currency and unsupported funding provenance before reserving
98
+ or transferring money.
99
+
100
+ ## Balance-funding state and execution
101
+
102
+ The funding state workstream owns component state under
103
+ `src/component/balanceFunding/`; the funding workflow workstream owns provider
104
+ orchestration and its domain client. Use these additive method contracts:
105
+
106
+ ```ts
107
+ // Server-only. preparation is the existing BalanceFundingPreparation type.
108
+ balanceFunding.prepare(ctx, {
109
+ accountId,
110
+ scopeKey,
111
+ stripeSubscriptionId,
112
+ consent: true,
113
+ requestKey,
114
+ }); // => OperationStatus | Unavailable, saves intent before provisioning
115
+ balanceFunding.savePreparation(ctx, {
116
+ accountId,
117
+ scopeKey,
118
+ preparation,
119
+ consentAt,
120
+ }); // => { preparationId: string }, exact replay returns the same record
121
+ balanceFunding.begin(ctx, {
122
+ accountId,
123
+ scopeKey,
124
+ preparationId,
125
+ enabled,
126
+ consent,
127
+ requestKey,
128
+ }); // => { status: "accepted", operation: OperationRef }
129
+ // or { status: "unchanged", enabled } or Unavailable
130
+ balanceFunding.start(ctx, { ...operation }); // => OperationStatus
131
+ balanceFunding.getOperation(ctx, { ...operation }); // => OperationStatus | null
132
+ balanceFunding.requestCancel(ctx, { ...operation }); // => OperationStatus
133
+
134
+ type PreparationLookup =
135
+ | {
136
+ status: "prepared";
137
+ operation: OperationRef;
138
+ stripeSubscriptionId: string;
139
+ preparationId: string;
140
+ }
141
+ | {
142
+ status: "pending" | "running" | "unknown" | "failed" | "canceled";
143
+ operation: OperationRef;
144
+ };
145
+ balanceFunding.getPreparation(ctx, {
146
+ ...operation, // Account, scope, operation ID and version are all required.
147
+ stripeSubscriptionId,
148
+ }); // => PreparationLookup | Unavailable | null
149
+
150
+ balanceFunding.findPreparationOperation(ctx, {
151
+ accountId,
152
+ scopeKey,
153
+ stripeSubscriptionId,
154
+ requestKey,
155
+ providerApiVersion,
156
+ consent: true,
157
+ }); // => OperationStatus | Unavailable | null; read-only request recovery
158
+ ```
159
+
160
+ `getPreparation` reads the result of an existing preparation operation. It never
161
+ provisions a payment method or captures restoration settings. It validates the
162
+ saved account, subscription, scope, operation ID and version together; an
163
+ existing foreign or contradictory binding returns `invalid_scope` or
164
+ `identity_changed`, never a foreign preparation reference. `null` means no
165
+ matching operation was found, not proof that a provider write did not happen or
166
+ permission to start a new one. Pending, running, unknown, failed and canceled
167
+ results expose no preparation ID. Only a successfully verified and durably
168
+ saved preparation returns `prepared`, with the original server-owned ID.
169
+ Replays keep that result stable. Status and lookup results expose neither
170
+ restoration settings nor credentials.
171
+
172
+ Before recapturing provider settings or consent time, the runtime queries
173
+ `findPreparationOperation` with the original public request key. It validates
174
+ saved prepare-kind, account, scope, subscription, API version and consent binding,
175
+ returning only safe operation identity/state. Unknown or failed intents retain
176
+ their original identity; a new key never permits recapturing already-enabled
177
+ restoration or replacing unresolved preparation. A null lookup is not proof that
178
+ no provider effect happened. Full low-level captured snapshots remain immutable.
179
+
180
+ If a prepare response is lost, repeat `prepare` with the original request key
181
+ and unchanged payload to recover the same operation, then call `getPreparation`
182
+ for its reference. Hold pending or unknown work and reconcile that operation;
183
+ do not create another payment method. Pass the returned preparation ID to
184
+ `begin`. `begin` independently validates its saved account/subscription binding
185
+ and verified state before accepting the new setting intent. A browser-supplied
186
+ ID alone proves neither ownership nor readiness. `savePreparation` remains the
187
+ explicit path for verified legacy imports, not the new preparation handoff.
188
+
189
+ `accountId` must equal the preparation's `customerAccount`; scope identifies one
190
+ subscription. Enforce one active operation per account/subscription even if a
191
+ host supplies a different scope alias. The component validates that binding and
192
+ refuses conflicting preparation data. Capture original payment-method ID and
193
+ payment-method types once, including null versus empty values. Never recapture
194
+ restoration settings from an already enabled subscription. A changed
195
+ subscription needs an explicit new preparation after the old operation is
196
+ reconciled, not an overwrite.
197
+
198
+ `requestKey` identifies one host intent. The component binds it to the complete
199
+ payload. The same request returns the same operation even after completion; a
200
+ changed payload conflicts. A completed disable followed by a new enable uses a
201
+ new request key and operation version. Same-target calls while pending reuse the
202
+ active operation; opposing targets conflict. An already satisfied state may
203
+ return unchanged only when no unresolved operation exists.
204
+
205
+ Begin durably before any provider write. Persist a stable provider key per
206
+ phase, including prepare/create/attach and apply/enable/disable. Preparation
207
+ provisioning also needs a durable intent before provisioning so a lost prepare
208
+ response cannot create another payment method. The `prepare` entry point owns
209
+ that intent and saves the original settings before create/attach. Keep
210
+ `savePreparation` for verified legacy records. Replays use the saved restoration
211
+ and request snapshot.
212
+
213
+ The completion mutation compares operation identity, version, target and
214
+ provider receipt before updating the setting. An old action cannot finish a
215
+ newer version. If Stripe succeeds but the finish mutation fails, read current
216
+ subscription and payment-method ownership and reconcile the same operation.
217
+ External changes that match neither original nor intended settings produce an
218
+ explicit conflict. A configured preview API version is required at prepare and
219
+ apply time. A runtime must carry the selected API version and request scope
220
+ through all action steps. The runtime composition workstream must prove a
221
+ supported credential execution boundary. Do not assume a nested component can
222
+ read host environment variables. One supported design may invoke a host provider
223
+ action reference that creates the SDK from runtime host environment and returns
224
+ only a nonsecret validated receipt. If component-local credential access is
225
+ unsupported, keep ledgers and orchestration component-owned while provider steps
226
+ run in those host actions. Redact secrets from action results, durable
227
+ arguments, journals, status and logs. Never persist Stripe secrets in workflow
228
+ arguments or copy them into operation state.
229
+
230
+ ## Atomic recovery preparation
231
+
232
+ The recovery preparation workstream adds the following method to the existing
233
+ cost-recovery client:
234
+
235
+ ```ts
236
+ costRecovery.prepareGroup(ctx, {
237
+ ...groupOptions, // Existing RecoveryGroupOptions, including currency and limits.
238
+ limit: 100, // Optional, same bounded validation as reserve.
239
+ });
240
+ // => { status: "prepared", group, isDone: boolean } | Unavailable
241
+ ```
242
+
243
+ Each invocation runs one component mutation. It checks immutable group identity
244
+ and active-scope ownership, derives the next reservation identity, reserves at
245
+ most the permitted batch and seals only when the target equals the reserved
246
+ amount. A sealed group's replay returns the original group with `isDone: true`.
247
+ An open group returns `isDone: false` until another bounded invocation
248
+ completes. Do not derive batch IDs in host code from an independently read
249
+ `pendingOperations`. Persist or derive a monotonic batch sequence in the atomic
250
+ mutation; empty batches and finished reservations cannot recycle an old ID.
251
+
252
+ Preserve the existing signed accounting equation for each claim and balance:
253
+ `amountDue = collectedAmount + reservedAmount + outstanding`. Claim updates use
254
+ revision checks. Group identity, source gross/fees, currency and debit/credit
255
+ limits cannot change on retry. The active group excludes another boundary for
256
+ the same account/scope/currency through transactional state, not queue
257
+ concurrency. A foreign active group returns `scope_busy`. The host may choose to
258
+ defer recovery for an otherwise eligible sale; the package never chooses that
259
+ business policy.
260
+
261
+ The recovery workflow workstream adds `costRecovery.startGroup(ctx, { ...scope,
262
+ groupKey, requestKey, releaseUncollectible })` returning `OperationStatus |
263
+ Unavailable`. Preparation must finish before execution. Resolve the source kind
264
+ from the sealed group; never infer it from metadata strings. The settlement
265
+ caller provides its separately pinned allocation to existing settlement
266
+ execution, including the sealed recovery adjustment. Verify the same group's
267
+ scope and authorized adjustment before use. Invoice collection reuses
268
+ `attachInvoice` and `reconcileInvoice`. Preserve the explicit uncollectible-
269
+ release policy and bounded `finish` continuation. A failed workflow never
270
+ automatically releases an uncertain reservation.
271
+
272
+ The provenance resolver workstream resolves original
273
+ invoice/payment/subscription/price provenance with bounded complete provider
274
+ history and typed unavailable outcomes. Reject partial or ambiguous funding
275
+ instead of guessing. The explicit-policy pure deficit helper requires explicit
276
+ liability and rounding policy. The processing-cost reconciliation workstream
277
+ uses both in revision-guarded cost claim reconciliation and retains the original
278
+ recovery receipt for rollback. Current tier prices, affiliate rates or webhook
279
+ arrival order cannot rewrite an original allocation or prove original funding.
280
+
281
+ ## Durable execution decision and composition exit gate
282
+
283
+ Use [Workflow](https://github.com/convex/workflow) for multi-step funding and
284
+ recovery sequences. Keep handlers deterministic and perform provider I/O in
285
+ action steps. Workflow already uses Workpool for step scheduling. Add a separate
286
+ [Workpool](https://github.com/convex/workpool) only for independent bounded jobs
287
+ that need their own concurrency/retry policy. Avoid double-queueing each step.
288
+
289
+ The runtime composition workstream must demonstrate nested installation inside
290
+ BetterStripe with pinned compatible versions, generated references, credential
291
+ access/API-version propagation, start/status/cancel and nested-component test
292
+ registration. Until those checks pass, this is an implementation choice to
293
+ validate, not a compatibility claim. If composition fails, document the specific
294
+ failure and revise this decision before adding a host-owned execution service or
295
+ starting dependent workflows.
296
+
297
+ A pool-wide concurrency cap is capacity control. Component scope claims provide
298
+ serialization. Stripe writes still need stable keys, authoritative
299
+ reconciliation and existing financial ledgers. Retry only classified transient
300
+ or explicitly not-ready steps with bounded attempts/backoff; do not retry every
301
+ financial action by default. Never generate new money-operation IDs in a retried
302
+ step.
303
+
304
+ Cancellation stops future work where possible. An in-flight action can complete.
305
+ Record `cancelRequested` separately, then reconcile its receipt before reporting
306
+ terminal `canceled`. Completed provider effects remain ledger facts;
307
+ cancellation is not refund, reversal or reservation release. Unknown work keeps
308
+ its scope claim until reconciliation. Resume/restart keeps the original
309
+ operation and phase keys. A new workflow-run ID is never permission to repeat a
310
+ provider effect.
311
+
312
+ Persist definition version with operation state. Retain executable old
313
+ definitions until their operations finish or migrate through a tested compatible
314
+ transition. Reject incompatible resumes. Cleanup may remove terminal execution
315
+ history only after durable receipts and replay identities survive elsewhere;
316
+ never delete financial ledgers or key bindings to satisfy workflow retention
317
+ limits.
318
+
319
+ ## Migration and rollback
320
+
321
+ The funding cutover workstream imports balance-funding preparations and active
322
+ operations in bounded, idempotent pages. Preserve original restoration values,
323
+ operation version, consent, target and pending state. Preserve exact legacy
324
+ provider keys, including `example_balance_${subscriptionId}_${version}` and
325
+ their phase suffixes. Preserve `example_balance_prepare_${subscriptionId}` for
326
+ interrupted legacy preparation. A new namespace is safe only for genuinely new
327
+ operations. An unknown legacy operation requires reconciliation before switching
328
+ writers.
329
+
330
+ The financial cutover workstream reuses `costRecovery.importClaim` for verified
331
+ opening collections and preserves original claim/group/operation identities.
332
+ Imports use stable source keys and immutable payload comparison. An exact page
333
+ retry is a no-op; conflicting scope, amounts or receipts fail without partial
334
+ writes. Never import a live claim as a new opening balance. Host
335
+ authorization/mapping runs before imports. Use server-side checkpoints and per-
336
+ scope reconciliation, not a browser cursor, as migration evidence. Keep host
337
+ reporting projections replay-safe by source identity.
338
+
339
+ For every scope: pause old entry points that start new effects, retain authorized
340
+ receipt reconciliation and finish for existing operations, reconcile in-flight
341
+ operations, import and verify state, then enable one new writer. Reconciliation
342
+ must retain the original operation and phase keys; it cannot start a replacement
343
+ effect or admit a new intent. Retire the remaining old mutation entry points
344
+ only after the verified handoff accounts for their operations. Queries may
345
+ read projections, but never sum old and new balances. Record migration version
346
+ and source checkpoint. Do not delete legacy restoration/provenance until
347
+ rollback and retention needs end. Rollback first stops new starts, drains or
348
+ reconciles pending work and establishes one owner. Restore old writers only
349
+ after a tested reverse mapping supports new state. Reverting code alone is
350
+ unsafe after new operations exist.
351
+
352
+ ## Parallel implementation and integration
353
+
354
+ Each agent claims its ticket, uses an isolated `codex/<issue-number>-<slug>`
355
+ worktree, and starts dependent work only after blockers merge. Domain agents own
356
+ their client/component domain files, schema fragments and co-located tests. Host
357
+ cutover agents own their specified example domains. The contracts workstream
358
+ owns this ADR; the shared outcomes workstream owns shared outcome definitions.
359
+ Resolve interface changes here before implementing incompatible callers.
360
+
361
+ The coordinator is the shared-file integration owner. Serialize edits to
362
+ `src/client/index.ts`, `src/component/schema.ts`,
363
+ `src/component/convex.config.ts`, package manifests/lockfile and
364
+ `_generated/**`. Domain PRs propose minimal shared patches and coordinate them
365
+ before pushing. Integrate each domain's exports and registration with its
366
+ implementation, before dependent cutovers. The release workstream performs final
367
+ consolidation, not the first registration of earlier APIs. Generate types
368
+ through actual codegen; never hand-edit generated files. Do not publish npm or
369
+ operate live money as part of these implementation tickets.
370
+
371
+ ## Required acceptance evidence
372
+
373
+ The following are behavioral fixtures for implementation tests, not a new
374
+ parallel model of production state. Domain PRs turn the relevant rows into tests
375
+ against real component mutations/actions. The integration verification
376
+ workstream verifies their combined behavior.
377
+
378
+ | Fixture | Required observation |
379
+ | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
380
+ | Same request key and payload arrives twice | One operation, one original payload, same phase keys |
381
+ | Prepare response is lost after successful provisioning | Replay finds the same operation; scoped lookup returns the original preparation ID; begin uses it without another create/attach |
382
+ | Preparation lookup is pending, unknown or foreign | No preparation reference or new provider effect; pending/unknown holds and foreign scope rejects |
383
+ | Same key with a different account, currency or target | Conflict before provider mutation |
384
+ | Enable pending, then disable requested | Scope remains owned by enable; disable conflicts |
385
+ | Stripe applies enable, component finish fails | Replay verifies provider state and finishes the original version |
386
+ | Old action finishes after another version | No newer setting or ledger update |
387
+ | Recovery needs 101 claims at batch limit 100 | Two bounded calls, distinct reservation IDs, one sealed target |
388
+ | Empty reservation or already finished group replay | No reused batch identity, extra collection or release |
389
+ | Two recovery groups compete for one scope | One active boundary; loser receives scope_busy |
390
+ | Cancellation races a successful provider call | Receipt reconciled; successful money effect retained |
391
+ | Queue retry occurs after provider key retention expires | Verify full authoritative receipts or hold unknown; never blind recreate |
392
+ | Migration page retries or conflicts | Exact replay is a no-op; conflict rolls back the page |
393
+ | Migration pauses starts with an in-flight provider result | New effects stay paused while original receipt reconciliation and finish remain authorized |
394
+ | Legacy funding is enabled with original card settings | Import preserves card restoration and pending provider key |
395
+ | Definition upgrade resumes an old operation | Compatible old definition runs or explicit hold; no effect replay |
396
+ | Provider history is partial, multi-funded or foreign | Explicit unavailable/rejected result; no inferred zero or guessed source |
397
+
398
+ Run `pnpm run check:all` for every implementation handoff. Preserve all gate
399
+ floors and budgets. Put sanitized logs/results directly in each ready PR and
400
+ report unavailable provider/deployment checks honestly. Unit mocks cannot
401
+ establish live Stripe eligibility or nested deployment compatibility. Require
402
+ sandbox integration evidence for those claims before consumer cutover.
403
+
404
+ ## Current source anchors
405
+
406
+ - [Funding provider protocol](../../src/client/billing/balanceFunding.ts) and
407
+ [example pending-operation mutations](../../example/convex/storeBalance/funding/internal/mutations.ts).
408
+ - [Recovery client](../../src/client/costRecovery.ts),
409
+ [reservation and sealing mutations](../../src/component/costRecovery/reservations.ts),
410
+ [sale preparation](../../example/convex/settlement/recovery.ts) and
411
+ [invoice preparation](../../example/convex/sellerCosts/recoveryInvoices/mutations.ts).
412
+ - [Settlement execution](../../src/client/settlement/execution.ts) and
413
+ [existing public settlement contract](../settlement.md).
414
+ - [Component environment configuration](../../src/component/convex.config.ts) and
415
+ [existing read/provider contracts](../read-contracts.md).
@@ -0,0 +1,200 @@
1
+ # Nested durable execution
2
+
3
+ **Compatibility change:** consumers using Convex below 1.46.0 must upgrade
4
+ before adopting this change. The previous peer range started at 1.29.3. Public
5
+ BetterStripe methods are preserved, but that older runtime range is no longer
6
+ claimed as supported. This change does not publish a release or alter a tag.
7
+
8
+ BetterStripe installs Workflow 0.4.10, which installs Workpool 0.4.14 and Batch
9
+ Worker 0.2.2. Convex 1.46.0 or newer and convex-helpers 0.1.127 or newer are
10
+ required by these packages. BetterStripe's Convex peer minimum is now 1.46.0.
11
+ The direct Workflow and Workpool dependencies are pinned so library behavior
12
+ changes require an explicit package update and verification.
13
+
14
+ `src/component/durableExecution/runtime.ts` exports `executionWorkflow`, bound
15
+ to the generated `components.workflow` reference. Its pool runs at most two
16
+ steps concurrently and does not retry actions automatically. Domain workflows
17
+ can define versioned internal mutations using this manager. The initial runtime spike added no public financial endpoints. The merged
18
+ domain workflows now expose the APIs described in the [release handoff](../release-handoff.md).
19
+ Existing scheduled jobs are not migrated automatically.
20
+
21
+ Workflow already schedules its handler and steps through its own Workpool.
22
+ Do not enqueue those steps in another pool. A standalone Workpool is appropriate
23
+ for an independent job that needs bounded concurrency and a completion callback
24
+ but has no multi-step journal or replay dependency. The tests install an extra
25
+ pool only to compare that execution model. Production installs one Workflow
26
+ child, with its own pool, and no sibling pool.
27
+
28
+ ## Version comparison
29
+
30
+ The installed package manifests declare these peer requirements:
31
+
32
+ | Package | Convex peer | Workpool peer |
33
+ | --------------- | ----------- | -------------------- |
34
+ | Workflow 0.4.10 | `^1.46.0` | `^0.4.4` |
35
+ | Workpool 0.4.14 | `^1.36.1` | n/a |
36
+ | Workflow 0.4.4 | `^1.36.1` | `^0.4.4` |
37
+ | Workflow 0.3.12 | `^1.31.7` | `^0.3.0 \|\| ^0.4.0` |
38
+ | Workflow 0.3.4 | `^1.24.8` | `^0.3.0` |
39
+ | Workpool 0.3.1 | `^1.24.8` | n/a |
40
+
41
+ Workflow 0.3.4 with Workpool 0.3.1 could accept the old Convex minimum by
42
+ manifest alone. It does not provide the selective failed-step restart required
43
+ by the saved-receipt replay scenario. Its published test registration also
44
+ registers Workpool at the root rather than beneath the named Workflow. The
45
+ [Workflow changelog](https://github.com/get-convex/workflow/blob/main/CHANGELOG.md)
46
+ records selective restart in 0.3.6 and corrected nested registration in 0.3.9;
47
+ those versions require Convex 1.31.7 or newer. Consequently, the older pair does
48
+ not preserve the required semantics and verifiable nested test boundary.
49
+
50
+ Choose the current 0.4.10/0.4.14 pair, matching the repository's installed Convex
51
+ 1.46.0. This also includes subsequent workflow argument-validation, cleanup and
52
+ test-isolation fixes. The [Workpool changelog](https://github.com/get-convex/workpool/blob/main/CHANGELOG.md)
53
+ records newer recovery-race and bounded batch-processing fixes. Older manifests
54
+ do not establish an ongoing maintainer support guarantee; no such guarantee is
55
+ assumed here. The comparison uses published package manifests/source and the
56
+ maintainers' changelogs, not a claim that old providers were live-tested.
57
+
58
+ ## Credentials and provider versions
59
+
60
+ Use a host internal action as the provider boundary. Create its serializable
61
+ reference with `createFunctionHandle` in an authorized host mutation or action.
62
+ Pass that handle and the nonsecret operation scope to the component. The action
63
+ creates the Stripe SDK from its runtime environment and the operation's explicit
64
+ API version, then returns a validated, nonsecret receipt. Pass the saved Stripe
65
+ account or context explicitly to every provider request. Host authorization and
66
+ server-derived scope checks must run before creating an operation or selecting
67
+ the provider action.
68
+
69
+ Workflow handlers run in a deterministic environment that disables direct
70
+ access to `process`, `fetch` and cryptography. Never read credentials in a
71
+ workflow handler, and never copy secrets into workflow arguments, action
72
+ arguments, journals, completion context, results, status or logs. Persist only
73
+ provider identities, phase keys, versions and validated receipts needed for
74
+ reconciliation. Provider actions must redact their errors too; Workflow records
75
+ failure text. The test transport records whether authorization matched, never
76
+ its value.
77
+
78
+ The component already declares and receives its Stripe environment variables.
79
+ A local push and `core/queries:getStripeMode` invocation confirmed that declared
80
+ environment forwarding works. This does not grant a workflow handler environment
81
+ access. Host action handles provide an explicit, tested credential boundary and
82
+ also let the host select supported provider configuration without placing keys
83
+ in durable state.
84
+
85
+ ## Replay, retries and cancellation
86
+
87
+ A successful action step has a saved result. When a later persistence step
88
+ fails, restart from that failed step, preserving the earlier provider journal.
89
+ The integration test restarts from the persistence mutation reference and proves
90
+ that the provider action runs once while persistence runs twice. A default
91
+ restart preserves recorded failed steps as well; it does not erase their
92
+ failure. Never restart from step zero to recover a financial operation.
93
+
94
+ This journal behavior does not guarantee exactly-once Stripe effects. If Stripe
95
+ applies a request but the action result is lost before journaling, the operation
96
+ owner must reconcile provider state and reuse its saved phase key. An execution
97
+ failure does not establish a rejected financial outcome. Unknown effects retain
98
+ reservations until reconciled. The runtime deliberately has no generic automatic
99
+ provider-write retry policy. Provider action implementations must also explicitly
100
+ configure the Stripe SDK network retry setting for their phase. The fixture uses
101
+ `maxNetworkRetries: 0`; disabling Workflow retries alone would not disable the
102
+ SDK's own retries. Its ambiguous transport test loses the response after the
103
+ request and asserts only one SDK transport attempt.
104
+
105
+ The explicit two-attempt retry test uses a read-only Stripe operation and an
106
+ opt-in step policy. It proves the configured attempt cap, not permission to retry
107
+ financial writes. Domain retry adapters must follow the financial readiness
108
+ contract: only a retryable `not_ready` result may trigger a capped retry. A thrown
109
+ provider error or unknown effect requires reconciliation, not blind re-execution.
110
+
111
+ Cancellation can stop future steps but cannot abort a provider call already in
112
+ flight. The cancellation-race test releases an in-flight provider action after
113
+ canceling the workflow; the transport completes, workflow status stays canceled,
114
+ and the later persistence step does not run. Domain operation state must record
115
+ and reconcile that possible effect. Workflow cancellation is neither a refund
116
+ nor proof that no money moved.
117
+
118
+ Completion callbacks record success, failure or cancellation. A restart can
119
+ produce another completion for the new execution generation. Callbacks must
120
+ therefore compare operation identity/version and apply financial changes
121
+ idempotently. Execution cleanup removes Workflow history, not financial receipts
122
+ or operation-key bindings. The test keeps its separate receipt and completion
123
+ records after cleaning execution history. Production retention must wait until
124
+ operation reconciliation and the domain's retention policy permit cleanup.
125
+
126
+ ## Definition versions and retention limits
127
+
128
+ Workflow does not pin an old JavaScript implementation automatically. Store a
129
+ positive definition version and the immutable provider/API-version snapshot in
130
+ the domain operation. Route resumes to compatible, retained internal definitions
131
+ such as `applyV1`; keep those exports executable while their operations can
132
+ resume. Keep host provider action exports and compatible receipt schemas for the
133
+ same lifetime: a function handle does not pin an old action implementation. Do
134
+ not rewrite an old definition to use a new API version or phase key.
135
+ The changed-definition test changes action arguments during replay and verifies
136
+ that Workflow refuses the journal mismatch before making another provider call.
137
+ The original API version and receipt remain in saved history.
138
+
139
+ An incompatible definition must leave the financial operation held for
140
+ reconciliation. Its failed execution status alone does not release reservations
141
+ or permit a fresh provider attempt. Cleanup also cannot make the old provider
142
+ effect safe to repeat: the retention test proves restart fails after cleanup,
143
+ while its separate receipt and completion records remain. Once journal retention
144
+ expires, the domain must use retained operation/receipt evidence and provider
145
+ reconciliation, not recreate the workflow and replay effects. The shared runtime
146
+ binding supplies neither domain identity/version guards nor retention policy;
147
+ those remain mandatory work in each financial workflow cutover.
148
+
149
+ ## Reproducing verification
150
+
151
+ Run the focused behavioral suite:
152
+
153
+ ```sh
154
+ VITEST_MAX_WORKERS=1 pnpm exec vitest run src/component/durableExecution/composition.test.ts
155
+ ```
156
+
157
+ It uses the published Workflow, Workpool and Batch Worker test registrations
158
+ nested under a BetterStripe component. Host action references cross the component
159
+ boundary through `createFunctionHandle`. The real Stripe SDK constructs requests;
160
+ only HTTP transport is replaced. Tests cover explicit version/account headers,
161
+ credential isolation from durable state, saved-receipt replay, configured retry
162
+ limits, unknown effects, cross-workflow concurrency, cancellation races,
163
+ completion retention, and an independent queue.
164
+
165
+ Use a dedicated development deployment or a verified, isolated project-local
166
+ anonymous deployment for installation checks. Before any `dev`, environment or
167
+ `run` command, inspect the selected project-local configuration and confirm its
168
+ identity, data ownership and unused ports. A fresh directory alone is not proof
169
+ of isolation: the CLI can fall back to shared home-directory anonymous state.
170
+ Do not use generic `CONVEX_AGENT_MODE=anonymous` as an isolation guarantee.
171
+
172
+ For an already verified project-local deployment, keep the explicit deployment
173
+ selector in a private env file and supply it on supported commands. Run commands
174
+ from the owning app directory. For example, after verification:
175
+
176
+ ```sh
177
+ node node_modules/convex/bin/main.js dev --env-file /absolute/private/local.env --once --typecheck disable --local-cloud-port 3260 --local-site-port 3261
178
+ # Only on that verified fixture deployment, set a dummy key if required:
179
+ node node_modules/convex/bin/main.js env set STRIPE_SECRET_KEY sk_test_composition_fixture --env-file /absolute/private/local.env
180
+ node node_modules/convex/bin/main.js run --component betterStripe core/queries:getStripeMode '{}' --env-file /absolute/private/local.env
181
+ ```
182
+
183
+ Choose unused ports. Do not weaken a schema, clear unrelated data, or reuse a
184
+ shared deployment to make an installation check pass. The original local spike
185
+ installed `betterStripe`, `betterStripe/workflow`,
186
+ `betterStripe/workflow/workpool` and
187
+ `betterStripe/workflow/workpool/batchWorker`, then returned `"test"` for mode.
188
+
189
+ Generate references with `pnpm run codegen` against that local deployment. Do
190
+ not edit generated files by hand. Run `pnpm run check:all` before handoff.
191
+
192
+ The original local push proved nested installation and generated references;
193
+ the runtime harness proved persisted test-state execution. Later domain and
194
+ cross-domain checks added local-backend restart and reconciliation evidence.
195
+ See the [release handoff](../release-handoff.md#verification-and-release) for
196
+ those scopes. Synthetic provider transports and dummy keys do not establish live
197
+ Stripe eligibility or actual money movement. Live provider reconciliation and
198
+ production rollout require separately authorized acceptance. None of these
199
+ checks establishes exactly-once external effects or automatically completes a
200
+ financial migration.