@fantastic.dev/better-stripe 0.45.1 → 0.45.2

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.
@@ -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.
@@ -0,0 +1,69 @@
1
+ # Durable recovery groups
2
+
3
+ `stripe.costRecovery.startGroup` runs an already prepared and sealed recovery
4
+ group. The host authorizes the account, scope, currency, source and economic
5
+ allocation before starting. Settlement allocations must include the group's
6
+ exact signed recovery adjustment. The component pins the entire allocation and
7
+ rejects a different allocation, policy, callback, provider handle or API version
8
+ on replay. One settlement source can belong to only one workflow operation.
9
+ `requestKey` is an immutable identity within one BetterStripe component;
10
+ different callers must namespace their keys.
11
+
12
+ The host supplies an internal action reference as `provider`. Its validators
13
+ must accept `RecoveryProviderRequest`. Inside that action, call
14
+ `stripe.costRecovery.executeGroupProvider(ctx, args, {
15
+ stripeSecretKey: process.env.STRIPE_SECRET_KEY! })`. This options object exists
16
+ only during action execution. Never place credentials in `startGroup`, workflow
17
+ arguments, operation records, callback arguments or logs. The adapter constructs
18
+ a fresh Stripe client using the pinned API version and zero automatic network
19
+ retries. Existing `attachInvoice`, `reconcileInvoice`, settlement execution and
20
+ reserve/seal/finish APIs retain their behavior.
21
+
22
+ The provider action receives only a scoped operation reference, phase and pinned
23
+ versions. The adapter reads the immutable saved inputs and verifies an active
24
+ persisted dispatch before contacting Stripe. Its receipt echoes those references
25
+ and versions plus the source ID. A component bridge rejects unknown fields or
26
+ identity mismatches and sanitizes exceptions before returning a receipt to the
27
+ Workflow journal. It never persists provider response objects or messages.
28
+
29
+ Settlement execution reuses the existing transfer and affiliate allocation
30
+ ledger and its original idempotency keys. Reconciliation reads bounded transfer
31
+ history, mirrors verified transfers and confirms earnings without creating
32
+ missing transfers. Invoice execution reuses the original recovery invoice-item
33
+ key and item binding protocol. Invoice history is capped at 10,000 items;
34
+ incomplete history cannot authorize another write. The host still owns invoice
35
+ creation, finalization/payment policy, seller eligibility and reporting.
36
+ `releaseUncollectible` is an explicit immutable policy; paid invoices collect,
37
+ void invoices release, and uncollectible invoices release only when authorized.
38
+ Other invoice states retain the reservation.
39
+
40
+ `getGroupOperation`, `resumeGroup` and `requestGroupCancel` require the full saved
41
+ scope, operation ID and version. The SDK projects these fields from returned
42
+ statuses before invoking strict component validators. Only known readiness
43
+ observations receive automatic retries, at most `maxAttempts` (1–20) with the
44
+ explicit bounded `retryDelayMs`. An unknown provider effect waits for an explicit
45
+ `resumeGroup`, which performs reconciliation only. Missing transfers, ambiguous
46
+ history or failed reads never trigger new money writes or release reservations.
47
+
48
+ Each Workflow segment has at most 20 provider observations and 20 finish batches
49
+ (of at most 10 reservation operations each). `resumeGroup` continues an exhausted
50
+ or infrastructure-failed segment under the original operation and money keys.
51
+ A persisted verified receipt takes priority: continuation finishes the ledger
52
+ without contacting the provider. Failed receipt/finish/completion database steps
53
+ restart from the failed step while retaining earlier journaled results. No new
54
+ financial execution identity is allocated during resume.
55
+
56
+ An optional internal mutation `completion` runs after successful ledger finish.
57
+ It receives `RecoveryOperationStatus`, must perform database work only and must
58
+ use the operation ID/version as its projection identity. Its database changes
59
+ and the operation's completed status commit atomically. A callback failure can
60
+ be resumed without repeating the provider effect. It is a success callback;
61
+ cancellation does not invoke it.
62
+
63
+ Cancellation before provider dispatch stops execution and keeps the sealed
64
+ reservation. Cancellation during an action cannot undo the provider effect: a
65
+ verified success still completes collection and the callback, with
66
+ `cancelRequested: true`. An uncertain in-flight result keeps the reservation and
67
+ requires reconciliation. A canceled status therefore never means funds were
68
+ released. Hosts must retire their legacy orchestration for a group before using
69
+ this workflow; mixing independent executors defeats ownership of the operation.
@@ -0,0 +1,114 @@
1
+ # Durable balance-funding state
2
+
3
+ The `balanceFunding` component domain implements the persistence boundary from
4
+ [the extraction contract](architecture/component-extraction.md). It stores opaque
5
+ host scope, verified original payment settings, consent reference and timestamp,
6
+ provider API version, operation identity/version, phase keys, receipts and pending
7
+ target. Host code authenticates callers, authorizes the account/subscription,
8
+ captures consent and selects policy before invoking any component method.
9
+
10
+ This domain does not call Stripe or run a workflow. Provider orchestration and
11
+ preview-version opt-in remain the funding workflow workstream. No credentials
12
+ belong in scope keys, consent references, provider receipts, durable arguments or
13
+ operation state. The component's tables are an execution journal, not a money
14
+ ledger.
15
+
16
+ ## Preparation and immutable intent
17
+
18
+ The low-level `mutations.prepare` takes the verified original settings in
19
+ `preparation` without a balance payment-method ID, plus `accountId`, `scopeKey`,
20
+ `consent: true`, `consentAt`, `consentReference`, `providerApiVersion` and
21
+ `requestKey`. The runtime must obtain these settings before any create/attach
22
+ write. This persists a pending preparation operation and stable `providerKey`
23
+ and create/attach phase keys. The runtime never recaptures original settings
24
+ from an already-enabled subscription.
25
+
26
+ `finishPreparation` accepts the complete operation reference, verified preparation
27
+ including the new payment-method ID, and the same provider API version. It checks
28
+ the captured restoration settings and active version before saving the result.
29
+ Null and empty restoration values remain distinct. Exact completion is idempotent;
30
+ a contradictory result rejects. A canceled or stale operation cannot finish.
31
+
32
+ The host-facing preparation lookup is `queries.getPreparation`: pass account,
33
+ scope, subscription, operation ID and version. Only a succeeded preparation
34
+ operation returns `status: "prepared"` and its original preparation ID. Pending,
35
+ running, unknown, failed and canceled results expose only operation identity and state,
36
+ with an optional safe failure code.
37
+ Foreign or contradictory bindings return an explicit unavailable outcome. Missing
38
+ operations return null, which does not authorize another provider effect. Recover
39
+ a lost prepare response by replaying its original public request key. Before any
40
+ provider/settings/consent-time recapture, call `findPreparationOperation` with
41
+ account, scope, subscription, request key, API version and `consent: true`.
42
+ This read-only lookup verifies the saved prepare-kind and all those bindings,
43
+ returning only safe operation state/reference or conflict/null. Then call
44
+ `getPreparation` for that same operation. Unknown and failed requests recover
45
+ the original identity without exposing restoration data or phase keys. Null is
46
+ not proof of no provider effect or permission to create a replacement. A new key
47
+ never permits recapturing already-enabled settings or replacing unresolved work.
48
+ Exact low-level prepare snapshots, including consent time, remain immutable.
49
+
50
+ ## Apply, inspect and cancel
51
+
52
+ `begin` accepts the saved preparation ID, account/scope, desired `enabled`,
53
+ explicit enable consent and a request key. New request keys bind the full payload;
54
+ replaying one returns the original result even after completion. A changed payload
55
+ conflicts. Same-target pending intents reuse the active operation; opposite targets
56
+ conflict. A scope alias cannot acquire a second preparation or evade the
57
+ account/subscription boundary. New versions are positive safe integers.
58
+
59
+ `start` transitions pending work to running before provider execution. Repeated
60
+ start of running or unknown work does not establish permission to repeat an effect.
61
+ `markUnknown` retains the active claim when the provider outcome is uncertain.
62
+ `finish` checks operation identity, version, target, account/subscription, API
63
+ version and exact observed payment settings before updating enabled state.
64
+ A repeated old completion returns its original receipt without changing a newer
65
+ setting. Provider reconciliation remains necessary after transport uncertainty.
66
+
67
+ `requestCancel` cancels unstarted work and releases its claim transactionally.
68
+ For running/unknown work it records `cancelRequested` and retains the claim until
69
+ the original provider result is reconciled. A successful effect remains succeeded
70
+ even when cancellation was requested. Cancellation never restores payment settings
71
+ or reverses a provider effect by itself.
72
+
73
+ `getOperation` returns safe identity/state/cancellation fields. The server-only
74
+ `readPreparation` and `inspectOperation` queries return restoration data or phase
75
+ keys for trusted provider actions. They require the saved account, scope and
76
+ subscription; operation inspection also requires operation ID/version. Never
77
+ forward those raw records or receipts to browser-facing queries. Status/lookup
78
+ results contain no restoration settings or credentials.
79
+
80
+ `failBeforeStart` records a terminal `failed` state only while the intent is still
81
+ pending, before provider execution begins. It accepts only `invalid_scope`,
82
+ `unsupported_source` or `policy_invalid`, never a provider message. The same
83
+ request replay retains the failed operation; a fresh intent gets a new version
84
+ and phase keys. Running and unknown operations cannot use this transition or
85
+ release their claim. It does not classify provider exceptions or prove no effect
86
+ after provider execution has begun; those paths require reconciliation. Status
87
+ and preparation lookup expose the safe code without restoration data.
88
+
89
+ ## Import and migration pause
90
+
91
+ `savePreparation` is for verified complete legacy preparations. Exact replay
92
+ returns the existing ID; changed restoration, scope, consent or API version
93
+ rejects. It does not overwrite existing records.
94
+
95
+ `importPreparation` also preserves the legacy enabled state, operation version,
96
+ pending target and exact provider base key. Its source key binds the complete
97
+ import payload. Exact replay remains a no-op after the imported operation has
98
+ advanced; changed imports reject transactionally. A different source cannot
99
+ replace an existing account/subscription record.
100
+
101
+ Imported pending operations start unknown and paused. Pending preparation imports
102
+ use `pending.kind: "prepare"` and may omit the balance payment-method ID. Preserve
103
+ `example_balance_prepare_${subscriptionId}` for their base key and its create/
104
+ attach suffixes. Pending apply imports preserve
105
+ `example_balance_${subscriptionId}_${version}` and enable/disable suffixes. Never
106
+ replace a legacy key with the new-operation namespace.
107
+
108
+ `setStartsPaused` blocks new intents and pending-to-running transitions while
109
+ keeping original status, cancellation, receipt reconciliation and completion
110
+ available. Imports begin paused; resume starts only after stopping the old writer
111
+ and checking the imported state. A paused replay can recover an existing intent,
112
+ but cannot authorize a new provider effect. Pause old starts rather than disabling
113
+ finish handlers needed to reconcile in-flight receipts. Rollback requires one
114
+ writer and verified state; reverting code alone cannot undo provider effects.
@@ -0,0 +1,53 @@
1
+ # Durable balance funding
2
+
3
+ `BetterStripe.balanceFundingWorkflow` adds component-owned preparation and apply workflows. The existing `prepareBalanceFunding` and `setBalanceFunding` methods remain available. The new interface requires explicit `STRIPE_CUSTOMER_PREVIEW_API_VERSION` configuration; the provider action checks the actual Stripe SDK version against the immutable operation snapshot before admitting a provider phase. Stripe still determines live account and preview eligibility.
4
+
5
+ The host authorizes the account, subscription and opaque scope, records consent, and supplies an internal provider action reference. Construct the Stripe client inside that action using the host's runtime secret. The component stores only the function handle, immutable scope/API/definition versions, phase keys and allowlisted receipts. Never put keys, raw provider objects, raw exceptions or restoration settings into workflow arguments or completion context.
6
+
7
+ ```ts
8
+ import {
9
+ BetterStripe,
10
+ STRIPE_CUSTOMER_PREVIEW_API_VERSION,
11
+ } from "@fantastic.dev/better-stripe";
12
+
13
+ // Host internal action. Instantiate BetterStripe at execution, not in durable args.
14
+ const stripe = () =>
15
+ new BetterStripe(components.betterStripe, {
16
+ STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
17
+ stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION,
18
+ });
19
+
20
+ // The action's args validator must match FundingProviderPhaseOptions:
21
+ // accountId, scopeKey, operationId, version, stripeSubscriptionId,
22
+ // providerApiVersion, definitionVersion, phase (create|attach|apply), providerKey.
23
+ // Use ordinary string validators for component operation IDs in the host.
24
+ export const fundingProvider = internalAction({
25
+ args: providerPhaseArgs,
26
+ handler: (ctx, args) =>
27
+ stripe().balanceFundingWorkflow.executeProviderPhase(ctx, args),
28
+ });
29
+
30
+ // Inside an authorized host action:
31
+ const result = await stripe().balanceFundingWorkflow.prepare(ctx, {
32
+ accountId,
33
+ scopeKey,
34
+ stripeSubscriptionId,
35
+ requestKey,
36
+ consent: true,
37
+ consentAt,
38
+ consentReference,
39
+ providerAction: internal.billing.fundingProvider,
40
+ });
41
+ ```
42
+
43
+ `prepare` recovers the original public request before reading provider settings again. A new request for an existing canonical preparation uses its original consent and restoration snapshot. Capture performs read-only provider calls; the component persists that snapshot before scheduling create or attach. Duplicate requests join the bound workflow. A successful preparation does not enable funding: use the existing safe `getPreparation` query to obtain a verified preparation ID, then call `apply(ctx, { accountId, scopeKey, stripeSubscriptionId, preparationId, enabled, consent, requestKey, providerAction })`. Enabling requires consent. Disabling restores the persisted original payment method and nullable payment-method-type settings, never current subscription prices or host metadata.
44
+
45
+ `inspect(ctx, operationReference)` returns only scoped operation state, version and cancellation state. `resume` and `cancel` accept the same account/scope/subscription/operation/version reference. These control paths do not instantiate Stripe or require its secret. The host must authorize these operations before calling them; component APIs are server capabilities, not browser authorization policies.
46
+
47
+ Every provider phase has one atomic dispatch claim and its original idempotency key. SDK write retries and Workflow action retries are disabled. A lost create response with no verified payment-method ID remains held: ordinary PaymentMethod reads cannot prove which unattached resource was created. Resume never creates another method in that state. Unknown attachment or apply outcomes use known-ID, read-only provider reconciliation; an inconclusive readback stays held and does not repeat the write. Conflicting targets cannot replace the active operation or its original restoration settings.
48
+
49
+ Positive receipts are persisted before the bridge returns and again in a separate workflow mutation. If storage fails after provider success, retained, scope-bound provider journal receipts can restore canonical evidence. Resume restarts only a known failed step or finishes from complete verified receipts; it does not repeat completed provider effects. Cancellation is a request, not proof that an in-flight provider call stopped. It retains uncertain claims and restoration data; known positive receipts may still be reconciled and finished afterward.
50
+
51
+ Operations pin `balance-funding/v1` and their original provider API version. A changed definition or API version is held rather than replayed. Compatible old definitions and pinned host provider configuration must remain available while operations are incomplete. History reads are bounded and require completeness. Cleaned, missing or incompatible history cannot authorize a new workflow or effect; retained operation receipts are never deleted by this interface. Do not clean workflow history while uncertain operations still need reconciliation.
52
+
53
+ This proves durable local orchestration and conservative replay boundaries, not exactly-once provider effects. Tests use the actual nested Workflow/Workpool components and real Stripe SDK transport with synthetic responses. The local installation uses a dummy key and does not establish live Stripe eligibility or perform live provider writes.
@@ -0,0 +1,94 @@
1
+ # Example balance-funding cutover
2
+
3
+ The cutover moves the example's financial preparation and execution into the installed
4
+ BetterStripe component. `storeBalanceRequests` stores host consent intents and
5
+ component references, not provider execution history. Queueing and initial
6
+ scheduling happen in one mutation. A ten-minute observer watchdog makes abandoned pending intents held and
7
+ retryable. Watchdogs are fenced by an observation epoch; an obsolete timeout
8
+ cannot hold a newer retry. Same-target retries reschedule even an existing pending
9
+ intent and retain its original request and financial operation.
10
+ Provider writes and uncertain outcomes belong to the component workflow.
11
+
12
+ The example still enforces sandbox mode, seller role, current account and plan,
13
+ and the subscription's `storeBilling` and `sellerId` metadata. It uses demo
14
+ personas. Production hosts must derive the seller from an authenticated session.
15
+ No migration action runs automatically on deploy. Starting a payment-source change
16
+ migrates that seller's existing legacy record first, if one exists.
17
+
18
+ ## Compatibility and verification
19
+
20
+ Keep the old `storeBalanceFunding` rows and original host functions throughout
21
+ the compatibility window. The importer preserves original method/type restoration
22
+ settings, including `null` versus an empty list, consent timestamp, operation
23
+ version and provider keys. It pins the legacy `2026-09-30.preview` API version.
24
+ It never prepares again from a subscription whose settings have already changed.
25
+
26
+ Before import, old starts are paused. A late old finish is allowed before the
27
+ snapshot is imported; the snapshot hash then changes and must be read again.
28
+ After import, old finishes are rejected and must reconcile the component receipt.
29
+ Unknown legacy operations have no workflow journal. First stop and drain every legacy worker that could still dispatch its old
30
+ provider key, then record an operator audit reference for that exact source
31
+ snapshot. Only after this attestation can scoped, verified Stripe readback finish
32
+ the operation. Matching target settings alone do not prove an old worker stopped. Missing, mismatched or ambiguous evidence stays held;
33
+ it does not start another workflow or provider write.
34
+
35
+ The action verifies original account, subscription metadata and payment-method
36
+ ownership. Import and its checkpoint commit together, with the source hash and
37
+ current seller binding checked again. Replacement accounts or subscriptions are
38
+ held for explicit review. Original source rows are never deleted by this adapter.
39
+
40
+ For a pending legacy row, pause and read its `fundingId` and `snapshot` using
41
+ `storeBalance/funding/internal/migration:pause`. After independently stopping and
42
+ draining old workers, call
43
+ `storeBalance/funding/internal/quiescence:confirm` with those values and a bounded
44
+ `reference` identifying the operational audit. This is a trusted operator
45
+ attestation, not an automated proof. Do not confirm it while an old provider call
46
+ could still complete. Re-run the seller migration or backfill after confirmation.
47
+ A changed legacy snapshot invalidates the attestation.
48
+
49
+ ## Bounded backfill
50
+
51
+ Use an isolated sandbox first. Run these internal functions with the intended
52
+ example deployment selected. Do not point this runbook at another app's database.
53
+ An operator needs the deployment's admin authorization.
54
+
55
+ ```sh
56
+ pnpm --filter ./example exec convex run storeBalance/backfill/mutations:start '{}'
57
+ # Copy the returned runId into each following command.
58
+ pnpm --filter ./example exec convex run storeBalance/backfill/actions:step '{"runId":"..."}'
59
+ pnpm --filter ./example exec convex run storeBalance/backfill/queries:state '{"runId":"..."}'
60
+ ```
61
+
62
+ Starting a run fences all legacy starts before scanning. Each `step` processes at
63
+ most ten rows. The reserved page is persisted before provider reads; interrupted
64
+ actions replay it. Acknowledgements use the saved cursor and count each page once.
65
+ Counts are derived from current scoped component state. Repeat `step` while the
66
+ run is `running`. `verified` means `scanned === active` and `held === 0` at the
67
+ checkpoint. It is not proof that live Stripe preview eligibility exists or that
68
+ later external changes cannot occur.
69
+
70
+ A run with unresolved rows finishes as `held`. Reconcile those original records,
71
+ then call `start` with `{"rescan":true}` to audit all rows again. Do not delete
72
+ source records or disable compatibility readers solely because a scan ended.
73
+ Check pending component operations and actual Stripe settings before retirement.
74
+ The component remains the sole financial writer after activation; a repeated
75
+ scan reads its current verified state rather than restoring the old enabled flag.
76
+
77
+ ## Rollback
78
+
79
+ Before a global run starts, `funding/internal/migration:rollback` can restore the
80
+ legacy writer for one record only if its original source hash, enabled state and
81
+ operation version still match, with no active component operation. It pauses
82
+ component starts before releasing the old writer. This is a data rollback, not a
83
+ Stripe reversal.
84
+
85
+ After new component operations or a global run, that shortcut is rejected. Pause
86
+ starts, reconcile pending provider outcomes and explicitly verify a reverse
87
+ mapping before a reviewed deployment rollback. Never recreate old operation
88
+ versions or reuse an old provider key for a different effect. Retain component
89
+ history and original source records until the compatibility audit is complete.
90
+
91
+ The sandbox renewal retry reads only verified, enabled component funding with no
92
+ active operation and no paused starts. It cannot collect using a stale legacy
93
+ payment-method record. An insufficient balance does not authorize card fallback;
94
+ that remains an explicit seller recovery choice.
@@ -0,0 +1,21 @@
1
+ # Example recovery cutover
2
+
3
+ The example keeps seller eligibility, original catalog ownership, affiliate allocation, store plan commission, webhook routing and reporting projections. The component owns reservation preparation, provider execution, retries, receipt persistence, collection and processing-cost rollback.
4
+
5
+ Settlement and plan-invoice entry points enqueue component recovery workflows. A provider action reads its credentials at execution time. The host `recoveryJobs` table contains routing and operation references only; component claims and reservations remain the financial ledger. `sellerCosts.workflow.queries.list` exposes bounded operation status, and `blockedSummary` returns at most 100 blocked jobs with an explicit `hasMore` flag. These queries follow the example's existing selected-seller authorization model.
6
+
7
+ A settlement with no owned recovery reservation retains the existing direct payout policy, including when another invoice owns the active recovery group. An owned reservation uses the durable workflow. Replayed events resume the same operation; a saved receipt can finish a failed database projection without another provider call. Processing-cost reconciliation supplies the host's explicit deficit policy, independently pins main and rollback claim revisions, and adopts an eligible legacy claim and its host marker in the same transaction as the final projection.
8
+
9
+ ## Legacy records
10
+
11
+ Existing sealed, unattempted groups can start the new workflow. Existing collected settlement groups require exact transfer mirrors for every positive allocation leg before the host marks the sale settled. A partially collecting settlement group uses those same verified mirrors and finishes one bounded database batch per invocation. It never creates a new transfer or provider idempotency key.
12
+
13
+ Invoice compatibility uses `costRecovery.verifyInvoiceReceipt`. This read-only method requires the previously bound item, exact account/scope/invoice/currency/amount bindings, one unambiguous item and complete history within five pages and 500 items. It uses GETs only and performs no item binding or financial mutation. Unknown, incomplete or malformed evidence leaves reservations held. A verified paid invoice can continue an already collecting group; a verified void invoice can continue an already releasing group. The host never switches the persisted direction because a later invoice was canceled. Each invocation finishes one bounded database batch and schedules another invocation if needed.
14
+
15
+ Legacy transfer attempts with no conclusive mirror, unmapped historical recovery amounts, and unknown in-flight groups stay blocked. Their status identifies `legacy_inflight_unknown`, `legacy_mapping_required` or `settlement_pending`. Operators must establish an explicit historical mapping and receipt before retrying. The cutover does not infer a collected group, forgive a claim, run a backfill, or release an unknown provider attempt. The legacy import helper retains its invoice and pending-settlement guards.
16
+
17
+ A refund before new settlement dispatch cancels the workflow and keeps the sealed reservation held. An in-flight refund also holds the reservation until the existing settlement is reconciled. Cancellation alone does not release financial reservations. These cases require explicit manual resolution when no verified completion exists. If a blocked cost observation was waiting for settlement, a verified settlement projection schedules reconciliation against the now-collected group.
18
+
19
+ ## Verification
20
+
21
+ Co-located tests run real nested component workflows and cover duplicate events, provider success followed by failed host projection, explicit resume, unknown attempts, original catalog ownership, cancellation, independent revision guards, legacy import/projection atomicity and observable blocked status. Eleven-reservation fixtures cover partially completed legacy settlement and invoice collections, release direction, replay and mismatched proof. Provider-boundary fixtures exercise the host adapters without live Stripe requests; separate package tests use the actual Stripe SDK transport to verify GET-only invoice proof, pagination caps and mismatches.
@@ -0,0 +1,23 @@
1
+ # Processing-cost reconciliation
2
+
3
+ `betterStripe.costRecovery.startProcessingCostReconciliation` observes provider costs and records a revised deficit in the existing recovery ledger. It never collects money itself. A host supplies authorization, an internal provider action, an explicit deficit policy, and optional internal import/projection mutations. Use `startRecoveryWorkflow` separately to collect the resulting ledger balance.
4
+
5
+ The immutable request binds account, scope, currency, claim key, original payment and gross, expected claim revision, policy, provider/API definition version, callback handles, and retry bounds. Reusing a request key with a changed binding returns `identity_changed`. A scoped payment retains one claim key. Original selling fee and verified provenance cannot change after the first completed observation. A changed authoritative claim revision returns `revision_changed`; a new host decision must use a new request and the newly read revision. Resume never refreshes it implicitly.
6
+
7
+ ## Provider action boundary
8
+
9
+ The host's internal action receives only the scoped operation reference and pinned versions. Call `betterStripe.costRecovery.observeProcessingCosts(ctx, request, { stripeSecretKey })` inside that action. Resolve credentials there; never put them in operation arguments, callback payloads, or Workflow state. The adapter creates a fresh Stripe client pinned to the saved API version, disables SDK network retries, and only issues GET requests. The component bridge validates a closed receipt before Workflow journals it. Provider bodies, metadata, credentials, and exception text are excluded.
10
+
11
+ Sale mode verifies the original invoice payment and historical price/product using the payment-source resolver. It does not infer provenance from metadata or a current subscription item. Explicit `invoice_recovery` mode requires a matching collected invoice recovery group and rollback group. It verifies the bound invoice item, the full invoice amount, one complete forward and inverse funding relationship, the original charge, and its fee. This mode carries invoice/item/funding provenance and does not invent a price or product.
12
+
13
+ Provider histories are limited to five pages and 500 items per collection. Repeated IDs, malformed pages, exhausted budgets, incomplete histories, partial funding, and ambiguous funding fail closed. Unknown and unavailable observations never write zero costs. Known `not_ready` outcomes retry up to `maxAttempts` (1–20); unknown outcomes stop for explicit host resume. Resume performs read-only observation again, using the same binding and revision guards.
14
+
15
+ ## Atomic adoption, rollback, and projections
16
+
17
+ Use `expectedRevision: -1` for an absent live claim. An optional import hook runs only when that claim is absent, after identity and revision checks. The host verifies its historical record and returns either `null` or an opening snapshot containing an immutable `operationKey`, `amountDue`, `collectedAmount`, and `revision`. The component imports through the existing opening-claim ledger and advances that revision once. A host migration marker written by the hook shares the transaction; hook or projection failure rolls back both host and component changes.
18
+
19
+ An optional rollback binds a collected original recovery group and its own `expectedRevision`. Its revision guard is independent of the main claim. The original group's funding identity and economics must match the observed payment before any import, claim, rollback, or funding-binding write. Refund/dispute principal adjusts the existing rollback claim. A later won dispute can reduce an already collected rollback obligation into a ledger credit without collecting or releasing funds again.
20
+
21
+ The projection callback is a database-only internal mutation invoked with the completed scoped result. It shares the transaction with both claim updates and completion. A failed projection leaves all changes unapplied. Resume restarts the failed apply step using its saved provider observation, without reading the provider again. Completed operation replay returns its original result even after newer operations have advanced the ledger; it never rewrites that newer state.
22
+
23
+ Host store eligibility, liability policy, economic allocation, reports, and migration cutover remain host decisions. The component stores generic operation metadata and uses existing claims, opening imports, balances, and rollback reservations for financial accounting.