Repository navigation
Description
Parent epic: #2116
Priority and sequence
P0 within the Context Engine epic · CE07. Required for the first two-song/two-brief checkpoint.
Customer journey
A customer starts enrichment with an authorized budget, sees actual charges, and does not get duplicate charges because a request was retried.
Customer value and architecture
Make costs predictable while reusing Recoup's existing billing system.
Scope
- Reuse shared AI-accounting infrastructure from Sites [Sites] Meter Sites operations with credit reservations and spending limits #2105 milestone 1; add context request/module/attempt attribution and stable settlement identifiers, not a new wallet.
- Authorize payer and per-request/pilot spend limits before paid calls, including concurrent modules; use reservations or equivalent serialized authorization and release unused capacity.
- Separate estimated/confirmed provider expense from customer debit and pricing-rule version; preserve costs of failed/unusable calls even where customer policy differs.
- Reconcile ambiguous charge acknowledgements without reinvoking providers. Charge or reuse cached results according to an explicit disclosed policy; no duplicate Flamingo endpoint-plus-workflow debit.
- Use existing model credit rules and existing analysis endpoint pricing where applicable. This ticket does not approve new prices, top-ups, unlimited spend or autonomous paid refresh.
Acceptance criteria
- Concurrent modules cannot exceed authorized spending except an explicitly measured/bounded provider exposure policy.
- Crash/retry/duplicate delivery creates at most one intended settlement per chargeable attempt; pending reconciliation is visible.
- Actual provider costs, customer debits, waived work and unknown/unconfirmed expense are reported separately.
- Request-total and pilot-total ceilings plus paid-but-unusable/failure/cancel treatment are configured before live testing.
- Shared AI-accounting milestone evidence is linked to [Sites] Meter Sites operations with credit reservations and spending limits #2105; unrelated hosting/session/top-up milestones do not block a bounded context pilot.
- Reused accepted analysis does not invoke or charge the analysis provider again.
Blocking dependencies
- [Context] Define context contracts, ownership rules and acceptance fixtures #2118
- [Context] Persist versioned sources, module results and context document lineage #2121
These are completion prerequisites, mirrored by native GitHub blocked-by links. Contracts, fixtures and independent scaffolding may begin earlier.
Execution gates
Hard gate before any paid adapter test or pilot. Fixture work can proceed earlier. Coordinate with #2105 AI-accounting milestone and existing song-analysis billing #2061; do not duplicate their billing primitives.
Validation
Reservation races, provider completion before crash, lost settlement acknowledgement, insufficient funds, paid failure, cancellation, cache reuse and nested endpoint charging tests.
Owning implementation
API existing wallet/usage ledger + context billing adapter
Delivery conventions
Shared API business logic serves HTTP, MCP and workers; clients do not duplicate it. Validate input with Zod and use the existing Supabase access layer. Database changes go through database-repository migrations and PRs. Use Vercel Workflows for new durable work. Reuse existing credits and record costs without exposing credentials or private traces. Every owning repository uses a feature branch and PR; distinguish fixture, local, merged and deployed verification.
October 8 accounting prerequisite audit
Inspected API main db4d9a54 and the existing #2105/#2061 requirements. ensureCreditsOrShortCircuit / checkCreditsAvailable perform a balance check, not a reservation. recordCreditDeduction later calls the atomic wallet-plus-usage RPC with a fresh event ID. Atomic debit/audit consistency does not establish retry-stable settlement or prevent multiple approved operations from concurrently exceeding a request/pilot budget. Music Flamingo already charges through its endpoint; Context must not add a duplicate debit around that call.
A read-only production function-name inventory found the existing deduct_credits and bigint deduct_credits_with_audit RPCs, with no reservation/settlement-named RPCs. This is metadata evidence, not proof that no differently named mechanism exists. No financial rows were read or mutated. No current main implementation of the shared reservation milestone was found in the inspected credits/Context paths. #2105 milestone 1 remains unproven.
One bounded reconciliation prerequisite is implemented in API #974, head 75197774: a missing completion acknowledgement propagates the existing reconciliation signal through the recorded planner instead of persisting a false failed node. Existing database logic already marks uncertain running attempts as unknown and preserves succeeded ones; the fix is the orchestration layer. 35 focused tests and full repository lint pass; CI/review pending. This is not a reservation, charge, retry or pilot activation.
Next accounting implementation must reuse the existing wallet and usage ledger, with stable operation/attempt settlement identity, atomic capacity reservation, request and pilot ceilings, and explicit unknown-expense reconciliation. Inspect monthly balance reset and existing auto-top-up interactions before defining available versus held balance. Do not enable Context paid flags or invent prices, refund rules or spending ceilings to bypass this prerequisite.
Reservation integration constraints from current code
The existing refill raises remaining_credits to a plan floor and advances its timestamp; auto-top-up decides from remaining_credits and can trigger off-session payment after a successful debit. Consequently, a hold must not be implemented as a temporary debit followed by a refund: that would look like consumption to these paths, could interact with refills, and could trigger purchases for work that later cancels.
Before activating reservations, define and implement one shared wallet invariant: confirmed balance, outstanding authorized holds, and spendable balance. Reserve/release/settle must serialize against the same billing-owner row. Existing debit callers and balance/refill writers must coexist with holds without silently spending reserved capacity or resurrecting spent credits. Hold creation/release must not call auto-top-up or write a usage charge. Only an explicitly authorized, finalized charge follows the existing billing policy; no new purchase behavior is approved.
Required fixture coverage includes refill with an outstanding hold, credit grant/top-up concurrent with settlement, old debit path concurrent with reservation, duplicate settlement acknowledgement, cancellation before dispatch versus uncertain provider completion, and held/settled totals across a single request and the pilot. Unknown provider exposure stays reserved or pending reconciliation under an explicit policy; do not blindly expire it into spendable credit. These are implementation constraints, not shipped functionality or approved numeric spending limits.
Stable charge receipt prerequisite — October 8, 7:29 PM ET
Database87, head dd34cf0d956e5b585a68b864f2936fd08b3b11fa, and API976, head 59c11a2f, implement an opt-in stable charge receipt using the existing wallet and usage log. Same billing owner/work key/normalized payload returns the saved receipt; changed input conflicts. Database tests exercise duplicate/concurrent delivery, rollback and denied browser roles. The API adapter preserves uncertainty without retrying or generating another charge identity. No live caller is changed or connected.
Read-only production schema inspection found that credits_usage has an integer primary key but no unique account index. The new function rejects zero/multiple wallet records and debits the exact locked row ID, instead of calling the legacy account-wide debit. This prevents this operation from debiting multiple records, but does not repair existing records, constrain future legacy creation, or complete wallet identity enforcement. Before reservations, resolve that shared ownership invariant explicitly; do not infer duplicate production rows from a missing constraint. No real balances were read or changed.
Validation: eleven real transaction tests pass on disposable PostgreSQL 15/17; CI receipt checks pass on 15/16. Thirteen new API adapter cases plus eleven existing billing cases, full API lint, scoped format and diff checks pass. Remaining CI/review pending. Neither PR is merged or production-deployed. These receipts depend on retaining audit events unchanged. No new wallet, prices, top-ups, spending flags or provider calls.
This is only the duplicate-charge/reconciliation prerequisite. Remaining shared AI accounting: before-call reservations, request/pilot ceilings, interactions with refill/legacy writers, retained identities, provider-expense versus customer-charge reporting, and approved failure/cancellation policy. Existing debit behavior can still yield a negative balance; the new unused receipt function is not spending authorization. Next batch: inspect exact-head reviews/checks, fix valid findings and prepare explicit approval for these two PRs before rollout.
Charge receipt release verified — October 8, 10:33 PM ET
Sidney explicitly approved Database87 and API976. Database87 merged at f446984ab6933716b8fcc0aae8ef87493d84b9c7; normal Supabase integration applied 20261009000000_record_credit_charge_once. Production migration history, function body SHA-256 18f5657dc93408e03c0d8fc9731d73d11e5fc22924f98b5c8f41389155aa4ab9, invoker execution and pinned search path match the reviewed function. service_role may execute; anon/authenticated cannot. No charge function was invoked against a real wallet.
API976 was refreshed against released main for strict branch protection, retested (24 focused cases and full lint), and merged only after all final-head checks passed and no unresolved reviews remained. Checked head aeff080e6c21db7ddb18072219fc59187c1a0108; squash merge 348c481e0efb96293c66c305310222155ef8602f has the same tree. Vercel production dpl_AzNHCH2QQp99yzLxsLfJyFxQkDGm is READY; api.recoupable.dev maps to that commit. Unauthenticated release-case list still returns HTTP401.
No live caller uses the new charge adapter. No balances, prices, paid-provider flags or auto-top-up settings changed. This release supplies retry-safe charge identity, not a completed reservation/budget system or hosted payment test. Next approved batch: inspect wallet creation/refill writers and implement the smallest shared reservation prerequisite under #2105/#2123, preserving stable receipts and leaving paid Context collection off. Account-level wallet uniqueness, legacy writer compatibility, request/pilot limits, retained charge identities and explicit failure policies still need completion.
Mono257 now contains the released API/Database references at c422daa10bf8df9a34920b6a1ae4fac799044bad, still only three platform gitlinks and separately unapproved/unmerged. The heartbeat resumes after this approved release.
Single-wallet prerequisite — October 8, 10:51 PM ET
Database88, head fb4dd28ec3ee43053505651232e033531ac3d7ef, enforces one credits_usage row per non-null billing account. The migration changes no balances, usage receipts, prices or role grants. Existing duplicates fail installation for explicit review; it never merges/deletes balances. Installation has bounded lock/work timeouts. Nullable-owner behavior is preserved, and those rows are not valid charge payers.
A read-only aggregate production preflight found zero duplicate account groups and zero unassigned rows; no account identities or balances were returned. This is a point-in-time observation, not a deployed constraint. All 18 new/existing credit transaction tests pass on disposable PostgreSQL 15/17. Five new regression assertions failed before the migration, including all twelve concurrent initial inserts succeeding. CI on 15/16, Supabase preview and review are pending. Worktree .worktrees/database/credit-wallet-identity, branch codex/credit-wallet-identity, is pushed and clean. No merge or production migration; this PR requires its own approval.
Source audit confirms the API's initial-read fallback already rereads after a failed insert. A concurrent legacy admin grant may now fail and roll back instead of creating a second wallet; no grant retry is introduced. Remaining hazards: refill writes an absolute balance based on an earlier read; top-up increments and unaudited deductions also use read-modify-write. Account uniqueness does not fix those lost updates, coordinate old spenders with holds, or implement request/pilot ceilings. Inventory, rollout checks and limits are in the PR's tests/CREDIT-WALLET-IDENTITY.md.
Next bounded batch: inspect Database88 exact-head CI/preview/review, address valid findings, then prepare explicit approval. Continue scoped refill/legacy writer engineering afterward without enabling paid callers. No budget values, prices, provider collection, top-ups, financial mutations or duplicate Records intake occurred. Mono257 remains separately unapproved.
Database88 ready for approval — October 9 UTC
Sidney requested pausing the ten-minute loop and continuing manually; the existing heartbeat is PAUSED and must remain paused until explicitly resumed. Database88 review corrections are pushed at c5a12d025f52b4c59d971d220002eb0a83af237d: release notes now identify the ACCESS EXCLUSIVE lock and its read/write impact; tests require the migration file rather than silently falling back. All 18 local credit transaction tests pass after corrections. All nine exact-head checks pass, and both review findings are confirmed addressed/resolved. The Supabase preview database shows a validated UNIQUE(account_id) constraint and valid unique backing index. This proves preview installation, not production rollout.
Database88 remains unmerged and requires specific approval under the standing per-PR release rule. No production schema, balances, prices or paid flags changed. On approval, recheck the exact head, required checks and aggregate duplicate preflight; merge through normal workflow; verify production migration and constraint metadata. Keep Mono257 separately unapproved. After this prerequisite, concurrent refill/top-up absolute writes still need a bounded fix before reservations and paid Context collection can be activated.
Priority clarification — agreed 2026-10-09
The next #2116 milestone is company onboarding and linked existing evidence. This ticket remains the safety gate for paid execution, not a gate on unpaid source inventory, manual review or deterministic export parsing. Preserve completed billing/recovery work and the separately reviewed Database88 change; do not expand the billing lane until a concrete paid operation in the selected milestone requires it. No paid collector, model call, pricing or automatic purchase is enabled by this reordering. The recurring loop remains paused. Earlier dated next-step notes do not override this priority.
Activity