You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
code
Project directory:
/Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc
Engineering brief produced from the codebase and task details:
### Task Summary
Harden the Solana payment subsystem against the adversarial review: P0 (secret audit of git history, prompt-injection hardening in admin_chat initiate_payment, null recipient_discord_id confirmation bypass), P1 (wallet swap window between test and final, idempotency slot reuse after forced failure, per-payment + rolling daily USD caps on admin-triggered payouts, admin success-DM over threshold), P2 (log audit, RLS posture doc). End-to-end hardening with no half-fixes on the subtle wallet-swap and idempotency paths.
### Key Evidence
- The `initiate_payment` LLM tool schema in admin_chat already does NOT accept a wallet_address parameter — it takes only recipient_user_id, amount_sol, reason. The wallet is looked up via db_handler.get_wallet(guild_id, recipient_user_id, 'solana') at tools.py:2474. The task's P0 premise ('remove LLM-sourced wallet addresses') is largely already satisfied — the plan should (a) grep siblings for any other tool that accepts a wallet_address, (b) add an assertion/docstring in execute_initiate_payment that wallets MUST come from wallet_registry, (c) add a regression test that a wallet_address key in params is ignored. This is verification + defensive assertion, NOT a rewrite. (source: src/features/admin_chat/tools.py:580-599, 2438-2505; relevance: high)
Assistant
User
Assistant
Updated critique_output.json.
Most of the prior significant flags are genuinely resolved. I marked FLAG-002, FLAG-003, the collision/control-flow issues, the multi-caller upsert_wallet issue, the constructor-site drift issue, the sentinel-convention issue, the grants verification gap, and the criteria-quality issue as verified.
One significant concern remains open and was re-flagged as FLAG-001: the revised plan derives USD for amount-token payouts only locally, but explicitly does not persist it to record['amount_usd']. In this repo, the rolling daily cap helper is defined to sum stored amount_usd, and the planned success-DM threshold also keys off payment.get('amount_usd'). That means actual admin-chat final payouts would still undercount the rolling cap and miss success DMs unless the plan either persists the derived USD or recomputes it consistently in those downstream paths.
User
Assistant
Updated critique_output.json.
This revision resolves the prior significant cap-path gap. I verified FLAG-001 and the related issue-hints/correctness/scope/all-locations/callers/verification findings: the plan now persists derived USD for capped amount-token payouts, explicitly protects uncapped-provider behavior, and adds the missing end-to-end tests for rolling-cap and success-DM wiring.
I flagged one remaining minor completeness issue as FLAG-004: the success criteria still claim null-recipient rejections trigger an admin DM, but the plan steps only tighten confirm_payment to warn and return None; they do not add a shared admin-DM path for that rejection.
execute_payment ALREADY uses the stored recipient_wallet string from the payment row (payment_service.py:244), not a re-read from wallet_registry. The final payment in admin_chat is created with recipient_wallet=payment['recipient_wallet'] copied from the test payment row (admin_chat_cog.py:356). So execute_payment is safe. The actual wallet-swap risk lives in request_payment's pre-insert check at payment_service.py:84-90, which rejects a new intent whose wallet_id→wallet_registry.wallet_address mismatches the string — causing the entire final-payout to silently drop if the user upserts a new wallet. Fix: block upsert_wallet while an active intent exists (in db_handler.upsert_wallet), don't rely on post-hoc rejection. (source: src/features/payments/payment_service.py:68-90, 244; src/features/admin_chat/admin_chat_cog.py:236, 356; relevance: high)
Null recipient_discord_id confirmation bypass is real: payment_service.confirm_payment at lines 193-202 only checks recipient match if not privileged_override and expected_user_id is not None. A payment with recipient_discord_id=NULL can be confirmed by any user. Fail-closed fix: require expected_user_id AND confirmed_by_user_id to be non-null and match, unless privileged_override=True. sql/payments.sql:77 allows NULL — consider adding a partial CHECK for provider='solana_payouts'. (source: src/features/payments/payment_service.py:193-202; sql/payments.sql:77; relevance: high)
Idempotency slot reuse after forced failure: the unique index uq_payment_requests_active_producer_ref at payments.sql:126-128 is partial WHERE status NOT IN ('failed','cancelled'). Once a row is marked failed, a new row with the same (producer, producer_ref, is_test) can be freely inserted. request_payment (payment_service.py:54-61) early-returns on existing rows but likely only sees non-terminal ones. Since admin_chat uses ONE producer_ref across test AND final payments (admin_chat_cog.py:234, 354), and test failures free the slot, an attacker who forces a test failure can retrigger with a different wallet. Fix: query ALL prior rows for (producer, producer_ref, is_test) including terminal; if any prior row has a different recipient_wallet, log WARN, DM admin, and create the new row as manual_hold. (source: sql/payments.sql:126-128; src/features/payments/payment_service.py:54-61,167-174; src/features/admin_chat/tools.py:2473; src/features/admin_chat/admin_chat_cog.py:234,354; relevance: high)
No USD cap enforcement exists. request_payment accepts arbitrary amount_usd/amount_token with only a > 0 check (payment_service.py:102, 112). manual_hold is already a terminal status in the enum (payments.sql:100) and db_handler.mark_payment_manual_hold is wired. Caps should go in PaymentService.request_payment, provider-scoped to {'solana_payouts'}. Over-cap should create a manual_hold row + admin DM (NOT silent reject), preserving the audit trail. (source: src/features/payments/payment_service.py:32-174; sql/payments.sql:92-102; relevance: high)
Admin DM path today fires only on failed/manual_hold via payment_cog._dm_admin_payment_failure (payment_cog.py:267-333). No success DM exists. Add a sibling _dm_admin_payment_success called from _handle_terminal_payment when status=='confirmed', not is_test, provider in {'solana_payouts'}, and amount_usd >= ADMIN_SUCCESS_DM_THRESHOLD_USD (default 100). Must be visually differentiated from failure DM (distinct prefix/emoji). (source: src/features/payments/payment_cog.py:267-333; relevance: high)
Two Solana providers are already split and wired in main.py:157-161 ('solana_grants', 'solana_payouts'). grants_cog uses 'solana_grants' exclusively (grants_cog.py:574,686); admin_chat uses 'solana_payouts' (admin_chat_cog.py:238, 358). Cap enforcement must be scoped to 'solana_payouts' so grants are unaffected. Rolling daily window aggregates on (guild_id, provider='solana_payouts', status IN pending_confirmation/queued/processing/submitted/confirmed) within 24h. (source: main.py:157-161; src/features/admin_chat/admin_chat_cog.py:238,358; src/features/grants/grants_cog.py:574,686; relevance: medium)
upsert_wallet in db_handler.py:1417-1465 has no inflight-intent check. It updates wallet_address in place and clears verified_at on change (line 1442). Fix: before UPDATE, call a new helper has_active_payment_or_intent(guild_id, discord_user_id) that queries non-terminal payment_requests rows AND awaiting_* admin_payment_intents rows; abort with a structured error if any exist. Caller (_handle_wallet_received at admin_chat_cog.py:193-218) surfaces the error to the admin review channel. (source: src/common/db_handler.py:1417-1465; src/features/admin_chat/admin_chat_cog.py:193-218; relevance: high)
Existing tests: tests/test_admin_payments.py instantiates a real PaymentService at line 687 with provider dict {'solana': provider} (note: NOT 'solana_payouts'). tests/test_social_publish_service.py:474-685 also uses real PaymentService. Cap config must be injectable via constructor kwargs with sensible defaults (or a capped_providers set) so these tests keep passing without rewrites. conftest.py supplies shared fixtures. Existing tests cover happy paths but NOT the adversarial cases we're adding. (source: tests/test_admin_payments.py:497-729; tests/test_social_publish_service.py:474-685; tests/conftest.py; relevance: medium)
sql/payments.sql currently has no header comment and no documented RLS posture. Given Supabase/Postgres with service-role access from the bot, posture is 'RLS NOT enabled; all access mediated via service-role handlers in db_handler.py; no direct browser/Discord client access; writes parameterized'. Comment-only — do NOT ALTER TABLE ENABLE RLS (requires rewriting policies across the bot). (source: sql/payments.sql:1-12; relevance: medium)
Logging audit targets: src/common/log_handler.py (central logger). Payment logs already redact wallets via _redact_wallet/_redact_wallet_address (payment_cog.py; admin_chat/tools.py:1072-1124). SolanaClient logs recipient+signature only. Grep for SOLANA_PRIVATE_KEY, HELIUS_API_KEY, Keypair.from_bytes tracebacks, os.environ dumps. Document findings; add scrubbing only if a real leak is found. (source: src/common/log_handler.py; src/features/payments/payment_cog.py; src/features/admin_chat/tools.py:1072-1124; relevance: medium)
code
### Relevant Code
| File | Functions | Why |
| --- | --- | --- |
| src/features/payments/payment_service.py | PaymentService.request_payment, PaymentService.confirm_payment, PaymentService.execute_payment | Core target. Confirm-payment fail-closed fix (lines 193-202). Cap enforcement injection point (after amount_token derivation at lines 90-119, before create_payment_request at 163). Idempotency collision detection before early return at lines 54-61 and in fallback at 167-174. execute_payment at 244 already uses stored wallet — add regression test, no code change. |
| src/features/payments/payment_cog.py | PaymentCog._handle_terminal_payment, PaymentCog._dm_admin_payment_failure | Add sibling _dm_admin_payment_success called from _handle_terminal_payment (lines 267-272) when status=='confirmed', not is_test, provider in admin-payout set, amount_usd>=threshold. Reuse ADMIN_USER_ID env plumbing. Differentiated prefix/emoji from failure DM. |
| src/features/admin_chat/admin_chat_cog.py | AdminChatCog._handle_wallet_received, AdminChatCog._start_admin_payment_flow, AdminChatCog.handle_payment_result | handle_wallet_received (193-218) calls upsert_wallet with no inflight guard — surface new structured error to admin review channel. start_admin_payment_flow (220-271) and handle_payment_result (299-402) handoff reads recipient_wallet from test row (already safe, pin with test). Ensure recipient_discord_id always passed non-null. |
| src/features/admin_chat/tools.py | execute_initiate_payment, initiate_payment tool schema | Tool schema at 580-599 already excludes wallet_address. Grep ALL admin_chat tools for any wallet_address-accepting sibling. Add docstring + defensive pop-and-warn in execute_initiate_payment (2438-2526) asserting wallets must come from wallet_registry. Add test that wallet_address in params is ignored. |
| src/common/db_handler.py | upsert_wallet, get_wallet, get_wallet_by_id, get_payment_requests_by_producer, create_payment_request, mark_payment_manual_hold | upsert_wallet (1417-1465) needs inflight guard via new helper has_active_payment_or_intent(guild_id, discord_user_id). Add new helper get_payment_requests_for_ref_all (no terminal-status filter) for slot-reuse detection. Add new helper get_rolling_24h_payout_usd(guild_id, provider) for daily cap aggregation. |
| sql/payments.sql | wallet_registry schema, payment_requests schema, uq_payment_requests_active_producer_ref | Add top-of-file comment block documenting RLS posture. Do NOT change the partial-index predicate (legitimate retries need it). Collision detection stays in app code. Consider adding a CHECK that recipient_discord_id is non-null when provider='solana_payouts' (defense-in-depth). |
| src/common/log_handler.py | - | Log audit target. Grep for env-var logging, unsanitized tracebacks, os.environ dumps. Add scrubbing filter for SOLANA_PRIVATE_KEY/HELIUS*/ANTHROPIC* only if a real leak path exists. Document findings either way. |
| main.py | PaymentService construction | Lines 157-161 construct PaymentService with providers and test_payment_amount. Pass new kwargs (per_payment_usd_cap, daily_usd_cap, capped_providers, admin_success_dm_threshold_usd) sourced from env with safe defaults (500/2000/{'solana_payouts'}/$100). |
| tests/test_admin_payments.py | PaymentService integration tests | Extend PaymentService tests at 687+ with adversarial cases: null-recipient reject, cap manual_hold, rolling daily cap, slot-reuse collision, upsert_wallet block, admin success DM, wallet_address tool arg ignored, execute_payment stored-wallet regression pin. Preserve FakeAdminPaymentService happy-path tests. |
| tests/test_scheduler.py | - | Scheduler wrappers (lines 390-584) must still work — caps run only in request_payment, NOT execute_payment, so scheduled queue path is unaffected. Verify. |
| tests/test_social_publish_service.py | - | Existing PaymentService construction (474-685) uses provider dict {'solana': provider}. New caps must be provider-scoped to 'solana_payouts' so these tests remain green with defaults. |
code
### Test Expectations
- [fail_to_pass] tests/test_admin_payments.py::test_confirm_rejects_null_recipient_discord_id: NEW: confirm_payment returns None and logs WARN when recipient_discord_id is NULL and privileged_override is False, regardless of confirmed_by_user_id. privileged_override=True still works for test-payment auto-advance.
[fail_to_pass] tests/test_admin_payments.py::test_request_payment_per_payment_cap_manual_holds: NEW: request_payment with provider='solana_payouts' and amount_usd > per-payment cap creates the row with status='manual_hold', logs WARN, and triggers admin DM. grants provider is unaffected.
[fail_to_pass] tests/test_admin_payments.py::test_request_payment_rolling_daily_cap_manual_holds: NEW: once rolling 24h sum of solana_payouts amount_usd crosses daily cap, next new intent is manual_hold'd even if per-payment amount is under per-payment cap. Grants are unaffected.
[fail_to_pass] tests/test_admin_payments.py::test_slot_reuse_collision_detected: NEW: prior failed row with same (producer, producer_ref, is_test) and DIFFERENT recipient_wallet causes request_payment to log WARN, DM admin, and create the new row as manual_hold (NOT silent replacement).
[fail_to_pass] tests/test_admin_payments.py::test_upsert_wallet_blocked_during_active_intent: NEW: db_handler.upsert_wallet refuses to update wallet_address while a non-terminal payment_requests row OR awaiting_* admin_payment_intents row exists for (guild_id, discord_user_id), and _handle_wallet_received surfaces the error to the admin review channel.
[fail_to_pass] tests/test_admin_payments.py::test_admin_success_dm_over_threshold: NEW: on confirmed non-test solana_payouts payment with amount_usd >= $100, admin is DM'd with success-differentiated message. Under-threshold does NOT DM. Failure DM path is unchanged.
[fail_to_pass] tests/test_admin_payments.py::test_execute_payment_uses_stored_wallet: NEW regression pin: execute_payment passes payment['recipient_wallet'] (frozen stored string) to provider.send, NOT a re-read from wallet_registry. Prevents future regression.
[fail_to_pass] tests/test_admin_payments.py::test_initiate_payment_tool_rejects_wallet_address_arg: NEW: passing a wallet_address key through execute_initiate_payment params is ignored (not persisted, not used for lookup); wallet is exclusively resolved via db_handler.get_wallet(guild_id, recipient_user_id, 'solana').
[pass_to_pass] tests/test_admin_payments.py (existing happy-path): Existing happy path (wallet capture → test → confirm → final → notify) still passes with new caps/collision logic (test uses high cap).
[pass_to_pass] tests/test_scheduler.py (existing): Scheduler queue path still advances queued payments; caps run only in request_payment, not execute_payment.
[pass_to_pass] tests/test_social_publish_service.py (existing PaymentService tests): Social publish service's PaymentService usage keeps working — new caps are scoped to 'solana_payouts', these tests use different provider names.
code
### Constraints
- Fail-closed: on ANY validation ambiguity (cap, collision, null recipient, inflight wallet change), the payment must NOT execute. Prefer manual_hold + admin DM over silent rejection so the trail is preserved.
Do NOT change the partial-index predicate on uq_payment_requests_active_producer_ref — legitimate retries after a failed payment rely on the failed/cancelled exclusion. Collision detection must live in app code.
Do NOT break grants. Cap enforcement and admin success DM must be scoped to provider='solana_payouts' (or an explicit capped_providers set), not global. grants_cog uses 'solana_grants' with its own semantics.
Do NOT re-read recipient_wallet from wallet_registry in execute_payment. Keep the frozen-string behavior at payment_service.py:244. Add a regression test pinning this.
Do NOT add LLM-sourced wallet parameters anywhere. If a sibling admin_chat tool is found that accepts wallet_address text, remove or harden it in the same plan.
Do NOT widen upsert_wallet's blocking window beyond necessary. Block ONLY while a non-terminal payment_requests row OR an awaiting_* admin_payment_intents row exists for (guild_id, discord_user_id). Completed/failed/cancelled intents must NOT block.
Do NOT log secrets. Any new logging in cap/collision/success-DM paths must redact wallets via existing _redact_wallet helpers and must not log env-var values or key material.
Cap config must be injectable via PaymentService constructor kwargs (not env-only) so existing tests can pass high/infinite caps without env pollution.
Helius RPC and SolanaClient primitives are out of scope per task. Fix only application-layer vectors.
sql/payments.sql RLS documentation is COMMENT-ONLY. Do NOT ALTER TABLE ENABLE RLS — that would require rewriting policies across the bot's service-role access.
Admin success DM must be visually differentiated from failure DM (distinct prefix, emoji, status word). Do NOT overload _dm_admin_payment_failure — add a sibling method.
Default thresholds (env-overridable): per-payment cap 500,dailycap2000/guild, admin success DM threshold $100. Bake defaults into main.py's PaymentService constructor call.
Null-recipient_discord_id fix must preserve privileged_override=True escape hatch for admin auto-advance of test payments (admin_chat_cog.py:258-262). Verify test payments still carry recipient_discord_id and don't hit the null path.
Rolling 24h cap must include in-flight statuses (pending_confirmation/queued/processing/submitted/confirmed) so burst concurrent tool calls cannot all slip under the cap simultaneously. If a serializable transaction is impractical, document the residual burst window in a comment.
P0 prompt-injection task premise is already mostly fixed — the plan must explicitly say 'verification + defensive assertion + test' is the work, not a rewrite, so the review agent does not mark prep as incomplete.
code
### Suggested Approach
Implement in this order so each layer builds on verified foundations. DO NOT delegate understanding of the subtle wallet-swap and idempotency paths.
Groundwork (P2, low-risk): add RLS-posture comment block at the top of sql/payments.sql. Extend tests/conftest.py with an in-memory wallet_registry + payment_requests store if one doesn't already exist, so adversarial tests can operate against real PaymentService logic.
P0: Null recipient_discord_id fail-closed (payment_service.py:193-202). Change to if not privileged_override: if expected_user_id is None or confirmed_by_user_id is None or int(expected_user_id) != int(confirmed_by_user_id): log WARN; return None. Ship with the new test. Audit every confirm_payment call site (payment_cog.py + admin_chat_cog.py:258-262) to ensure no flow relies on NULL recipient.
P0: admin_chat prompt-injection verification. Grep ALL admin_chat tools for 'wallet_address' / 'address' fields in input_schema. If any sibling tool accepts a raw wallet, remove or harden. Add a docstring + defensive params.pop('wallet_address', None) with WARN log at the top of execute_initiate_payment. Add the tool-arg-ignored test. Explicitly record in the plan that the task's P0 premise was already substantially implemented.
P1: upsert_wallet inflight block (db_handler.py:1417-1465). Add helper has_active_payment_or_intent(guild_id, discord_user_id) querying non-terminal payment_requests + awaiting_* admin_payment_intents. Verify exact admin_payment_intents status enum values before coding the 'active' predicate. Return structured error from upsert_wallet on conflict. Update _handle_wallet_received (admin_chat_cog.py:193-218) to surface to admin review channel.
P1: Idempotency slot-reuse collision detection (payment_service.py:54-61, 167-174). Add db_handler helper get_payment_requests_for_ref_all(producer, producer_ref, is_test) that does NOT filter terminal. Before the idempotent early-return, query this helper: if any prior row has a different recipient_wallet than the incoming request, log WARN, DM admin, create the new row as manual_hold (do NOT return the old non-terminal row as if nothing happened). Be careful the early-return at lines 54-61 does not short-circuit BEFORE collision detection.
P1: Per-payment + rolling daily USD caps in PaymentService. Add constructor kwargs per_payment_usd_cap, daily_usd_cap, capped_providers=frozenset({'solana_payouts'}), default to None (disabled) for backward-compat with existing tests. In request_payment, after amount_token derivation, if provider in capped_providers and not is_test: if amount_usd > per_payment_cap OR get_rolling_24h_payout_usd(guild_id, provider) + amount_usd > daily_cap → create the row with status='manual_hold' + last_error='cap exceeded' + admin DM. Add db_handler helper get_rolling_24h_payout_usd that sums amount_usd across pending_confirmation/queued/processing/submitted/confirmed within 24h. If serializable transaction is impractical, document residual burst window.
P1: Admin success DM (payment_cog.py:267-333). Add _dm_admin_payment_success sibling with distinct prefix ('✅ Payment Completed'), called from _handle_terminal_payment when status=='confirmed' AND not is_test AND provider in admin-payout set AND amount_usd >= ADMIN_SUCCESS_DM_THRESHOLD_USD env (default 100). Reuse ADMIN_USER_ID plumbing. Do NOT touch _dm_admin_payment_failure.
P2: Log audit. Grep src/ for os.environ/os.getenv sites near key access, exc_info=True near SolanaClient.from_bytes. Document findings in plan memo. Add a scrubbing filter in log_handler.py ONLY if a real leak path is found.
P2: Git history secret audit. Run git log -p -S 'PRIVATE_KEY' -- ., git log -p -- '**/*.env*', gitleaks if installed. Record findings in plan output. Audit task, not a code fix (unless a leaked secret requires rotation — flag to user separately).
Regression tests. Add all tests from test_expectations. Run pytest tests/ and verify test_admin_payments, test_scheduler, test_social_publish_service remain green. Defaults for new constructor kwargs must keep existing test construction sites passing unchanged.
Main wiring (main.py:157-161). Pass the new kwargs from env vars with documented defaults.
Subtle pitfalls:
In step 5, the idempotent early return at payment_service.py:54-61 must be reordered to run AFTER collision detection, OR collision detection must happen inside that branch too.
In step 6, rolling window MUST include in-flight statuses, not just confirmed, to prevent concurrent burst slip-through.
In step 4, read admin_payment_intents table schema + db_handler.create_admin_payment_intent to enumerate exact status values before hardcoding the 'active' set.
The initial P0 premise about LLM-sourced wallet addresses appears already fixed by a prior change — state this explicitly in the plan so review doesn't reject prep as incomplete; the work is verification + defensive assertion + test.
Do NOT double-check caps in execute_payment. Caps run only in request_payment. Scheduler path (claim_due_payment_requests → execute_payment) must not hit cap logic.
privileged_override=True must remain usable for test-payment auto-advance (admin_chat_cog.py:258-262). Verify the test payment row carries recipient_discord_id (it does via line 244) so it doesn't hit the new null-reject branch anyway.
code
The engineering brief above was produced by analyzing the codebase. Use it as a strong starting point, but the suggested approach is a hypothesis — verify it's the best fix, not just a valid one.
Idea:
Harden the Solana payment subsystem against the attack vectors found by the adversarial security review. Fix P0: git history secret audit, prompt-injection hardening in admin_chat (remove LLM-sourced wallet addresses from initiate_payment tool; wallets must come from wallet_registry keyed by mentioned Discord user), null recipient_discord_id confirmation bypass (fail-closed). Fix P1: wallet swap window between test and final payment (verify execute_payment uses stored recipient_wallet string; reject or warn on upsert_wallet during active intents), idempotency slot reuse after forced failure (warn/DM on producer_ref collision with prior failed row having different wallet), per-payment and rolling daily USD cap on admin-triggered payouts enforced in PaymentService (default 500/payment,2000/day/guild, exceeding goes to manual_hold), admin DM on successful admin_chat payouts over threshold (default $100, differentiated from failure DMs). Fix P2: log audit for secret leakage, document RLS posture at top of sql/payments.sql. Already using Helius so RPC attacks out of scope. Two wallets already split into solana_grants and solana_payouts providers. Think carefully about wallet-swap and idempotency — they are subtle and easy to half-fix. Goal is end-to-end hardening.
Implement the P0/P1/P2 hardening from the adversarial security review against src/features/payments/ and src/features/admin_chat/. The work is layered: fail-closed correctness first (null recipient, prompt-injection defense, inflight wallet lock), then monetary safety (idempotency collision detection, per-payment + rolling daily USD caps on solana_payouts), then observability (admin success DM, log audit, RLS posture doc, git history audit).
Important corrections to the brief:
RLS is already enabled on payment_requests, wallet_registry, and payment_channel_routes (sql/payments.sql:192-199). Anon/authenticated roles are fully revoked; the bot accesses via service role which bypasses RLS. The RLS-posture doc step is a comment block describing existing posture, not a claim that RLS is off.
P0 prompt-injection is already substantially implemented — the initiate_payment tool schema at src/features/admin_chat/tools.py:580-599 exposes only recipient_user_id, amount_sol, reason. The wallet comes from db_handler.get_wallet(guild_id, recipient_user_id, 'solana') at tools.py:2474. The work is: (a) grep all admin_chat tool schemas for any sibling wallet_address field, (b) add a defensive params.pop('wallet_address', None) + WARN log and a docstring at the top of execute_initiate_payment, (c) add a regression test. This step is verification + defensive assertion, not a rewrite.
The subtler idempotency bug is that get_payment_requests_by_producer (db_handler.py:1853) already returns all statuses (no terminal filter) and request_payment at payment_service.py:54-61 unconditionally returns existing_rows[0]. If the most-recent prior row is failed, the caller gets back the failed row and treats it as a fresh pending row. The fix is two-pronged: (a) collision detection across all prior rows (different recipient_wallet → manual_hold new row + admin DM), and (b) narrow the idempotent early-return to non-terminal prior rows so legitimate retries after failure land on a fresh row.
The wallet-swap vector lives in the combination of (a) upsert_wallet having no inflight guard and (b) request_payment's wallet_id consistency check at payment_service.py:84-90 rejecting the final payment when the stored wallet mismatches the frozen wallet string — causing silent dropout of the final payout. Fix is to block upsert_wallet while an active payment intent exists for that user.
execute_payment already uses the stored recipient_wallet string (payment_service.py:244). The work here is a regression-pin test only — no code change.
Key invariants (non-negotiable)
Fail-closed. On cap breach, collision with different wallet, null recipient, or inflight wallet change: create a manual_hold row + admin DM, never silent reject (preserves audit trail).
Provider-scoped caps. Caps apply only to providers in capped_providers (default frozenset({'solana_payouts'})). solana_grants MUST remain unaffected.
Do NOT change the partial-index predicate on uq_payment_requests_active_producer_ref. Legitimate retries after failure rely on the failed/cancelled exclusion. Collision detection stays in app code.
Do NOT re-read recipient_wallet in execute_payment. Keep the frozen-string semantics at payment_service.py:244. Pin with a regression test.
Do NOT add cap enforcement in execute_payment. Caps run only in request_payment; the scheduler's claim_due_payment_requests → execute_payment path must not hit cap logic.
Do NOT widen upsert_wallet's block window. Block only while a non-terminal payment_requests row OR an active admin_payment_intents row exists for (guild_id, discord_user_id). Terminal (completed/failed/cancelled) rows do NOT block.
Preserve privileged_override=True for test-payment auto-advance (admin_chat_cog.py:258-262). The test payment row carries recipient_discord_id (set at line 244) so it does not hit the new null-recipient branch anyway.
No secret logging. New logging in cap/collision/DM paths must redact wallets via existing _redact_wallet helpers and must never log env-var values or key material.
Cap config must be injectable via constructor kwargs (not env-only) so existing PaymentService tests remain green with defaults.
Modifyconfirm_payment at payment_service.py:193-202. Replace the current if not privileged_override and expected_user_id is not None: with:
python
if not privileged_override:
if expected_user_id is None or confirmed_by_user_id is None or int(expected_user_id) != int(confirmed_by_user_id):
self.logger.warning(
"[PaymentService] rejected confirmation for %s: expected_user=%s confirmed_by=%s",
payment_id,
expected_user_id,
confirmed_by_user_id,
)
return None
Audit every confirm_payment call site: payment_cog.py (button confirmation — always carries a user) and admin_chat_cog.py:258-262 (test payment auto-confirm via privileged_override — actually passes confirmed_by='auto' without privileged_override=True, see below).
Verifyadmin_chat_cog.py:258-262 — the test payment call passes confirmed_by='auto' and confirmed_by_user_id=int(intent['recipient_user_id']) but notprivileged_override=True. The test payment row carries recipient_discord_id=int(intent['recipient_user_id']) (set at admin_chat_cog.py:244), so the equality check succeeds under the new rule. No change needed at that call site. Add a comment there explaining why the test still auto-confirms under the tightened rule.
Grepsrc/features/admin_chat/tools.py for every tool input schema (all dicts in ADMIN_CHAT_TOOLS) and confirm none accept a field named wallet_address, address, solana_address, recipient_wallet, or wallet. Current evidence: only _redact_wallet_address helper (lines 1072, 1124) uses that name. If any schema is found, strip the field from the schema and from the execute function.
Modifyexecute_initiate_payment at tools.py:2438. At the top of the function (after the try/type coercion), add:
python
# Wallets MUST come from wallet_registry keyed by recipient_user_id.
# Never trust an LLM-sourced wallet string in the params payload.
if 'wallet_address' in params or 'recipient_wallet' in params:
logger.warning(
"[AdminChat] execute_initiate_payment received wallet_address/recipient_wallet in params; ignoring"
)
params.pop('wallet_address', None)
params.pop('recipient_wallet', None)
Add a one-line docstring at execute_initiate_payment stating "Wallets are resolved exclusively via db_handler.get_wallet(...); callers MUST NOT pass wallet_address."
Note in plan: the P0 premise was already substantially satisfied by prior work; this step is verification + defensive assertion + regression test, not a rewrite.
Step 3: Git history secret audit (no code change)
Scope: Small
Run the following audit commands and record findings in the review memo:
If gitleaks is installed: gitleaks detect --source . --no-banner
Document findings (even if empty) in a memo block at the top of the plan. If any real secret is found, STOP and flag to the user for rotation — do NOT attempt rewrite-history fixes automatically.
Add a new method on DatabaseHandler after list_active_intents:
python
def has_active_payment_or_intent(self, guild_id: int, discord_user_id: int) -> bool:
"""True when any non-terminal payment_request row or non-terminal
admin_payment_intent row exists for this user."""
Implement two queries:
payment_requests WHERE guild_id=? AND recipient_discord_id=? AND status NOT IN ('confirmed', 'failed', 'manual_hold', 'cancelled') LIMIT 1.
admin_payment_intents WHERE guild_id=? AND recipient_user_id=? AND status NOT IN ('completed', 'failed', 'cancelled') LIMIT 1. (Matches the active predicate already used in get_active_intent_for_recipient at db_handler.py:1754 and list_active_intents at db_handler.py:1782.)
Return True if either returns a row.
Use_gate_check(guild_id) and the existing supabase-guard pattern for consistency with neighboring helpers.
Step 5: Block upsert_wallet while an active intent exists (src/common/db_handler.py, src/features/admin_chat/admin_chat_cog.py)
Scope: Small
Modifyupsert_wallet at db_handler.py:1417-1465. Before the existing lookup, add:
python
if existing and existing.get('wallet_address') != address:
if self.has_active_payment_or_intent(guild_id, discord_user_id):
logger.warning(
"[DB] upsert_wallet blocked: active payment/intent for guild %s user %s",
guild_id,
discord_user_id,
)
return {'__error__': 'active_payment_or_intent'}
Note: use a structured sentinel so the caller can distinguish "blocked" from "error" without raising. Alternatively raise a dedicated WalletUpdateBlockedError; pick whichever matches the codebase's error-surfacing convention.
Verify the structured-return pattern against other db_handler helpers before committing. If the codebase prefers exceptions at the db layer, switch to raising and catching at the caller. Check upsert_wallet's current callers via grep first.
Modify_handle_wallet_received at admin_chat_cog.py:193-218. After the upsert_wallet call, detect the blocked sentinel/exception and surface a user-facing error:
python
if isinstance(wallet_record, dict) and wallet_record.get('__error__') == 'active_payment_or_intent':
await self._notify_admin_review(
message.channel, intent,
"I cannot update this wallet address: an active payment is in flight. "
"Please wait for it to resolve or cancel it before changing wallets.",
resolved_by_message_id=message.id,
)
return
Keep the existing if not wallet_record: branch for the general-failure path.
Add a new helper get_payment_requests_for_ref_all(guild_id, producer, producer_ref, is_test) in db_handler.py that wraps the existing query but is explicitly documented as "returns rows in ALL statuses including terminal". In practice this is identical to the existing get_payment_requests_by_producer which already has no status filter — so this step may be just a clarifying rename/alias + docstring, verifying the behavior. Confirm by reading db_handler.py:1853-1883 before touching.
Reworkrequest_payment at payment_service.py:54-61. Replace the current body with collision-detect-first, idempotent-return-second:
python
all_prior_rows = self.db_handler.get_payment_requests_by_producer(
guild_id=guild_id, producer=producer, producer_ref=producer_ref, is_test=is_test,
)
normalized_wallet = str(recipient_wallet or '').strip()
collision = None
for row in all_prior_rows:
prior_wallet = str(row.get('recipient_wallet') or '').strip()
if prior_wallet and normalized_wallet and prior_wallet != normalized_wallet:
collision = row
break
# Non-terminal idempotent return (fresh retries after failed/cancelled must create a new row)
terminal = {'confirmed', 'failed', 'manual_hold', 'cancelled'}
active_prior = [r for r in all_prior_rows if str(r.get('status') or '').lower() not in terminal]
if active_prior and not collision:
return active_prior[0]
On collision: create the new row with status='manual_hold', last_error='idempotency collision: prior wallet differs', and schedule an admin DM. Path: set record['status'] = 'manual_hold' and record['last_error'] = ... at the record-building step, then after insert call payment_cog._dm_admin_payment_failure (or equivalent path) via the terminal handler. Preferred: route through existing _handle_terminal_payment so the manual_hold DM fires via the existing path — verify _handle_terminal_payment is invoked for newly-inserted manual_hold rows. If not, explicitly fire _dm_admin_payment_failure here.
Subtle pitfall (flagged for the reviewer): the reorder must ensure the early-return at the end of collision-free idempotent flow happens only when prior rows exist and none are terminal-only. If all prior rows are terminal (and none are collisions), we must fall through to create a fresh row — this is the bug fix. Add an inline comment explaining this.
Fallback path at payment_service.py:167-174 (post-insert re-read for concurrent duplicates): apply the same collision detection against the re-read rows. If the re-read row has a different recipient_wallet, log WARN but return the canonical row (DB won this race).
Addget_rolling_24h_payout_usd(guild_id: int, provider: str) -> float on DatabaseHandler. Query payment_requests:
guild_id=?
provider=?
is_test = false
status IN ('pending_confirmation','queued','processing','submitted','confirmed') (includes all non-terminal + confirmed so burst requests cannot all slip under the cap simultaneously — confirmed stays in the 24h window because the money has been committed).
created_at >= now() - interval '24 hours'
Sumamount_usd across results; coerce nulls to 0.0. Return float.
Add a comment noting: "Supabase REST does not provide a serializable transaction; this aggregation races concurrent burst calls. The residual burst window is ~RPC latency (~100-500ms). Downstream manual_hold + admin DM provides the fail-closed backstop."
Step 8: PaymentService cap enforcement (src/features/payments/payment_service.py)
Normalize: self.per_payment_usd_cap = float(...) if provided else None, self.capped_providers = frozenset(p.lower() for p in (capped_providers or ())). Defaults are all-None so existing tests (test_admin_payments.py:687, test_social_publish_service.py:474) continue to pass unchanged.
Inject cap logic in request_paymentafter amount_token derivation (lines 90-119) and beforecreate_payment_request (line 163). Only when not is_test AND normalized_amount_usd is not None AND provider.lower() in self.capped_providers:
python
cap_breach = None
if self.per_payment_usd_cap is not None and normalized_amount_usd > self.per_payment_usd_cap:
cap_breach = f"per-payment cap exceeded: ${normalized_amount_usd:.2f} > ${self.per_payment_usd_cap:.2f}"
elif self.daily_usd_cap is not None:
rolling = self.db_handler.get_rolling_24h_payout_usd(guild_id, provider.lower())
if rolling + normalized_amount_usd > self.daily_usd_cap:
cap_breach = f"daily cap exceeded: ${rolling:.2f} + ${normalized_amount_usd:.2f} > ${self.daily_usd_cap:.2f}"
if cap_breach:
self.logger.warning("[PaymentService] cap breach for %s:%s — %s", producer, producer_ref, cap_breach)
record['status'] = 'manual_hold'
record['last_error'] = cap_breach
Setstatus='manual_hold' in the record dict before the insert (not after) so a single atomic insert lands the row in its terminal hold state.
Trigger admin DM: since the row is inserted as manual_hold directly, the downstream _handle_terminal_payment path does NOT fire automatically (that path is triggered by handle_payment_result/webhook, not insertion). After the insert, if cap_breach and created, explicitly invoke the payment_cog admin DM path. Cleanest: add self._on_cap_breach_dm_callback as an optional constructor kwarg that main.py wires to payment_cog._dm_admin_payment_failure, and call it here. If wiring is too invasive, alternatively fire via a bot attribute lookup pattern. Pick whichever matches surrounding code (verify by checking how other cross-cog DMs are routed).
Do NOT add cap logic in execute_payment. Verify the scheduler path at tests/test_scheduler.py:390-584 by running those tests after the change — they should pass untouched.
Step 9: Admin success DM over threshold (src/features/payments/payment_cog.py, main.py)
Scope: Small
Add_dm_admin_payment_success sibling in payment_cog.py modeled on _dm_admin_payment_failure (lines 273-333) but with:
Includes amount_usd in the body alongside amount_token.
Call it from _handle_terminal_payment at line 267-271:
python
if payment.get('status') == 'confirmed' and not payment.get('is_test'):
provider = str(payment.get('provider') or '').lower()
amount_usd = float(payment.get('amount_usd') or 0)
if provider in self._admin_success_dm_providers and amount_usd >= self._admin_success_dm_threshold_usd:
await self._dm_admin_payment_success(payment)
Addself._admin_success_dm_threshold_usd and self._admin_success_dm_providers attributes on PaymentCog.__init__, sourced from env defaults or cog constructor kwargs. Default threshold: $100. Default providers: frozenset({'solana_payouts'}).
Do NOT modify _dm_admin_payment_failure.
Step 10: Wire caps + success DM into main (main.py)
SOLANA_PRIVATE_KEY, HELIUS_API_KEY, ANTHROPIC_API_KEY — grep across src/ and assert they only appear in os.environ/os.getenv reads, not in logger.* args.
Keypair.from_bytes, Keypair(, SolanaClient( — ensure no exc_info=True paths near key material.
Document findings in the review memo. Add scrubbing filter in log_handler.py ONLY if a real leak path is found. Default expectation: no code change, memo only.
Add a comment block at the top of sql/payments.sql (before create extension):
sql
-- RLS posture:
-- * Row-level security is ENABLED on wallet_registry, payment_channel_routes,
-- and payment_requests (see `alter table ... enable row level security` below).
-- * All read/write access is mediated by the bot's DatabaseHandler using the
-- Supabase service role, which bypasses RLS. No anon or authenticated-role
-- clients access these tables directly.
-- * anon and authenticated roles have ALL privileges revoked; no policies are
-- defined because no non-service-role access path exists.
-- * Parameterized writes only; no raw SQL string interpolation from user input.
-- * Changing this posture (e.g. exposing tables to a browser client) requires
-- writing explicit row-level policies first — do NOT simply grant.
Do NOTALTER TABLE anything. Comment-only change.
Phase 5: Tests
Step 13: Extend PaymentService test suite (tests/test_admin_payments.py, tests/conftest.py)
Scope: Medium
Inspecttests/conftest.py (currently untracked per git status) and tests/test_admin_payments.py:497-729 to understand the existing in-memory db fake pattern. If conftest.py already provides in-memory wallet_registry + payment_requests + admin_payment_intents stores, reuse. Otherwise extend with whatever helpers the new tests need.
Add the following fail-to-pass tests (each independent, each against a real PaymentService with a fake db_handler):
test_confirm_rejects_null_recipient_discord_id — payment row has recipient_discord_id=None; confirm_payment(...) returns None and logs WARN; with privileged_override=True it still advances.
test_confirm_rejects_mismatched_user — payment has recipient_discord_id=111, confirmed_by_user_id=222 → None.
test_request_payment_per_payment_cap_manual_holds — construct with per_payment_usd_cap=100, capped_providers=('solana_payouts',); a $101 request lands as manual_hold; grants provider ignored.
test_request_payment_rolling_daily_cap_manual_holds — seed fake db with 1900ofrolling24hsolanapayoutsat‘confirmed‘status;new200 request → manual_hold. Seed a solana_grants request of $5000 and verify it does NOT count against the cap.
test_slot_reuse_collision_detected — seed fake db with a failed prior row for (producer, producer_ref, is_test) with recipient_wallet='ABC'; new request_payment with recipient_wallet='XYZ' → new row created with status='manual_hold', last_error contains "collision".
test_slot_reuse_same_wallet_creates_fresh_row_after_failure — seed failed prior row with same wallet; new request creates a fresh pending_confirmation row (pins the reordered early-return fix).
test_idempotent_return_for_nonterminal — seed a pending_confirmation row; new request_payment returns the existing row unchanged (pins idempotency still works).
test_upsert_wallet_blocked_during_active_intent — fake db: active payment_requests row non-terminal for user; upsert_wallet returns error sentinel; _handle_wallet_received surfaces error to admin review channel.
test_upsert_wallet_unblocked_after_terminal — only terminal rows; upsert proceeds.
test_execute_payment_uses_stored_wallet — seed payment row with frozen recipient_wallet='STORED'; execute_payment passes 'STORED' to provider.send even when wallet_registry has been changed to 'NEW'. Pins regression.
test_initiate_payment_tool_rejects_wallet_address_arg — call execute_initiate_payment with params={'wallet_address': 'EVIL', ...}; verify the wallet comes from db_handler.get_wallet(...) and the params wallet was popped + WARN logged.
Verify existing happy-path tests still pass with default (None) caps by running pytest tests/test_admin_payments.py after each adjacent code change, not just at the end.
Runpytest tests/test_scheduler.py tests/test_social_publish_service.py after all code changes. Caps run only in request_payment; these tests should pass without modification because:
test_scheduler.py exercises claim_due_payment_requests → execute_payment which we did NOT touch.
test_social_publish_service.py constructs PaymentService without the new kwargs → they default to None → no cap enforcement.
If either fails, read the failure and fix the code (not the test) unless the test is making an assumption that violates the new invariants; flag any test changes in the plan output.
Step 15: Run the full suite (tests/)
Scope: Small
Runpytest tests/ end-to-end. Every test must pass.
If any unrelated test fails, stop and investigate — do not hand-wave or skip.
Phase 5 (tests) — run targeted new tests after each phase, then the full suite at the end.
Between phases, run the relevant subset of tests as a cheap trip-wire before moving on:
After Phase 1: pytest tests/test_admin_payments.py -k confirm.
After Phase 2: pytest tests/test_admin_payments.py -k "wallet or slot or idempotent".
After Phase 3: pytest tests/test_admin_payments.py -k "cap or success_dm" + pytest tests/test_scheduler.py.
After Phase 5: full pytest tests/.
Validation Order
Unit tests (new + existing) — pytest tests/test_admin_payments.py.
Adjacent suites — pytest tests/test_scheduler.py tests/test_social_publish_service.py (regression pins that caps don't leak into scheduler or social flows).
Full suite — pytest tests/.
Manual read-through — re-audit payment_service.request_payment and admin_chat_cog._handle_wallet_received against the invariants list above, looking specifically for any path that (a) silently drops a final payout, (b) bypasses cap enforcement for solana_payouts, or (c) allows a wallet swap mid-flow.
Git history audit memo — ensure Step 3's findings are recorded in the review output. If any real secret was found, STOP and raise to the user for rotation before landing.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-10T20:04:10Z",
"hash": "sha256:abe1d19ff09fada593261a833c5fb1b553acfc73cc101006f180453a5a363070",
"questions": [
"Error-surfacing convention for the new upsert_wallet blocked path: should it return a structured {'__error__': ...} sentinel (matches some existing db_handler helpers' return-None style loosely), or raise a dedicated WalletUpdateBlockedError? I can pick the structured sentinel to minimize surface area, but if the codebase has a preferred exception pattern for block/policy violations please point me at an example.",
"Should the cap-breach admin DM fire from inside PaymentService.request_payment (requires wiring a DM callback into the service constructor) or from PaymentCog via a post-insert terminal-handler hook (requires the newly-inserted manual_hold row to be routed through _handle_terminal_payment, which may not currently fire on insertion)? Default assumption: wire a callback into PaymentService.__init__ and pass payment_cog._dm_admin_payment_failure from main.py.",
"For the rolling 24h cap, should confirmed rows count against the window (preventing a burst of fresh requests from slipping under the cap when prior payouts have already settled) or should the window be non-terminal only (so completed payouts free the budget)? Default: include confirmed in the window for fail-closed semantics. Confirm this matches the intent.",
"Should manual_hold rows count against the rolling daily cap? Default: NO \u2014 held rows represent money that was blocked, not committed, so excluding them keeps the cap semantically 'committed + in-flight USD'. Confirm.",
"Default env var names \u2014 is ADMIN_PAYOUT_PER_PAYMENT_USD_CAP, ADMIN_PAYOUT_DAILY_USD_CAP, ADMIN_PAYMENT_SUCCESS_DM_THRESHOLD_USD acceptable, or do you prefer a different prefix to match existing naming (e.g., PAYMENTS_*, SOLANA_PAYOUTS_*)?",
"Should the cap enforcement also apply to amount_token-denominated requests (i.e., when the caller passes amount_token directly instead of amount_usd)? The admin_chat final payout at admin_chat_cog.py:360 passes amount_token=float(intent['requested_amount_sol']) with no amount_usd. Default: derive amount_usd from amount_token * token_price_usd for cap-check purposes when the provider is capped and is_test is False, so the cap applies to ALL admin payouts regardless of denomination. Confirm \u2014 otherwise admin_chat payouts bypass the USD cap entirely, which defeats the point.",
"Does _handle_terminal_payment (payment_cog.py:267) currently get invoked for payments inserted directly in manual_hold status, or only for payments that transition into a terminal status via the scheduler? If the former, the cap-breach DM + collision DM can reuse it; if the latter, we need to fire the DM explicitly from request_payment via the callback pattern."
],
"success_criteria": [
{
"criterion": "All existing tests in tests/test_admin_payments.py, tests/test_scheduler.py, and tests/test_social_publish_service.py still pass unchanged (default None caps preserve existing PaymentService construction).",
"priority": "must"
},
{
"criterion": "New test test_confirm_rejects_null_recipient_discord_id passes: confirm_payment with recipient_discord_id=None returns None and logs WARN.",
"priority": "must"
},
{
"criterion": "New test verifying privileged_override=True still bypasses null-recipient check passes.",
"priority": "must"
},
{
"criterion": "New test test_confirm_rejects_mismatched_user passes: confirm_payment with a non-matching confirmed_by_user_id returns None.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_per_payment_cap_manual_holds passes: amount_usd over per-payment cap lands the row as manual_hold with cap-breach last_error; grants provider is unaffected.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_rolling_daily_cap_manual_holds passes: rolling 24h aggregation across non-test solana_payouts rows in (pending_confirmation, queued, processing, submitted, confirmed) drives the cap; grants are unaffected.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_collision_detected passes: prior row with different recipient_wallet triggers manual_hold creation plus admin DM, NOT silent replacement.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_same_wallet_creates_fresh_row_after_failure passes: when the only prior rows are terminal and the wallet matches, a new pending_confirmation row is created (pins reordered early-return).",
"priority": "must"
},
{
"criterion": "New test test_idempotent_return_for_nonterminal passes: non-terminal prior row is returned unchanged.",
"priority": "must"
},
{
"criterion": "New test test_upsert_wallet_blocked_during_active_intent passes: upsert_wallet refuses updates while a non-terminal payment_request or active admin_payment_intent exists and _handle_wallet_received surfaces the error.",
"priority": "must"
},
{
"criterion": "New test test_upsert_wallet_unblocked_after_terminal passes: upsert proceeds when only terminal rows exist.",
"priority": "must"
},
{
"criterion": "New test test_admin_success_dm_over_threshold passes: confirmed, non-test, solana_payouts, amount_usd >= threshold triggers _dm_admin_payment_success; under-threshold does not; failure DM path is unchanged.",
"priority": "must"
},
{
"criterion": "New test test_execute_payment_uses_stored_wallet passes: execute_payment passes payment['recipient_wallet'] to provider.send even when wallet_registry has been updated (regression pin).",
"priority": "must"
},
{
"criterion": "New test test_initiate_payment_tool_rejects_wallet_address_arg passes: wallet_address key in params is popped and ignored; wallet is resolved exclusively via db_handler.get_wallet.",
"priority": "must"
},
{
"criterion": "PaymentService constructor accepts per_payment_usd_cap, daily_usd_cap, capped_providers kwargs; all default to None so existing construction sites remain compatible.",
"priority": "must"
},
{
"criterion": "Cap enforcement in PaymentService runs only in request_payment, never in execute_payment; scheduler path (claim_due_payment_requests -> execute_payment) is untouched.",
"priority": "must"
},
{
"criterion": "Cap-breach, collision, and null-recipient paths create a manual_hold row (or reject for null) AND trigger an admin DM; no silent rejection path for these failure modes.",
"priority": "must"
},
{
"criterion": "_dm_admin_payment_success is a new sibling method with distinct prefix/emoji from _dm_admin_payment_failure; _dm_admin_payment_failure itself is unchanged.",
"priority": "must"
},
{
"criterion": "main.py wires per_payment_usd_cap, daily_usd_cap, capped_providers=('solana_payouts',), and admin_success_dm_threshold from env vars with defaults 500/2000/100.",
"priority": "must"
},
{
"criterion": "upsert_wallet blocks the update only when the incoming address differs from the stored address AND an active payment/intent exists; identical-address upserts and upserts without active intents remain unblocked.",
"priority": "must"
},
{
"criterion": "sql/payments.sql has a top-of-file comment block documenting the RLS posture (RLS already enabled, anon/authenticated revoked, service-role bypass); no ALTER TABLE changes.",
"priority": "must"
},
{
"criterion": "Git history secret audit commands from Step 3 are run and findings recorded in the review output (even if empty).",
"priority": "must"
},
{
"criterion": "Log audit grep from Step 11 is performed and findings recorded. If no real leak path found, no log_handler.py code change.",
"priority": "must"
},
{
"criterion": "Admin success DM is provider-scoped to capped_providers (solana_payouts) and threshold-gated; solana_grants payouts never trigger admin success DMs.",
"priority": "must"
},
{
"criterion": "pytest tests/ runs green end-to-end.",
"priority": "must"
},
{
"criterion": "New cap/collision/DM code paths redact wallets via existing _redact_wallet helpers and never log env-var values or key material.",
"priority": "should"
},
{
"criterion": "has_active_payment_or_intent uses the same non-terminal predicate ('completed','failed','cancelled' for intents; 'confirmed','failed','manual_hold','cancelled' for payments) as existing helpers \u2014 no ad-hoc drift.",
"priority": "should"
},
{
"criterion": "Inline comment at the collision-detection + idempotent-return reorder explains WHY terminal rows must not short-circuit the early return.",
"priority": "should"
},
{
"criterion": "Rolling-24h cap helper includes a comment documenting the residual burst-race window under non-serializable Supabase REST access.",
"priority": "should"
},
{
"criterion": "Plan output explicitly states that the P0 prompt-injection premise was already substantially satisfied by prior work, to prevent the review agent from marking prep as incomplete.",
"priority": "should"
},
{
"criterion": "No unrelated refactors or test rewrites beyond what the new behavior strictly requires.",
"priority": "should"
}
],
"assumptions": [
"The existing get_payment_requests_by_producer helper already returns all statuses (no terminal filter), so collision detection can reuse it directly; a new get_payment_requests_for_ref_all alias is documentation only, not a new query.",
"admin_payment_intents 'active' predicate is `status NOT IN ('completed','failed','cancelled')`, matching the existing get_active_intent_for_recipient query at db_handler.py:1754.",
"payment_requests 'active/non-terminal' predicate is `status NOT IN ('confirmed','failed','manual_hold','cancelled')`, covering pending_confirmation, queued, processing, submitted.",
"Rolling 24h cap window INCLUDES confirmed rows (not just in-flight) to enforce fail-closed semantics against burst requests; excludes manual_hold and failed/cancelled.",
"Default cap thresholds are per_payment=500, daily=2000/guild,successDM=100, all env-overridable. capped_providers defaults to frozenset({'solana_payouts'}).",
"The cap-breach admin DM will be routed via a callback wired from main.py into PaymentService.init, invoking payment_cog._dm_admin_payment_failure. This is cleaner than relying on _handle_terminal_payment which is triggered by transitions, not inserts.",
"For admin_chat final payouts that pass amount_token (not amount_usd) at admin_chat_cog.py:360, cap enforcement will derive a usd-equivalent from the provider's get_token_price_usd() for the cap check so the cap applies uniformly. If token price is unavailable, the request is held as manual_hold (fail-closed). Will confirm this assumption before landing.",
"upsert_wallet error surfacing uses a structured {'__error__': 'active_payment_or_intent'} sentinel rather than raising, matching the general return-None-on-failure pattern of neighboring db_handler helpers. If an exception pattern is found to be more idiomatic during implementation, will switch.",
"RLS is already enabled on payment_requests, wallet_registry, and payment_channel_routes (confirmed at sql/payments.sql:192-199); the RLS 'doc' step is comment-only, not a schema change.",
"Git history secret audit is a command-run + memo task; if a real secret is found, the plan escalates to user for rotation rather than attempting history-rewrite automatically.",
"P0 prompt-injection hardening is verification + defensive pop-and-warn + regression test, not a rewrite \u2014 the initiate_payment tool schema at tools.py:580-599 already omits wallet_address.",
"privileged_override=True is NOT currently used in admin_chat test-payment auto-confirmation (the call at admin_chat_cog.py:258-262 passes confirmed_by='auto' + recipient_user_id instead); under the tightened confirm_payment rule, the call still succeeds because recipient_user_id matches the row's recipient_discord_id set at line 244. No change needed at that call site \u2014 will add a clarifying comment.",
"execute_payment's stored-wallet behavior at payment_service.py:244 is code-unchanged; the work for that brief item is a regression test only.",
"conftest.py (currently untracked per git status) likely provides the shared in-memory fake db pattern already used by test_admin_payments.py; will inspect and extend rather than duplicate."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{
"admin-chat-classification": [
{
"id": "DEBT-006",
"concern": "anthropic client may not be initialized when interceptor fires before _ensure_agent.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
}
],
"admin-payments-intent-state": [
{
"id": "DEBT-004",
"concern": "button confirmation path does not directly update admin_payment_intents \u2014 intent sync happens indirectly via handle_payment_result on terminal state.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
},
{
"id": "DEBT-005",
"concern": "no direct bridge from paymentconfirmview to admin_payment_intents.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
}
],
"db-handler-social-publications": [
{
"id": "DEBT-001",
"concern": "mixing fluent client, raw sql, and rpc access patterns in one subsystem increases maintenance surface.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
],
"db-handler-supabase-infrastructure": [
{
"id": "DEBT-002",
"concern": "supabase rpc is untested in this codebase and may require dashboard configuration.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
],
"social-channel-routes": [
{
"id": "DEBT-003",
"concern": "route management tooling is absent, leaving the routing system inert until manual db inserts.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
]
}
code
Escalated debt subsystems:
[]
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Your output template is at: /Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc/.megaplan/plans/harden-the-solana-payment-20260410-2147/critique_output.json
Read this file first — it contains 8 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
code
Additional guidelines:
- Robustness level: heavy. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"Checked src/features/admin_chat/tools.py:580-599 and execute_initiate_payment at src/features/admin_chat/tools.py:2438-2505; the plan correctly treats the prompt-injection item as verification plus defensive hardening, because the live tool schema already omits any wallet field and the wallet is already loaded from db_handler.get_wallet(...).","flagged":false},{"detail":"Checked the required payout-cap item against the real admin payout caller in src/features/admin_chat/admin_chat_cog.py:352-365; that path calls request_payment(... amount_token=float(intent['requested_amount_sol']), amount_usd=None ...), but Step 8 in the plan says cap logic runs only when normalized_amount_usd is not None, so the plan as written does not fully cover the main admin-triggered payout path called out in the brief.","flagged":true},{"detail":"Ran the sample git-history audit commands locally; git log -S 'SOLANA_PRIVATE_KEY' surfaced code changes that introduced env-var names but not literal secret material, the .env history query returned no matches, and gitleaks is not installed, so the audit step remains appropriate but there is no obvious already-exposed secret in the sampled history.","flagged":false}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"Step 5 says to add the active-payment guard in upsert_wallet before the existing-wallet lookup, but the sample code branches on existing before existing = self.get_wallet(...) has run. That control flow is not implementable as written and needs to be reordered or rewritten.","flagged":true},{"detail":"The collision path in Step 6 assumes it can create a fresh manual_hold row whenever any prior (producer, producer_ref, is_test) row has a different wallet, but sql/payments.sql:126-128 still enforces uniqueness for every status except failed and cancelled. If the differing prior row is pending_confirmation, queued, processing, submitted, confirmed, or manual_hold, the insert cannot succeed, so the plan needs an explicit non-insert branch instead of assuming a new held row can always be created.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"upsert_wallet is shared outside admin chat: src/features/grants/grants_cog.py:557-603 also uses it during grant wallet verification. The plan only describes surfacing the blocked-update path in admin_chat_cog._handle_wallet_received, so the broader caller surface is not fully accounted for.","flagged":true},{"detail":"I grepped all real request_payment callers in src/ and only found admin_chat and grants, so the plan's choice to scope caps to an explicit provider set is the right overall boundary as long as the implementation actually handles the admin-chat caller shape.","flagged":false}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"The plan says to grep for PaymentCog( and find a single construction site, but there are two repo instantiations today: main.py:233 and src/features/payments/payment_cog.py:503. If the constructor grows success-DM configuration, both locations need to stay in sync.","flagged":true},{"detail":"The supporting test glue is broader than the plan currently describes. The fake databases and bot doubles that would need to absorb helper or return-shape changes live inline in tests/test_admin_payments.py and tests/test_social_publish_service.py, not only in tests/conftest.py.","flagged":true}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"Checked every confirm_payment caller in src/features/admin_chat/admin_chat_cog.py, src/features/grants/grants_cog.py, and src/features/payments/payment_cog.py; each existing call site passes a concrete confirmed_by_user_id, so the planned null-recipient fail-closed change is compatible with current callers and does not require a caller-side redesign.","flagged":false},{"detail":"Checked the real admin payout caller at src/features/admin_chat/admin_chat_cog.py:352-365; it passes amount_token and omits amount_usd, so any cap logic written around the grants-style USD caller alone will miss the exact caller the brief cares about most.","flagged":true},{"detail":"Checked upsert_wallet callers and found both src/features/admin_chat/admin_chat_cog.py:193-201 and src/features/grants/grants_cog.py:557-562. A truthy sentinel such as {'__error__': ...} would be caught in admin chat only if the new branch is added there, but grants would still treat that dict as a valid wallet record and continue.","flagged":true}]},{"id":"conventions","question":"Does the approach match how the codebase solves similar problems?","findings":[{"detail":"The proposed {'__error__': 'active_payment_or_intent'} return value does not match the surrounding DatabaseHandler convention, which is overwhelmingly Optional[Dict] or bool with None/False on failure across src/common/db_handler.py. That divergence is risky here because current callers already treat any dict as success.","flagged":true},{"detail":"Adding optional provider-scoped kwargs to PaymentService.__init__ is consistent with the existing service construction style, which already injects providers, test_payment_amount, and logger_instance directly for production and tests.","flagged":false}]},{"id":"verification","question":"Is there convincing verification for the change?","findings":[{"detail":"The planned test list does not include a cap test for the admin-chat final-payment path that passes amount_token without amount_usd, even though that is the live caller in src/features/admin_chat/admin_chat_cog.py:352-365. Without that regression test, the cap feature could still ship green while leaving the primary admin payout path uncapped.","flagged":true},{"detail":"The plan adds an admin-chat test for blocked wallet updates, but it does not add any regression coverage for the other live upsert_wallet caller in grants_cog. That leaves the proposed sentinel-versus-exception choice unverified on a real second caller.","flagged":true}]},{"id":"criteria_quality","question":"Are the success criteria well-prioritized and verifiable?","findings":[{"detail":"Several must criteria are not directly verifiable from code, tests, or diff inspection alone, especially the requirements that the git-history audit commands and log-audit grep be run and that their findings be recorded. Those are useful review tasks, but they are not strong must gates for an automated review pipeline.","flagged":true},{"detail":"The numeric/default criteria and the concrete new pytest cases are well-formed yes/no checks, so those parts of the success criteria are appropriately prioritized as must items.","flagged":false}]}],"flags":[{"id":"FLAG-001","concern":"Solana payout caps: Step 8 still leaves admin-chat final payouts uncapped because it keys cap enforcement off normalized_amount_usd, while the live final-payout caller passes amount_token only.","category":"correctness","severity_hint":"likely-significant","evidence":"The live caller in src/features/admin_chat/admin_chat_cog.py:352-365 sends amount_token=float(intent['requested_amount_sol']) and omits amount_usd, but the plan's cap step is written to run only when normalized_amount_usd is not None."},{"id":"FLAG-002","concern":"Wallet registry updates: The proposed upsert_wallet blocked-path sentinel is only handled in admin chat, but grants_cog is another live caller and would treat a truthy sentinel dict as a successful wallet record.","category":"correctness","severity_hint":"likely-significant","evidence":"src/features/admin_chat/admin_chat_cog.py:193-201 and src/features/grants/grants_cog.py:557-562 both call upsert_wallet; the plan only adds blocked-path handling to admin chat while proposing a truthy {'__error__': ...} return shape."},{"id":"FLAG-003","concern":"Payment idempotency: The collision path over-assumes it can insert a new manual_hold row for any prior-wallet mismatch, but the active unique index still blocks inserts when the prior row is not failed or cancelled.","category":"correctness","severity_hint":"likely-significant","evidence":"sql/payments.sql:126-128 keeps (producer, producer_ref, is_test) unique for pending_confirmation, queued, processing, submitted, confirmed, and manual_hold, while Step 6 describes creating a fresh held row for any mismatched prior wallet."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
code
Project directory:
/Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc
Engineering brief produced from the codebase and task details:
### Task Summary
Harden the Solana payment subsystem against the adversarial review: P0 (secret audit of git history, prompt-injection hardening in admin_chat initiate_payment, null recipient_discord_id confirmation bypass), P1 (wallet swap window between test and final, idempotency slot reuse after forced failure, per-payment + rolling daily USD caps on admin-triggered payouts, admin success-DM over threshold), P2 (log audit, RLS posture doc). End-to-end hardening with no half-fixes on the subtle wallet-swap and idempotency paths.
### Key Evidence
- The `initiate_payment` LLM tool schema in admin_chat already does NOT accept a wallet_address parameter — it takes only recipient_user_id, amount_sol, reason. The wallet is looked up via db_handler.get_wallet(guild_id, recipient_user_id, 'solana') at tools.py:2474. The task's P0 premise ('remove LLM-sourced wallet addresses') is largely already satisfied — the plan should (a) grep siblings for any other tool that accepts a wallet_address, (b) add an assertion/docstring in execute_initiate_payment that wallets MUST come from wallet_registry, (c) add a regression test that a wallet_address key in params is ignored. This is verification + defensive assertion, NOT a rewrite. (source: src/features/admin_chat/tools.py:580-599, 2438-2505; relevance: high)
execute_payment ALREADY uses the stored recipient_wallet string from the payment row (payment_service.py:244), not a re-read from wallet_registry. The final payment in admin_chat is created with recipient_wallet=payment['recipient_wallet'] copied from the test payment row (admin_chat_cog.py:356). So execute_payment is safe. The actual wallet-swap risk lives in request_payment's pre-insert check at payment_service.py:84-90, which rejects a new intent whose wallet_id→wallet_registry.wallet_address mismatches the string — causing the entire final-payout to silently drop if the user upserts a new wallet. Fix: block upsert_wallet while an active intent exists (in db_handler.upsert_wallet), don't rely on post-hoc rejection. (source: src/features/payments/payment_service.py:68-90, 244; src/features/admin_chat/admin_chat_cog.py:236, 356; relevance: high)
Null recipient_discord_id confirmation bypass is real: payment_service.confirm_payment at lines 193-202 only checks recipient match if not privileged_override and expected_user_id is not None. A payment with recipient_discord_id=NULL can be confirmed by any user. Fail-closed fix: require expected_user_id AND confirmed_by_user_id to be non-null and match, unless privileged_override=True. sql/payments.sql:77 allows NULL — consider adding a partial CHECK for provider='solana_payouts'. (source: src/features/payments/payment_service.py:193-202; sql/payments.sql:77; relevance: high)
Idempotency slot reuse after forced failure: the unique index uq_payment_requests_active_producer_ref at payments.sql:126-128 is partial WHERE status NOT IN ('failed','cancelled'). Once a row is marked failed, a new row with the same (producer, producer_ref, is_test) can be freely inserted. request_payment (payment_service.py:54-61) early-returns on existing rows but likely only sees non-terminal ones. Since admin_chat uses ONE producer_ref across test AND final payments (admin_chat_cog.py:234, 354), and test failures free the slot, an attacker who forces a test failure can retrigger with a different wallet. Fix: query ALL prior rows for (producer, producer_ref, is_test) including terminal; if any prior row has a different recipient_wallet, log WARN, DM admin, and create the new row as manual_hold. (source: sql/payments.sql:126-128; src/features/payments/payment_service.py:54-61,167-174; src/features/admin_chat/tools.py:2473; src/features/admin_chat/admin_chat_cog.py:234,354; relevance: high)
No USD cap enforcement exists. request_payment accepts arbitrary amount_usd/amount_token with only a > 0 check (payment_service.py:102, 112). manual_hold is already a terminal status in the enum (payments.sql:100) and db_handler.mark_payment_manual_hold is wired. Caps should go in PaymentService.request_payment, provider-scoped to {'solana_payouts'}. Over-cap should create a manual_hold row + admin DM (NOT silent reject), preserving the audit trail. (source: src/features/payments/payment_service.py:32-174; sql/payments.sql:92-102; relevance: high)
| --- | --- | --- |
| src/features/payments/payment_service.py | PaymentService.request_payment, PaymentService.confirm_payment, PaymentService.execute_payment | Core target. Confirm-payment fail-closed fix (lines 193-202). Cap enforcement injection point (after amount_token derivation at lines 90-119, before create_payment_request at 163). Idempotency collision detection before early return at lines 54-61 and in fallback at 167-174. execute_payment at 244 already uses stored wallet — add regression test, no code change. |
| src/features/payments/payment_cog.py | PaymentCog._handle_terminal_payment, PaymentCog._dm_admin_payment_failure | Add sibling _dm_admin_payment_success called from _handle_terminal_payment (lines 267-272) when status=='confirmed', not is_test, provider in admin-payout set, amount_usd>=threshold. Reuse ADMIN_USER_ID env plumbing. Differentiated prefix/emoji from failure DM. |
| src/features/admin_chat/admin_chat_cog.py | AdminChatCog._handle_wallet_received, AdminChatCog._start_admin_payment_flow, AdminChatCog.handle_payment_result | handle_wallet_received (193-218) calls upsert_wallet with no inflight guard — surface new structured error to admin review channel. start_admin_payment_flow (220-271) and handle_payment_result (299-402) handoff reads recipient_wallet from test row (already safe, pin with test). Ensure recipient_discord_id always passed non-null. |
| src/features/admin_chat/tools.py | execute_initiate_payment, initiate_payment tool schema | Tool schema at 580-599 already excludes wallet_address. Grep ALL admin_chat tools for any wallet_address-accepting sibling. Add docstring + defensive pop-and-warn in execute_initiate_payment (2438-2526) asserting wallets must come from wallet_registry. Add test that wallet_address in params is ignored. |
| src/common/db_handler.py | upsert_wallet, get_wallet, get_wallet_by_id, get_payment_requests_by_producer, create_payment_request, mark_payment_manual_hold | upsert_wallet (1417-1465) needs inflight guard via new helper has_active_payment_or_intent(guild_id, discord_user_id). Add new helper get_payment_requests_for_ref_all (no terminal-status filter) for slot-reuse detection. Add new helper get_rolling_24h_payout_usd(guild_id, provider) for daily cap aggregation. |
| sql/payments.sql | wallet_registry schema, payment_requests schema, uq_payment_requests_active_producer_ref | Add top-of-file comment block documenting RLS posture. Do NOT change the partial-index predicate (legitimate retries need it). Collision detection stays in app code. Consider adding a CHECK that recipient_discord_id is non-null when provider='solana_payouts' (defense-in-depth). |
| src/common/log_handler.py | - | Log audit target. Grep for env-var logging, unsanitized tracebacks, os.environ dumps. Add scrubbing filter for SOLANA_PRIVATE_KEY/HELIUS*/ANTHROPIC* only if a real leak path exists. Document findings either way. |
| main.py | PaymentService construction | Lines 157-161 construct PaymentService with providers and test_payment_amount. Pass new kwargs (per_payment_usd_cap, daily_usd_cap, capped_providers, admin_success_dm_threshold_usd) sourced from env with safe defaults (2000/{'solana_payouts'}/$100). |
| tests/test_admin_payments.py | PaymentService integration tests | Extend PaymentService tests at 687+ with adversarial cases: null-recipient reject, cap manual_hold, rolling daily cap, slot-reuse collision, upsert_wallet block, admin success DM, wallet_address tool arg ignored, execute_payment stored-wallet regression pin. Preserve FakeAdminPaymentService happy-path tests. |
| tests/test_scheduler.py | - | Scheduler wrappers (lines 390-584) must still work — caps run only in request_payment, NOT execute_payment, so scheduled queue path is unaffected. Verify. |
| tests/test_social_publish_service.py | - | Existing PaymentService construction (474-685) uses provider dict {'solana': provider}. New caps must be provider-scoped to 'solana_payouts' so these tests remain green with defaults. |
code
### Test Expectations
- [fail_to_pass] tests/test_admin_payments.py::test_confirm_rejects_null_recipient_discord_id: NEW: confirm_payment returns None and logs WARN when recipient_discord_id is NULL and privileged_override is False, regardless of confirmed_by_user_id. privileged_override=True still works for test-payment auto-advance.
[fail_to_pass] tests/test_admin_payments.py::test_request_payment_per_payment_cap_manual_holds: NEW: request_payment with provider='solana_payouts' and amount_usd > per-payment cap creates the row with status='manual_hold', logs WARN, and triggers admin DM. grants provider is unaffected.
[fail_to_pass] tests/test_admin_payments.py::test_request_payment_rolling_daily_cap_manual_holds: NEW: once rolling 24h sum of solana_payouts amount_usd crosses daily cap, next new intent is manual_hold'd even if per-payment amount is under per-payment cap. Grants are unaffected.
[fail_to_pass] tests/test_admin_payments.py::test_slot_reuse_collision_detected: NEW: prior failed row with same (producer, producer_ref, is_test) and DIFFERENT recipient_wallet causes request_payment to log WARN, DM admin, and create the new row as manual_hold (NOT silent replacement).
[fail_to_pass] tests/test_admin_payments.py::test_upsert_wallet_blocked_during_active_intent: NEW: db_handler.upsert_wallet refuses to update wallet_address while a non-terminal payment_requests row OR awaiting_* admin_payment_intents row exists for (guild_id, discord_user_id), and _handle_wallet_received surfaces the error to the admin review channel.
[fail_to_pass] tests/test_admin_payments.py::test_admin_success_dm_over_threshold: NEW: on confirmed non-test solana_payouts payment with amount_usd >= $100, admin is DM'd with success-differentiated message. Under-threshold does NOT DM. Failure DM path is unchanged.
[fail_to_pass] tests/test_admin_payments.py::test_execute_payment_uses_stored_wallet: NEW regression pin: execute_payment passes payment['recipient_wallet'] (frozen stored string) to provider.send, NOT a re-read from wallet_registry. Prevents future regression.
[fail_to_pass] tests/test_admin_payments.py::test_initiate_payment_tool_rejects_wallet_address_arg: NEW: passing a wallet_address key through execute_initiate_payment params is ignored (not persisted, not used for lookup); wallet is exclusively resolved via db_handler.get_wallet(guild_id, recipient_user_id, 'solana').
[pass_to_pass] tests/test_admin_payments.py (existing happy-path): Existing happy path (wallet capture → test → confirm → final → notify) still passes with new caps/collision logic (test uses high cap).
[pass_to_pass] tests/test_scheduler.py (existing): Scheduler queue path still advances queued payments; caps run only in request_payment, not execute_payment.
[pass_to_pass] tests/test_social_publish_service.py (existing PaymentService tests): Social publish service's PaymentService usage keeps working — new caps are scoped to 'solana_payouts', these tests use different provider names.
code
Groundwork (P2, low-risk): add RLS-posture comment block at the top of sql/payments.sql. Extend tests/conftest.py with an in-memory wallet_registry + payment_requests store if one doesn't already exist, so adversarial tests can operate against real PaymentService logic.
P0: Null recipient_discord_id fail-closed (payment_service.py:193-202). Change to if not privileged_override: if expected_user_id is None or confirmed_by_user_id is None or int(expected_user_id) != int(confirmed_by_user_id): log WARN; return None. Ship with the new test. Audit every confirm_payment call site (payment_cog.py + admin_chat_cog.py:258-262) to ensure no flow relies on NULL recipient.
P0: admin_chat prompt-injection verification. Grep ALL admin_chat tools for 'wallet_address' / 'address' fields in input_schema. If any sibling tool accepts a raw wallet, remove or harden. Add a docstring + defensive params.pop('wallet_address', None) with WARN log at the top of execute_initiate_payment. Add the tool-arg-ignored test. Explicitly record in the plan that the task's P0 premise was already substantially implemented.
P1: upsert_wallet inflight block (db_handler.py:1417-1465). Add helper has_active_payment_or_intent(guild_id, discord_user_id) querying non-terminal payment_requests + awaiting_* admin_payment_intents. Verify exact admin_payment_intents status enum values before coding the 'active' predicate. Return structured error from upsert_wallet on conflict. Update _handle_wallet_received (admin_chat_cog.py:193-218) to surface to admin review channel.
P1: Idempotency slot-reuse collision detection (payment_service.py:54-61, 167-174). Add db_handler helper get_payment_requests_for_ref_all(producer, producer_ref, is_test) that does NOT filter terminal. Before the idempotent early-return, query this helper: if any prior row has a different recipient_wallet than the incoming request, log WARN, DM admin, create the new row as manual_hold (do NOT return the old non-terminal row as if nothing happened). Be careful the early-return at lines 54-61 does not short-circuit BEFORE collision detection.
P1: Per-payment + rolling daily USD caps in PaymentService. Add constructor kwargs per_payment_usd_cap, daily_usd_cap, capped_providers=frozenset({'solana_payouts'}), default to None (disabled) for backward-compat with existing tests. In request_payment, after amount_token derivation, if provider in capped_providers and not is_test: if amount_usd > per_payment_cap OR get_rolling_24h_payout_usd(guild_id, provider) + amount_usd > daily_cap → create the row with status='manual_hold' + last_error='cap exceeded' + admin DM. Add db_handler helper get_rolling_24h_payout_usd that sums amount_usd across pending_confirmation/queued/processing/submitted/confirmed within 24h. If serializable transaction is impractical, document residual burst window.
Subtle pitfalls:
In step 5, the idempotent early return at payment_service.py:54-61 must be reordered to run AFTER collision detection, OR collision detection must happen inside that branch too.
In step 6, rolling window MUST include in-flight statuses, not just confirmed, to prevent concurrent burst slip-through.
In step 4, read admin_payment_intents table schema + db_handler.create_admin_payment_intent to enumerate exact status values before hardcoding the 'active' set.
The initial P0 premise about LLM-sourced wallet addresses appears already fixed by a prior change — state this explicitly in the plan so review doesn't reject prep as incomplete; the work is verification + defensive assertion + test.
Do NOT double-check caps in execute_payment. Caps run only in request_payment. Scheduler path (claim_due_payment_requests → execute_payment) must not hit cap logic.
privileged_override=True must remain usable for test-payment auto-advance (admin_chat_cog.py:258-262). Verify the test payment row carries recipient_discord_id (it does via line 244) so it doesn't hit the new null-reject branch anyway.
code
The engineering brief above was produced by analyzing the codebase. Use it as a strong starting point, but the suggested approach is a hypothesis — verify it's the best fix, not just a valid one.
Idea:
Harden the Solana payment subsystem against the attack vectors found by the adversarial security review. Fix P0: git history secret audit, prompt-injection hardening in admin_chat (remove LLM-sourced wallet addresses from initiate_payment tool; wallets must come from wallet_registry keyed by mentioned Discord user), null recipient_discord_id confirmation bypass (fail-closed). Fix P1: wallet swap window between test and final payment (verify execute_payment uses stored recipient_wallet string; reject or warn on upsert_wallet during active intents), idempotency slot reuse after forced failure (warn/DM on producer_ref collision with prior failed row having different wallet), per-payment and rolling daily USD cap on admin-triggered payouts enforced in PaymentService (default 500/payment,2000/day/guild, exceeding goes to manual_hold), admin DM on successful admin_chat payouts over threshold (default $100, differentiated from failure DMs). Fix P2: log audit for secret leakage, document RLS posture at top of sql/payments.sql. Already using Helius so RPC attacks out of scope. Two wallets already split into solana_grants and solana_payouts providers. Think carefully about wallet-swap and idempotency — they are subtle and easy to half-fix. Goal is end-to-end hardening.
Implement the P0/P1/P2 hardening from the adversarial review against src/features/payments/ and src/features/admin_chat/. Layered fail-closed: (1) correctness first (null recipient, prompt-injection defense, inflight wallet lock via exception), (2) monetary safety (idempotency collision with index-aware branching, per-payment + rolling daily USD caps that derive USD from amount_token when needed), (3) observability (admin success DM, log audit memo, RLS posture comment, git history audit memo).
Corrections confirmed against the repo
RLS is already enabled on wallet_registry, payment_channel_routes, payment_requests (sql/payments.sql:192-199). Step 12 is comment-only.
P0 prompt-injection is already substantially satisfied: the initiate_payment tool schema at src/features/admin_chat/tools.py:580-599 omits wallet_address, and execute_initiate_payment resolves wallets via db_handler.get_wallet(...) at tools.py:2474. The work here is verification + defensive pop-and-warn + regression test, NOT a rewrite.
get_payment_requests_by_producer at db_handler.py:1853 already returns rows across all statuses (no terminal filter), so collision detection re-uses it. The bug in request_payment at payment_service.py:54-61 is that existing_rows[0] is returned unconditionally — if the first prior row is failed, the caller sees a failed row as if it were fresh.
execute_payment already uses the stored recipient_wallet (payment_service.py:244). No code change — regression pin only.
Admin-chat final payout passes amount_token only, not amount_usd (admin_chat_cog.py:352-365). Cap logic must derive a USD equivalent from the provider token price to cover this path; fail-closed to manual_hold if price is unavailable.
upsert_wallet has two live callers: admin_chat_cog.py:193-201 and grants_cog.py:557-565. Both check if not wallet_record. Blocked-path signalling must be an exception (WalletUpdateBlockedError) so a truthy sentinel cannot be mistaken for a successful record by either caller.
Partial unique indexuq_payment_requests_active_producer_ref at sql/payments.sql:126-128 is WHERE status NOT IN ('failed','cancelled'). So manual_hold, pending_confirmation, queued, processing, submitted, confirmed all participate in uniqueness. A new manual_hold insert is only safe when every prior row is either failed or cancelled. Collision handling must branch on that.
Key invariants (non-negotiable)
Fail-closed. Null recipient → reject. Cap breach → manual_hold + admin DM. Wallet-swap collision → branch per unique-index rule (see Step 6) with admin DM. Inflight wallet change → raise WalletUpdateBlockedError. Never silent.
Provider-scoped caps. Caps and admin success DM apply only to providers in capped_providers (default frozenset({'solana_payouts'})). solana_grants is untouched.
Do NOT change the partial-index predicate. Collision handling stays in app code and respects the existing predicate.
Do NOT re-read recipient_wallet in execute_payment. Frozen-string semantics at payment_service.py:244. Pin with a regression test.
Do NOT add cap logic in execute_payment. Caps run only in request_payment.
Do NOT widen upsert_wallet's block window. Block only when the incoming address differs AND a non-terminal payment_requests row OR a non-terminal admin_payment_intents row exists for (guild_id, discord_user_id). Identical-address upserts and upserts with only terminal history remain unblocked.
Preserve privileged_override=True for any future auto-advance path. Current admin-chat test auto-confirm passes confirmed_by_user_id=int(intent['recipient_user_id']) and the test row carries matching recipient_discord_id, so the tightened check passes without needing override.
No secret logging. New logs redact wallets via existing _redact_wallet helpers; never log env or key material.
Cap config is injectable via constructor kwargs. Defaults are None (disabled) so existing tests construct PaymentService unchanged.
Modifyconfirm_payment at payment_service.py:193-202. Replace the current if not privileged_override and expected_user_id is not None: with:
python
if not privileged_override:
if (
expected_user_id is None
or confirmed_by_user_id is None
or int(expected_user_id) != int(confirmed_by_user_id)
):
self.logger.warning(
"[PaymentService] rejected confirmation for %s: expected_user=%s confirmed_by=%s",
payment_id, expected_user_id, confirmed_by_user_id,
)
return None
Audit every confirm_payment call site via Grep for confirm_payment(. Verify button confirmations always carry a user, grants auto-confirm at grants_cog.py:596-601 passes confirmed_by_user_id=grant['applicant_id'], and the admin-chat test auto-confirm at admin_chat_cog.py:258-262 passes confirmed_by_user_id=int(intent['recipient_user_id']) (matching the row's recipient_discord_id at line 244). Add a 1-line comment at each call site explaining why the tightened rule still permits the call.
Grepsrc/features/admin_chat/tools.py for every tool schema in ADMIN_CHAT_TOOLS. Confirm none contain wallet_address, address, solana_address, recipient_wallet, wallet. If any are found, strip them from both the schema and the corresponding execute function.
Modifyexecute_initiate_payment at tools.py:2438. Add a short docstring and a defensive pop at the top of the function body (after arg-coercion):
python
# Wallets are resolved exclusively via db_handler.get_wallet(...). The LLM
# MUST NOT supply wallet strings; reject silently with a WARN log if it does.
if 'wallet_address' in params or 'recipient_wallet' in params:
logger.warning(
"[AdminChat] execute_initiate_payment ignoring LLM-sourced wallet fields"
)
params.pop('wallet_address', None)
params.pop('recipient_wallet', None)
Record in the plan output that P0 prompt-injection was already substantially satisfied by prior work; this step is verification + defensive assertion + regression test.
Step 3: Git history secret audit memo (no code change)
Document findings (even if empty) in a memo block at the top of the review output. If any real secret is found, STOP and flag to the user for rotation.
Add a new DatabaseHandler.has_active_payment_or_intent(self, guild_id: int, discord_user_id: int) -> bool alongside list_active_intents.
Query 1 — payment_requests WHERE guild_id=? AND recipient_discord_id=? AND status NOT IN ('confirmed','failed','manual_hold','cancelled') LIMIT 1.
Query 2 — admin_payment_intents WHERE guild_id=? AND recipient_user_id=? AND status NOT IN ('completed','failed','cancelled') LIMIT 1. (Matches get_active_intent_for_recipient at db_handler.py:1754 and list_active_intents at db_handler.py:1782.)
Return True if either query returns a row. Use _gate_check(guild_id) and the supabase-guard pattern for consistency with neighbors.
Add a new exception class at the top of db_handler.py (or in a small exceptions.py neighbour if preferred): class WalletUpdateBlockedError(Exception): pass. Export from db_handler so callers can import it.
Modifyupsert_wallet at db_handler.py:1417-1465. Order matters — the existing-wallet lookup at line 1431 must run FIRST, then the block check, then the update. Insert the guard afterexisting = self.get_wallet(...):
python
existing = self.get_wallet(guild_id, discord_user_id, chain)
if existing and existing.get('wallet_address') != address:
if self.has_active_payment_or_intent(guild_id, discord_user_id):
logger.warning(
"[DB] upsert_wallet blocked: active payment/intent for guild %s user %s",
guild_id, discord_user_id,
)
raise WalletUpdateBlockedError(
"wallet update blocked while an active payment or intent exists"
)
Identical-address upserts (and upserts with no prior row) are unaffected.
Modify_handle_wallet_received at admin_chat_cog.py:193-218. Wrap the upsert_wallet call in try/except WalletUpdateBlockedError and surface the error:
python
try:
wallet_record = self.db_handler.upsert_wallet(...)
except WalletUpdateBlockedError:
await self._notify_admin_review(
message.channel, intent,
"I cannot update this wallet address: an active payment is in flight. "
"Please wait for it to resolve or cancel the current intent.",
resolved_by_message_id=message.id,
)
return
if not wallet_record:
# existing general-failure branch unchanged
...
at . Wrap the call in the same . Surface a user-facing message to the grant thread and early-return (do NOT continue to with a missing wallet):
Step 6: Idempotency collision detection with index-aware branching (src/features/payments/payment_service.py)
Scope: Medium
Readdb_handler.py:1853-1883 to confirm get_payment_requests_by_producer returns all statuses with no terminal filter. If confirmed, reuse it directly — no new helper needed. Add an inline comment in payment_service.py clarifying the invariant so future refactors do not add a filter.
Reworkrequest_payment at payment_service.py:54-61. Replace the unconditional return existing_rows[0] with collision-first, index-aware branching:
python
all_prior_rows = self.db_handler.get_payment_requests_by_producer(
guild_id=guild_id, producer=producer,
producer_ref=producer_ref, is_test=is_test,
)
normalized_wallet = str(recipient_wallet or '').strip()
INDEX_EXCLUDED = {'failed', 'cancelled'}
# Terminal for the idempotency-return check — rows we should NOT reuse as a
# fresh pending row (caller would treat a failed row as a live request).
TERMINAL_FOR_RETURN = {'confirmed', 'failed', 'manual_hold', 'cancelled'}
collision_row = None
blocking_prior_row = None # prior row still covered by the unique index
for row in all_prior_rows:
prior_wallet = str(row.get('recipient_wallet') or '').strip()
prior_status = str(row.get('status') or '').lower()
if prior_status not in INDEX_EXCLUDED:
blocking_prior_row = row # any non-excluded row blocks a fresh insert
if prior_wallet and normalized_wallet and prior_wallet != normalized_wallet:
collision_row = row # remember the first wallet mismatch we saw
break
# Legitimate idempotent early-return: only when a non-terminal prior row
# with the SAME wallet exists. Terminal rows must NOT short-circuit here —
# otherwise a failed prior row is surfaced to the caller as if fresh.
if not collision_row:
active_same_wallet = [
r for r in all_prior_rows
if str(r.get('status') or '').lower() not in TERMINAL_FOR_RETURN
and str(r.get('recipient_wallet') or '').strip() == normalized_wallet
]
if active_same_wallet:
return active_same_wallet[0]
status IN ('pending_confirmation','queued','processing','submitted','confirmed')
created_at >= now() - interval '24 hours'
Sumamount_usd across results; coerce nulls to 0.0; return float.
Comment: "Supabase REST has no serializable transaction — this aggregation races concurrent burst calls. Residual window is ~RPC latency (~100-500ms). Downstream manual_hold + admin DM is the fail-closed backstop."
Stub this helper in the inline fakes used by tests/test_admin_payments.py and tests/test_social_publish_service.py — return 0.0 by default so existing tests (which pass no caps) are unaffected.
Step 8: PaymentService cap enforcement covering amount_usd AND amount_token (src/features/payments/payment_service.py, main.py)
Normalize: self.per_payment_usd_cap = float(...) if provided else None, self.capped_providers = frozenset((p or '').lower() for p in (capped_providers or ())), self._on_cap_breach = on_cap_breach. Defaults are all None/empty so existing test constructions at tests/test_admin_payments.py:687+ and tests/test_social_publish_service.py:474-685 remain compatible.
Inject cap logic in request_paymentafter amount_token derivation (lines 90-119) and beforecreate_payment_request (line 163). This runs for both the amount_usd and amount_token callers:
python
cap_usd: Optional[float] = None
if not is_test and provider.strip().lower() in self.capped_providers:
if normalized_amount_usd is not None:
cap_usd = normalized_amount_usd
else:
# amount_token-only caller (e.g. admin_chat final payout). Derive
# USD from the provider token price for cap-check purposes. If
# price is unavailable, fail closed to manual_hold.
price = token_price_usd
if price is None:
try:
price = await payment_provider.get_token_price_usd()
except Exception as exc:
self.logger.warning(
"[PaymentService] token price lookup failed for cap check: %s", exc,
)
price = None
if price and price > 0:
cap_usd = float(amount_token) * float(price)
else:
cap_usd = None # sentinel: price unavailable → fail closed below
Step 9: Admin success DM over threshold (src/features/payments/payment_cog.py)
Scope: Small
ExtendPaymentCog.__init__ to read env with defaults inside the constructor (so both construction sites at main.py:233 and the setup(bot) hook at payment_cog.py:503 pick it up without changes):
python
import os
self._admin_success_dm_threshold_usd = float(
os.getenv('ADMIN_PAYMENT_SUCCESS_DM_THRESHOLD_USD', '100')
)
self._admin_success_dm_providers = frozenset(
p.strip().lower()
for p in (os.getenv('ADMIN_PAYMENT_SUCCESS_DM_PROVIDERS', 'solana_payouts').split(','))
if p.strip()
)
Add a sibling method _dm_admin_payment_success(self, payment) modeled on _dm_admin_payment_failure at payment_cog.py:273-333, but with:
Wallet redacted via existing _redact_wallet helpers.
Invoke from _handle_terminal_payment at lines 267-271, alongside (not replacing) the failure path:
python
if payment.get('status') == 'confirmed' and not payment.get('is_test'):
provider = str(payment.get('provider') or '').lower()
amount_usd = float(payment.get('amount_usd') or 0)
if (
provider in self._admin_success_dm_providers
and amount_usd >= self._admin_success_dm_threshold_usd
):
await self._dm_admin_payment_success(payment)
Do NOT modify _dm_admin_payment_failure.
Step 10: Wire caps + cap-breach DM into main (main.py)
where _bind_cap_breach_dm(bot) returns a small async def closure that looks up bot.get_cog('PaymentCog') and calls _dm_admin_payment_failure(payment) (or a new _dm_admin_payment_cap_breach sibling if the failure DM's wording does not fit — decide during implementation after reading _dm_admin_payment_failure's body).
Document findings in the review memo. Default expectation: no code change, memo only. Only add a scrubbing filter in log_handler.py if a real leak path is found — and flag it explicitly.
Add a comment block at the very top of sql/payments.sql (before create extension):
sql
-- RLS posture:
-- * Row-level security is ENABLED on wallet_registry, payment_channel_routes,
-- and payment_requests (see `alter table ... enable row level security` below).
-- * All access is mediated by DatabaseHandler using the Supabase service role,
-- which bypasses RLS. No anon/authenticated clients access these tables.
-- * anon and authenticated roles have ALL privileges revoked; no policies are
-- defined because no non-service-role access path exists.
-- * Writes are parameterized via supabase-py; no raw SQL string interpolation.
-- * Changing this posture (e.g. exposing tables to a browser client) requires
-- writing explicit row-level policies first — do NOT simply grant.
Do NOTALTER TABLE. Comment-only.
Phase 5: Tests
Step 13: Extend PaymentService test suite (tests/test_admin_payments.py, tests/conftest.py, tests/test_social_publish_service.py)
Scope: Medium
Inspect the currently-untracked tests/conftest.py and the inline fake-db classes in tests/test_admin_payments.py:497-729 and tests/test_social_publish_service.py:474-685. Whichever fake is used, extend it with:
A has_active_payment_or_intent(guild_id, user_id) method.
A get_rolling_24h_payout_usd(guild_id, provider) method (returns 0.0 by default).
A raise WalletUpdateBlockedError path on upsert_wallet when configured to simulate an active intent.
Import WalletUpdateBlockedError from wherever Step 5 lands it.
Keep the changes additive — existing happy-path tests must keep passing with the new defaults.
Add fail-to-pass tests (each against a real PaymentService wired to the fake DatabaseHandler):
test_confirm_rejects_null_recipient_discord_id — payment with recipient_discord_id=None, privileged_override=False → returns None + WARN. Passes with privileged_override=True.
test_request_payment_amount_token_path_cap_breach — new: caller passes amount_token=5.0 with no amount_usd, provider token price is 1100 → . Pins the admin-chat path.
Step 14: Verify scheduler + social publish tests untouched
Scope: Small
Runpytest tests/test_scheduler.py tests/test_social_publish_service.py after all code changes. These should pass unchanged because:
Phase 3 (rolling 24h helper → cap enforcement covering both amount_usd and amount_token paths → success DM sibling → main.py wiring).
Phase 4 (log audit memo + RLS comment).
Phase 5 (targeted tests after each phase, full suite at the end).
Between phases, run the cheap trip-wire subsets:
After Phase 1: pytest tests/test_admin_payments.py -k "confirm or initiate_payment".
After Phase 2: pytest tests/test_admin_payments.py -k "wallet or slot or collision or idempotent".
After Phase 3: pytest tests/test_admin_payments.py -k "cap or success_dm or token_path" + pytest tests/test_scheduler.py.
After Phase 5: full pytest tests/.
Validation Order
Unit tests (new + existing) — pytest tests/test_admin_payments.py.
Adjacent suites — pytest tests/test_scheduler.py tests/test_social_publish_service.py (regression pins that caps don't leak into scheduler or social flows).
Full suite — pytest tests/.
Manual read-through — re-audit payment_service.request_payment and admin_chat_cog._handle_wallet_received and grants_cog._start_payment_flow against the invariants list, looking specifically for any path that (a) silently drops a final payout, (b) lets an amount_token-only caller bypass cap enforcement, (c) allows a wallet swap mid-flow, or (d) attempts a new manual_hold insert while a non-terminal prior row still holds the unique-index slot.
Git-history + log audit memos recorded in the review output. If any real secret leak is found, STOP and escalate.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-04-10T20:39:31Z",
"hash": "sha256:b0ea146ad02a6a83a704a55270292fea94160874a299ed04423c43832eb22527",
"changes_summary": "Resolved all 12 open significant flags. (1) Cap enforcement now covers amount_token-only callers (admin_chat final payout): derives USD from provider.get_token_price_usd() and fail-closes to manual_hold if price is unavailable. Added two new tests pinning that path. (2) upsert_wallet blocking is now exception-based (WalletUpdateBlockedError) and both live callers \u2014 admin_chat._handle_wallet_received AND grants_cog._start_payment_flow \u2014 catch it explicitly, eliminating the truthy-sentinel trap. (3) Collision handling is now index-aware with two explicit branches: Branch A inserts a fresh manual_hold row only when every prior row is failed/cancelled (index permits); Branch B returns None without attempting an insert when a prior row still holds a unique-index slot, and the admin DM fires in both cases. Added a new Branch-B test. (4) Step 5's control flow is fixed: the existing-wallet lookup now runs before the guard, and the sample code matches the real call order. (5) PaymentCog success-DM config is now read inside init from env so both construction sites (main.py:233 and the setup() hook at payment_cog.py:503) stay in sync without touching either caller. (6) Test glue expansion is explicit: inline fakes in test_admin_payments.py and test_social_publish_service.py are named as the sites where has_active_payment_or_intent, get_rolling_24h_payout_usd, and WalletUpdateBlockedError stubs must land. (7) Criteria quality: demoted git-history-audit and log-audit from must to should (they are memo tasks, not diff-verifiable); added must criteria for the two new token-path cap tests and the Branch-B collision test. No scope creep; the plan remains aligned with the original P0/P1/P2 brief.",
"flags_addressed": [
"FLAG-001",
"FLAG-002",
"FLAG-003",
"issue_hints",
"correctness-1",
"correctness-2",
"scope",
"all_locations-1",
"all_locations-2",
"callers-1",
"callers-2",
"criteria_quality"
],
"questions": [
"Should the cap-breach DM re-use _dm_admin_payment_failure (cheapest, but the wording says 'requires manual review' which fits) or become a third sibling _dm_admin_payment_cap_breach with slightly softer wording? Default: re-use dm_admin_payment_failure since cap-breach IS manual-review-required, and a manual_hold row will appear in the admin queue.",
"For Branch B of the collision path (prior row still in a non-excluded status), should the response include the prior row's payment_id in the admin DM so an operator can inspect it directly? Default: yes, include prior_payment_id and prior_status in the DM payload.",
"Should WalletUpdateBlockedError live in src/common/db_handler.py next to DatabaseHandler, or in a new src/common/exceptions.py module? Default: same file as DatabaseHandler to minimize surface area unless the codebase already has an exceptions module (will grep first).",
"For the amount_token cap path, should the derived USD also be stamped into record['amount_usd'] so downstream reporting sees it, or kept local to the cap check? Default: kept local \u2014 the admin-chat flow historically stores amount_usd=None for token-denominated requests and downstream code handles that; changing it would have broader reporting implications outside this task.",
"Env var names acceptable as ADMIN_PAYOUT_PER_PAYMENT_USD_CAP / ADMIN_PAYOUT_DAILY_USD_CAP / ADMIN_PAYMENT_SUCCESS_DM_THRESHOLD_USD / ADMIN_PAYMENT_SUCCESS_DM_PROVIDERS? If a different prefix (e.g. SOLANA_PAYOUTS*) is preferred for consistency, flag before landing."
],
"success_criteria": [
{
"criterion": "All existing tests in tests/test_admin_payments.py, tests/test_scheduler.py, and tests/test_social_publish_service.py pass unchanged (default None caps preserve existing PaymentService construction).",
"priority": "must"
},
{
"criterion": "New test test_confirm_rejects_null_recipient_discord_id passes: confirm_payment with recipient_discord_id=None returns None and logs WARN.",
"priority": "must"
},
{
"criterion": "New test verifying privileged_override=True still bypasses the null-recipient check passes.",
"priority": "must"
},
{
"criterion": "New test test_confirm_rejects_mismatched_user passes: confirm_payment with a non-matching confirmed_by_user_id returns None.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_per_payment_cap_manual_holds passes: amount_usd over per-payment cap lands the row as manual_hold with cap-breach last_error; grants provider is unaffected.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_amount_token_path_cap_breach passes: caller supplies amount_token with no amount_usd, derived USD (amount_token * token_price_usd) exceeds the cap \u2192 manual_hold. Pins the admin-chat final-payout path.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_amount_token_path_missing_price_holds passes: amount_token path with provider returning None/0 for token price \u2192 manual_hold with last_error='cap check unavailable'. Fail-closed pin.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_rolling_daily_cap_manual_holds passes: rolling 24h aggregation across non-test solana_payouts rows in (pending_confirmation, queued, processing, submitted, confirmed) drives the cap; grants are unaffected.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_collision_detected_after_failure passes: only prior rows are failed/cancelled with a different wallet \u2192 a fresh manual_hold row IS inserted (Branch A) and on_cap_breach fires.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_collision_blocked_when_prior_active passes: prior row is pending_confirmation/queued/etc with a different wallet \u2192 request_payment returns None without attempting an insert (Branch B), the prior row is NOT replaced, and on_cap_breach fires. Pins index-aware branching.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_same_wallet_creates_fresh_row_after_failure passes: only terminal prior rows with matching wallet \u2192 new pending_confirmation row is created (pins reordered early-return).",
"priority": "must"
},
{
"criterion": "New test test_idempotent_return_for_nonterminal passes: non-terminal prior row with matching wallet is returned unchanged.",
"priority": "must"
},
{
"criterion": "New test test_upsert_wallet_raises_during_active_intent passes: upsert_wallet raises WalletUpdateBlockedError while a non-terminal payment_requests OR admin_payment_intents row exists; admin_chat._handle_wallet_received catches it and surfaces to the admin review channel; grants_cog._start_payment_flow catches it and surfaces to the grant thread.",
"priority": "must"
},
{
"criterion": "New test test_upsert_wallet_unblocked_after_terminal passes: upsert_wallet proceeds when only terminal rows exist, and when the incoming address matches the stored address even while an active intent exists.",
"priority": "must"
},
{
"criterion": "New test test_admin_success_dm_over_threshold passes: confirmed, non-test, solana_payouts, amount_usd >= threshold triggers _dm_admin_payment_success; under-threshold does not; failure DM path is unchanged.",
"priority": "must"
},
{
"criterion": "New test test_execute_payment_uses_stored_wallet passes: execute_payment passes payment['recipient_wallet'] (frozen) to provider.send even when wallet_registry has been updated. Regression pin.",
"priority": "must"
},
{
"criterion": "New test test_initiate_payment_tool_rejects_wallet_address_arg passes: wallet_address/recipient_wallet keys in params are popped and ignored; wallet is resolved exclusively via db_handler.get_wallet.",
"priority": "must"
},
{
"criterion": "PaymentService constructor accepts per_payment_usd_cap, daily_usd_cap, capped_providers, and on_cap_breach kwargs; all default to None so existing construction sites remain compatible.",
"priority": "must"
},
{
"criterion": "Cap enforcement in PaymentService runs only in request_payment, never in execute_payment. Scheduler path (claim_due_payment_requests -> execute_payment) is untouched.",
"priority": "must"
},
{
"criterion": "Cap enforcement covers BOTH amount_usd-supplying callers AND amount_token-only callers. amount_token-only path derives USD via provider.get_token_price_usd(); if price is unavailable, the row is held as manual_hold (fail-closed).",
"priority": "must"
},
{
"criterion": "Cap-breach, collision (Branch A insert and Branch B reject), and null-recipient paths trigger an admin DM via on_cap_breach or equivalent path. No silent rejection.",
"priority": "must"
},
{
"criterion": "Collision handling is index-aware: Branch A (prior rows all failed/cancelled) inserts a fresh manual_hold row; Branch B (any prior row in a non-excluded status) returns None without attempting an insert. No code path tries to insert a manual_hold row that would violate uq_payment_requests_active_producer_ref.",
"priority": "must"
},
{
"criterion": "upsert_wallet blocked path raises WalletUpdateBlockedError (not a truthy sentinel). Both admin_chat._handle_wallet_received and grants_cog._start_payment_flow catch the exception and surface a user-facing message without continuing to request_payment.",
"priority": "must"
},
{
"criterion": "upsert_wallet's existing-wallet lookup runs BEFORE the has_active_payment_or_intent guard so the control flow is implementable. Identical-address upserts and upserts with no prior row are never blocked.",
"priority": "must"
},
{
"criterion": "_dm_admin_payment_success is a new sibling method with a distinct prefix ('\u2705 ') and no 'requires manual review' line. _dm_admin_payment_failure is unchanged.",
"priority": "must"
},
{
"criterion": "PaymentCog reads success-DM threshold and provider set from env inside with defaults (500/500, daily=100. capped_providers defaults to frozenset({'solana_payouts'}).",
"Cap-breach admin DM is routed via an async callback wired from main.py into PaymentService., invoking payment_cog's failure/cap-breach DM. Cleaner than relying on _handle_terminal_payment which only fires on status transitions, not inserts.",
"For amount_token-only callers (admin_chat final payout), cap enforcement derives USD via provider.get_token_price_usd() * amount_token. If the price lookup fails or returns non-positive, the row is held as manual_hold with last_error='cap check unavailable'. This is the core correctness fix for FLAG-001.",
"upsert_wallet blocked path raises a dedicated WalletUpdateBlockedError exception (not a truthy sentinel), so both admin_chat and grants_cog must catch it explicitly \u2014 eliminating the FLAG-002 silent-success risk.",
"The unique index uq_payment_requests_active_producer_ref at sql/payments.sql:126-128 is partial WHERE status NOT IN ('failed','cancelled'), so manual_hold IS covered. Collision handling must branch on whether any prior row is non-excluded before attempting a new insert \u2014 Branch A inserts (all prior rows failed/cancelled), Branch B returns None + DM without insertion. This is the core correctness fix for FLAG-003/correctness-2.",
"In upsert_wallet, the existing-wallet lookup at db_handler.py:1431 runs FIRST, then the new has_active_payment_or_intent guard uses that result. The sample code in Step 5 reflects this order \u2014 fixing correctness-1.",
"Both PaymentCog construction sites (main.py:233 and the setup() hook at payment_cog.py:503) work without modification because the success-DM threshold and provider set are read via os.getenv inside PaymentCog. with safe defaults ($100 and 'solana_payouts'). This avoids the all_locations-1 drift risk.",
"Inline fake-db glue lives in tests/test_admin_payments.py:497-729 and tests/test_social_publish_service.py:474-685 in addition to tests/conftest.py. The plan extends all three with has_active_payment_or_intent, get_rolling_24h_payout_usd, and WalletUpdateBlockedError stubs \u2014 addressing all_locations-2.",
"RLS is already enabled on payment_requests/wallet_registry/payment_channel_routes (sql/payments.sql:192-199). Step 12 is comment-only.",
"P0 prompt-injection hardening is verification + defensive pop-and-warn + regression test \u2014 the initiate_payment tool schema at tools.py:580-599 already omits wallet_address.",
"privileged_override=True remains usable; the current admin_chat test auto-confirm at admin_chat_cog.py:258-262 passes matching recipient_user_id so it does not need the override under the tightened confirm_payment rule. Same for grants auto-confirm at grants_cog.py:596-601.",
"execute_payment's stored-wallet semantics at payment_service.py:244 are code-unchanged \u2014 only a regression-pin test.",
"The git-history audit and log audit are memo tasks, not directly diff-verifiable in automated review. They are marked (not ), matching the criteria_quality flag's guidance."
],
"delta_from_previous_percent": 61.33,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "Solana payout caps: Step 8 still leaves admin-chat final payouts uncapped because it keys cap enforcement off normalized_amount_usd, while the live final-payout caller passes amount_token only.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Wallet registry updates: The proposed upsert_wallet blocked-path sentinel is only handled in admin chat, but grants_cog is another live caller and would treat a truthy sentinel dict as a successful wallet record.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-003",
"concern": "Payment idempotency: The collision path over-assumes it can insert a new manual_hold row for any prior-wallet mismatch, but the active unique index still blocks inserts when the prior row is not failed or cancelled.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the required payout-cap item against the real admin payout caller in src/features/admin_chat/admin_chat_cog.py:352-365; that path calls request_payment(... amount_token=float(intent['requested_amount_sol']), amount_usd=None ...), but Step 8 in the plan says cap logic runs only when normalized_amount_usd is not None, so the plan as written does not fully cover the main admin-triggered payout path called out in the brief.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: Step 5 says to add the active-payment guard in upsert_wallet before the existing-wallet lookup, but the sample code branches on existing before existing = self.get_wallet(...) has run. That control flow is not implementable as written and needs to be reordered or rewritten.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: The collision path in Step 6 assumes it can create a fresh manual_hold row whenever any prior (producer, producer_ref, is_test) row has a different wallet, but sql/payments.sql:126-128 still enforces uniqueness for every status except failed and cancelled. If the differing prior row is pending_confirmation, queued, processing, submitted, confirmed, or manual_hold, the insert cannot succeed, so the plan needs an explicit non-insert branch instead of assuming a new held row can always be created.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: is shared outside admin chat: also uses it during grant wallet verification. The plan only describes surfacing the blocked-update path in , so the broader caller surface is not fully accounted for.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-1",
"concern": "Does the change touch all locations AND supporting infrastructure?: The plan says to grep for and find a single construction site, but there are two repo instantiations today: and . If the constructor grows success-DM configuration, both locations need to stay in sync.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-2",
"concern": "Does the change touch all locations AND supporting infrastructure?: The supporting test glue is broader than the plan currently describes. The fake databases and bot doubles that would need to absorb helper or return-shape changes live inline in and , not only in .",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-1",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked the real admin payout caller at ; it passes and omits , so any cap logic written around the grants-style USD caller alone will miss the exact caller the brief cares about most.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-2",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked callers and found both and . A truthy sentinel such as would be caught in admin chat only if the new branch is added there, but grants would still treat that dict as a valid wallet record and continue.",
"status": "addressed",
"severity": "significant"
},
{
"id": "conventions",
"concern": "Does the approach match how the codebase solves similar problems?: The proposed return value does not match the surrounding convention, which is overwhelmingly or with / on failure across . That divergence is risky here because current callers already treat any dict as success.",
"status": "open",
"severity": "minor"
},
{
"id": "verification-1",
"concern": "Is there convincing verification for the change?: The planned test list does not include a cap test for the admin-chat final-payment path that passes without , even though that is the live caller in . Without that regression test, the cap feature could still ship green while leaving the primary admin payout path uncapped.",
"status": "open",
"severity": "minor"
},
{
"id": "verification-2",
"concern": "Is there convincing verification for the change?: The plan adds an admin-chat test for blocked wallet updates, but it does not add any regression coverage for the other live caller in . That leaves the proposed sentinel-versus-exception choice unverified on a real second caller.",
"status": "open",
"severity": "minor"
},
{
"id": "criteria_quality",
"concern": "Are the success criteria well-prioritized and verifiable?: Several criteria are not directly verifiable from code, tests, or diff inspection alone, especially the requirements that the git-history audit commands and log-audit grep be run and that their findings be recorded. Those are useful review tasks, but they are not strong gates for an automated review pipeline.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{
"admin-chat-classification": [
{
"id": "DEBT-006",
"concern": "anthropic client may not be initialized when interceptor fires before _ensure_agent.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
}
],
"admin-payments-intent-state": [
{
"id": "DEBT-004",
"concern": "button confirmation path does not directly update admin_payment_intents \u2014 intent sync happens indirectly via handle_payment_result on terminal state.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
},
{
"id": "DEBT-005",
"concern": "no direct bridge from paymentconfirmview to admin_payment_intents.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
}
],
"db-handler-social-publications": [
{
"id": "DEBT-001",
"concern": "mixing fluent client, raw sql, and rpc access patterns in one subsystem increases maintenance surface.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
],
"db-handler-supabase-infrastructure": [
{
"id": "DEBT-002",
"concern": "supabase rpc is untested in this codebase and may require dashboard configuration.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
],
"social-channel-routes": [
{
"id": "DEBT-003",
"concern": "route management tooling is absent, leaving the routing system inert until manual db inserts.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
]
}
code
Escalated debt subsystems:
[]
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Your output template is at: /Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc/.megaplan/plans/harden-the-solana-payment-20260410-2147/critique_output.json
Read this file first — it contains 8 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 2. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: heavy. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
code
Project directory:
/Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc
Engineering brief produced from the codebase and task details:
### Task Summary
Harden the Solana payment subsystem against the adversarial review: P0 (secret audit of git history, prompt-injection hardening in admin_chat initiate_payment, null recipient_discord_id confirmation bypass), P1 (wallet swap window between test and final, idempotency slot reuse after forced failure, per-payment + rolling daily USD caps on admin-triggered payouts, admin success-DM over threshold), P2 (log audit, RLS posture doc). End-to-end hardening with no half-fixes on the subtle wallet-swap and idempotency paths.
### Key Evidence
- The `initiate_payment` LLM tool schema in admin_chat already does NOT accept a wallet_address parameter — it takes only recipient_user_id, amount_sol, reason. The wallet is looked up via db_handler.get_wallet(guild_id, recipient_user_id, 'solana') at tools.py:2474. The task's P0 premise ('remove LLM-sourced wallet addresses') is largely already satisfied — the plan should (a) grep siblings for any other tool that accepts a wallet_address, (b) add an assertion/docstring in execute_initiate_payment that wallets MUST come from wallet_registry, (c) add a regression test that a wallet_address key in params is ignored. This is verification + defensive assertion, NOT a rewrite. (source: src/features/admin_chat/tools.py:580-599, 2438-2505; relevance: high)
execute_payment ALREADY uses the stored recipient_wallet string from the payment row (payment_service.py:244), not a re-read from wallet_registry. The final payment in admin_chat is created with recipient_wallet=payment['recipient_wallet'] copied from the test payment row (admin_chat_cog.py:356). So execute_payment is safe. The actual wallet-swap risk lives in request_payment's pre-insert check at payment_service.py:84-90, which rejects a new intent whose wallet_id→wallet_registry.wallet_address mismatches the string — causing the entire final-payout to silently drop if the user upserts a new wallet. Fix: block upsert_wallet while an active intent exists (in db_handler.upsert_wallet), don't rely on post-hoc rejection. (source: src/features/payments/payment_service.py:68-90, 244; src/features/admin_chat/admin_chat_cog.py:236, 356; relevance: high)
Null recipient_discord_id confirmation bypass is real: payment_service.confirm_payment at lines 193-202 only checks recipient match if not privileged_override and expected_user_id is not None. A payment with recipient_discord_id=NULL can be confirmed by any user. Fail-closed fix: require expected_user_id AND confirmed_by_user_id to be non-null and match, unless privileged_override=True. sql/payments.sql:77 allows NULL — consider adding a partial CHECK for provider='solana_payouts'. (source: src/features/payments/payment_service.py:193-202; sql/payments.sql:77; relevance: high)
Idempotency slot reuse after forced failure: the unique index uq_payment_requests_active_producer_ref at payments.sql:126-128 is partial WHERE status NOT IN ('failed','cancelled'). Once a row is marked failed, a new row with the same (producer, producer_ref, is_test) can be freely inserted. request_payment (payment_service.py:54-61) early-returns on existing rows but likely only sees non-terminal ones. Since admin_chat uses ONE producer_ref across test AND final payments (admin_chat_cog.py:234, 354), and test failures free the slot, an attacker who forces a test failure can retrigger with a different wallet. Fix: query ALL prior rows for (producer, producer_ref, is_test) including terminal; if any prior row has a different recipient_wallet, log WARN, DM admin, and create the new row as manual_hold. (source: sql/payments.sql:126-128; src/features/payments/payment_service.py:54-61,167-174; src/features/admin_chat/tools.py:2473; src/features/admin_chat/admin_chat_cog.py:234,354; relevance: high)
No USD cap enforcement exists. request_payment accepts arbitrary amount_usd/amount_token with only a > 0 check (payment_service.py:102, 112). manual_hold is already a terminal status in the enum (payments.sql:100) and db_handler.mark_payment_manual_hold is wired. Caps should go in PaymentService.request_payment, provider-scoped to {'solana_payouts'}. Over-cap should create a manual_hold row + admin DM (NOT silent reject), preserving the audit trail. (source: src/features/payments/payment_service.py:32-174; sql/payments.sql:92-102; relevance: high)
| --- | --- | --- |
| src/features/payments/payment_service.py | PaymentService.request_payment, PaymentService.confirm_payment, PaymentService.execute_payment | Core target. Confirm-payment fail-closed fix (lines 193-202). Cap enforcement injection point (after amount_token derivation at lines 90-119, before create_payment_request at 163). Idempotency collision detection before early return at lines 54-61 and in fallback at 167-174. execute_payment at 244 already uses stored wallet — add regression test, no code change. |
| src/features/payments/payment_cog.py | PaymentCog._handle_terminal_payment, PaymentCog._dm_admin_payment_failure | Add sibling _dm_admin_payment_success called from _handle_terminal_payment (lines 267-272) when status=='confirmed', not is_test, provider in admin-payout set, amount_usd>=threshold. Reuse ADMIN_USER_ID env plumbing. Differentiated prefix/emoji from failure DM. |
| src/features/admin_chat/admin_chat_cog.py | AdminChatCog._handle_wallet_received, AdminChatCog._start_admin_payment_flow, AdminChatCog.handle_payment_result | handle_wallet_received (193-218) calls upsert_wallet with no inflight guard — surface new structured error to admin review channel. start_admin_payment_flow (220-271) and handle_payment_result (299-402) handoff reads recipient_wallet from test row (already safe, pin with test). Ensure recipient_discord_id always passed non-null. |
| src/features/admin_chat/tools.py | execute_initiate_payment, initiate_payment tool schema | Tool schema at 580-599 already excludes wallet_address. Grep ALL admin_chat tools for any wallet_address-accepting sibling. Add docstring + defensive pop-and-warn in execute_initiate_payment (2438-2526) asserting wallets must come from wallet_registry. Add test that wallet_address in params is ignored. |
| src/common/db_handler.py | upsert_wallet, get_wallet, get_wallet_by_id, get_payment_requests_by_producer, create_payment_request, mark_payment_manual_hold | upsert_wallet (1417-1465) needs inflight guard via new helper has_active_payment_or_intent(guild_id, discord_user_id). Add new helper get_payment_requests_for_ref_all (no terminal-status filter) for slot-reuse detection. Add new helper get_rolling_24h_payout_usd(guild_id, provider) for daily cap aggregation. |
| sql/payments.sql | wallet_registry schema, payment_requests schema, uq_payment_requests_active_producer_ref | Add top-of-file comment block documenting RLS posture. Do NOT change the partial-index predicate (legitimate retries need it). Collision detection stays in app code. Consider adding a CHECK that recipient_discord_id is non-null when provider='solana_payouts' (defense-in-depth). |
| src/common/log_handler.py | - | Log audit target. Grep for env-var logging, unsanitized tracebacks, os.environ dumps. Add scrubbing filter for SOLANA_PRIVATE_KEY/HELIUS*/ANTHROPIC* only if a real leak path exists. Document findings either way. |
| main.py | PaymentService construction | Lines 157-161 construct PaymentService with providers and test_payment_amount. Pass new kwargs (per_payment_usd_cap, daily_usd_cap, capped_providers, admin_success_dm_threshold_usd) sourced from env with safe defaults (2000/{'solana_payouts'}/$100). |
| tests/test_admin_payments.py | PaymentService integration tests | Extend PaymentService tests at 687+ with adversarial cases: null-recipient reject, cap manual_hold, rolling daily cap, slot-reuse collision, upsert_wallet block, admin success DM, wallet_address tool arg ignored, execute_payment stored-wallet regression pin. Preserve FakeAdminPaymentService happy-path tests. |
| tests/test_scheduler.py | - | Scheduler wrappers (lines 390-584) must still work — caps run only in request_payment, NOT execute_payment, so scheduled queue path is unaffected. Verify. |
| tests/test_social_publish_service.py | - | Existing PaymentService construction (474-685) uses provider dict {'solana': provider}. New caps must be provider-scoped to 'solana_payouts' so these tests remain green with defaults. |
code
### Test Expectations
- [fail_to_pass] tests/test_admin_payments.py::test_confirm_rejects_null_recipient_discord_id: NEW: confirm_payment returns None and logs WARN when recipient_discord_id is NULL and privileged_override is False, regardless of confirmed_by_user_id. privileged_override=True still works for test-payment auto-advance.
[fail_to_pass] tests/test_admin_payments.py::test_request_payment_per_payment_cap_manual_holds: NEW: request_payment with provider='solana_payouts' and amount_usd > per-payment cap creates the row with status='manual_hold', logs WARN, and triggers admin DM. grants provider is unaffected.
[fail_to_pass] tests/test_admin_payments.py::test_request_payment_rolling_daily_cap_manual_holds: NEW: once rolling 24h sum of solana_payouts amount_usd crosses daily cap, next new intent is manual_hold'd even if per-payment amount is under per-payment cap. Grants are unaffected.
[fail_to_pass] tests/test_admin_payments.py::test_slot_reuse_collision_detected: NEW: prior failed row with same (producer, producer_ref, is_test) and DIFFERENT recipient_wallet causes request_payment to log WARN, DM admin, and create the new row as manual_hold (NOT silent replacement).
[fail_to_pass] tests/test_admin_payments.py::test_upsert_wallet_blocked_during_active_intent: NEW: db_handler.upsert_wallet refuses to update wallet_address while a non-terminal payment_requests row OR awaiting_* admin_payment_intents row exists for (guild_id, discord_user_id), and _handle_wallet_received surfaces the error to the admin review channel.
[fail_to_pass] tests/test_admin_payments.py::test_admin_success_dm_over_threshold: NEW: on confirmed non-test solana_payouts payment with amount_usd >= $100, admin is DM'd with success-differentiated message. Under-threshold does NOT DM. Failure DM path is unchanged.
[fail_to_pass] tests/test_admin_payments.py::test_execute_payment_uses_stored_wallet: NEW regression pin: execute_payment passes payment['recipient_wallet'] (frozen stored string) to provider.send, NOT a re-read from wallet_registry. Prevents future regression.
[fail_to_pass] tests/test_admin_payments.py::test_initiate_payment_tool_rejects_wallet_address_arg: NEW: passing a wallet_address key through execute_initiate_payment params is ignored (not persisted, not used for lookup); wallet is exclusively resolved via db_handler.get_wallet(guild_id, recipient_user_id, 'solana').
[pass_to_pass] tests/test_admin_payments.py (existing happy-path): Existing happy path (wallet capture → test → confirm → final → notify) still passes with new caps/collision logic (test uses high cap).
[pass_to_pass] tests/test_scheduler.py (existing): Scheduler queue path still advances queued payments; caps run only in request_payment, not execute_payment.
[pass_to_pass] tests/test_social_publish_service.py (existing PaymentService tests): Social publish service's PaymentService usage keeps working — new caps are scoped to 'solana_payouts', these tests use different provider names.
code
Groundwork (P2, low-risk): add RLS-posture comment block at the top of sql/payments.sql. Extend tests/conftest.py with an in-memory wallet_registry + payment_requests store if one doesn't already exist, so adversarial tests can operate against real PaymentService logic.
P0: Null recipient_discord_id fail-closed (payment_service.py:193-202). Change to if not privileged_override: if expected_user_id is None or confirmed_by_user_id is None or int(expected_user_id) != int(confirmed_by_user_id): log WARN; return None. Ship with the new test. Audit every confirm_payment call site (payment_cog.py + admin_chat_cog.py:258-262) to ensure no flow relies on NULL recipient.
P0: admin_chat prompt-injection verification. Grep ALL admin_chat tools for 'wallet_address' / 'address' fields in input_schema. If any sibling tool accepts a raw wallet, remove or harden. Add a docstring + defensive params.pop('wallet_address', None) with WARN log at the top of execute_initiate_payment. Add the tool-arg-ignored test. Explicitly record in the plan that the task's P0 premise was already substantially implemented.
P1: upsert_wallet inflight block (db_handler.py:1417-1465). Add helper has_active_payment_or_intent(guild_id, discord_user_id) querying non-terminal payment_requests + awaiting_* admin_payment_intents. Verify exact admin_payment_intents status enum values before coding the 'active' predicate. Return structured error from upsert_wallet on conflict. Update _handle_wallet_received (admin_chat_cog.py:193-218) to surface to admin review channel.
P1: Idempotency slot-reuse collision detection (payment_service.py:54-61, 167-174). Add db_handler helper get_payment_requests_for_ref_all(producer, producer_ref, is_test) that does NOT filter terminal. Before the idempotent early-return, query this helper: if any prior row has a different recipient_wallet than the incoming request, log WARN, DM admin, create the new row as manual_hold (do NOT return the old non-terminal row as if nothing happened). Be careful the early-return at lines 54-61 does not short-circuit BEFORE collision detection.
P1: Per-payment + rolling daily USD caps in PaymentService. Add constructor kwargs per_payment_usd_cap, daily_usd_cap, capped_providers=frozenset({'solana_payouts'}), default to None (disabled) for backward-compat with existing tests. In request_payment, after amount_token derivation, if provider in capped_providers and not is_test: if amount_usd > per_payment_cap OR get_rolling_24h_payout_usd(guild_id, provider) + amount_usd > daily_cap → create the row with status='manual_hold' + last_error='cap exceeded' + admin DM. Add db_handler helper get_rolling_24h_payout_usd that sums amount_usd across pending_confirmation/queued/processing/submitted/confirmed within 24h. If serializable transaction is impractical, document residual burst window.
Subtle pitfalls:
In step 5, the idempotent early return at payment_service.py:54-61 must be reordered to run AFTER collision detection, OR collision detection must happen inside that branch too.
In step 6, rolling window MUST include in-flight statuses, not just confirmed, to prevent concurrent burst slip-through.
In step 4, read admin_payment_intents table schema + db_handler.create_admin_payment_intent to enumerate exact status values before hardcoding the 'active' set.
The initial P0 premise about LLM-sourced wallet addresses appears already fixed by a prior change — state this explicitly in the plan so review doesn't reject prep as incomplete; the work is verification + defensive assertion + test.
Do NOT double-check caps in execute_payment. Caps run only in request_payment. Scheduler path (claim_due_payment_requests → execute_payment) must not hit cap logic.
privileged_override=True must remain usable for test-payment auto-advance (admin_chat_cog.py:258-262). Verify the test payment row carries recipient_discord_id (it does via line 244) so it doesn't hit the new null-reject branch anyway.
code
The engineering brief above was produced by analyzing the codebase. Use it as a strong starting point, but the suggested approach is a hypothesis — verify it's the best fix, not just a valid one.
Idea:
Harden the Solana payment subsystem against the attack vectors found by the adversarial security review. Fix P0: git history secret audit, prompt-injection hardening in admin_chat (remove LLM-sourced wallet addresses from initiate_payment tool; wallets must come from wallet_registry keyed by mentioned Discord user), null recipient_discord_id confirmation bypass (fail-closed). Fix P1: wallet swap window between test and final payment (verify execute_payment uses stored recipient_wallet string; reject or warn on upsert_wallet during active intents), idempotency slot reuse after forced failure (warn/DM on producer_ref collision with prior failed row having different wallet), per-payment and rolling daily USD cap on admin-triggered payouts enforced in PaymentService (default 500/payment,2000/day/guild, exceeding goes to manual_hold), admin DM on successful admin_chat payouts over threshold (default $100, differentiated from failure DMs). Fix P2: log audit for secret leakage, document RLS posture at top of sql/payments.sql. Already using Helius so RPC attacks out of scope. Two wallets already split into solana_grants and solana_payouts providers. Think carefully about wallet-swap and idempotency — they are subtle and easy to half-fix. Goal is end-to-end hardening.
Implement the P0/P1/P2 hardening from the adversarial review against src/features/payments/ and src/features/admin_chat/. Layered fail-closed: (1) correctness first (null recipient, prompt-injection defense, inflight wallet lock via exception), (2) monetary safety (idempotency collision with index-aware branching, per-payment + rolling daily USD caps that derive USD from amount_token when needed and persist it onto the stored payment row), (3) observability (admin success DM, log audit memo, RLS posture comment, git history audit memo).
Corrections confirmed against the repo
RLS is already enabled on wallet_registry, payment_channel_routes, payment_requests (sql/payments.sql:192-199). Step 12 is comment-only.
P0 prompt-injection is already substantially satisfied: the initiate_payment tool schema at src/features/admin_chat/tools.py:580-599 omits wallet_address, and execute_initiate_payment resolves wallets via db_handler.get_wallet(...) at tools.py:2474. Verification + defensive pop-and-warn + regression test, not a rewrite.
get_payment_requests_by_producer at db_handler.py:1853 already returns rows across all statuses; collision detection re-uses it directly.
execute_payment already uses the stored recipient_wallet (payment_service.py:244). Regression-pin test only.
Admin-chat final payout passes amount_token only (admin_chat_cog.py:352-365). For capped providers, the derived USD MUST be persisted into record['amount_usd'] (and record['token_price_usd']) so that (a) the rolling-24h aggregation in Step 7 sees it, (b) the success-DM gate in Step 9 sees it, (c) the last_error / manual_hold fields are consistent. If the price lookup fails, fail closed to manual_hold with last_error='cap check unavailable: token price missing'.
upsert_wallet has two live callers: admin_chat_cog.py:193-201 and grants_cog.py:557-565. Blocked-path signalling is a WalletUpdateBlockedError exception so neither caller can mistake it for a success.
Partial unique indexuq_payment_requests_active_producer_ref at sql/payments.sql:126-128 is WHERE status NOT IN ('failed','cancelled'). Collision handling must branch on whether any prior row is non-excluded before attempting a new insert.
PaymentCog is constructed at two sites: main.py:233 and the setup(bot) hook at src/features/payments/payment_cog.py:503. Success-DM config is read insidePaymentCog.__init__ from env; neither construction site needs to change.
Inline fake-db test glue lives in tests/test_admin_payments.py (classes around lines 497-729) and (lines 474-685) in addition to . New helpers must be stubbed in all three.
Key invariants (non-negotiable)
Fail-closed. Null recipient → reject. Cap breach → manual_hold + admin DM. Wallet-swap collision → branch per unique-index rule with admin DM. Inflight wallet change → raise WalletUpdateBlockedError.
Provider-scoped caps. Caps and admin success DM apply only to providers in capped_providers (default frozenset({'solana_payouts'})).
Derived USD is persisted end-to-end (capped-provider amount_token path only). Not a transient local; record['amount_usd'] and record['token_price_usd'] are stamped before insert so the rolling helper and success-DM gate see the real value.
Do NOT change the partial-index predicate. Collision handling stays in app code.
Do NOT re-read recipient_wallet in execute_payment. Frozen-string semantics.
Do NOT add cap logic in execute_payment.
Do NOT widen upsert_wallet's block window. Block only when the incoming address differs AND a non-terminal payment/intent exists.
Do NOT stamp amount_usd for uncapped providers or is_test paths. That would break existing happy-path tests that assert amount_usd is None for token-denominated requests on non-capped providers.
Preserve privileged_override=True for any future auto-advance path.
No secret logging. New logs redact wallets via _redact_wallet.
Cap config is injectable via constructor kwargs with None defaults.
Modifyconfirm_payment at payment_service.py:193-202:
python
if not privileged_override:
if (
expected_user_id is None
or confirmed_by_user_id is None
or int(expected_user_id) != int(confirmed_by_user_id)
):
self.logger.warning(
"[PaymentService] rejected confirmation for %s: expected_user=%s confirmed_by=%s",
payment_id, expected_user_id, confirmed_by_user_id,
)
return None
Audit every confirm_payment( call site. Verify admin-chat test auto-confirm at admin_chat_cog.py:258-262 and grants auto-confirm at grants_cog.py:596-601 both pass matching confirmed_by_user_id so the tightened rule is satisfied without needing privileged_override. Add a one-line comment at each call site.
GrepADMIN_CHAT_TOOLS schemas for any field named wallet_address, address, solana_address, recipient_wallet, wallet. Strip + harden if any are found.
Modifyexecute_initiate_payment at tools.py:2438. Add docstring + defensive pop at the top:
python
if 'wallet_address' in params or 'recipient_wallet' in params:
logger.warning(
"[AdminChat] execute_initiate_payment ignoring LLM-sourced wallet fields"
)
params.pop('wallet_address', None)
params.pop('recipient_wallet', None)
Record in the plan output that P0 prompt-injection was already substantially satisfied by prior work.
Step 3: Git history secret audit memo (no code change)
Addclass WalletUpdateBlockedError(Exception): pass to db_handler.py (or src/common/exceptions.py if one exists — grep first).
Modifyupsert_wallet at db_handler.py:1417-1465. The existing-wallet lookup at line 1431 runs FIRST, then the block check:
python
existing = self.get_wallet(guild_id, discord_user_id, chain)
if existing and existing.get('wallet_address') != address:
if self.has_active_payment_or_intent(guild_id, discord_user_id):
logger.warning(
"[DB] upsert_wallet blocked: active payment/intent for guild %s user %s",
guild_id, discord_user_id,
)
raise WalletUpdateBlockedError(
"wallet update blocked while an active payment or intent exists"
)
Modify_handle_wallet_received at admin_chat_cog.py:193-218:
python
try:
wallet_record = self.db_handler.upsert_wallet(...)
except WalletUpdateBlockedError:
await self._notify_admin_review(
message.channel, intent,
"I cannot update this wallet address: an active payment is in flight. "
"Please wait for it to resolve or cancel the current intent.",
resolved_by_message_id=message.id,
)
return
Modify_start_payment_flow at grants_cog.py:550-565:
python
try:
wallet_record = self.db.upsert_wallet(...)
except WalletUpdateBlockedError:
await thread.send(
"I cannot register this wallet right now: there is an active payment "
"in progress for your account. Please wait for it to finalize and try again."
)
return
Step 6: Idempotency collision detection with index-aware branching (src/features/payments/payment_service.py)
Scope: Medium
Readdb_handler.py:1853-1883 to confirm get_payment_requests_by_producer returns all statuses. Add an inline comment documenting the invariant.
Reworkrequest_payment at payment_service.py:54-61:
python
all_prior_rows = self.db_handler.get_payment_requests_by_producer(
guild_id=guild_id, producer=producer,
producer_ref=producer_ref, is_test=is_test,
)
normalized_wallet = str(recipient_wallet or '').strip()
INDEX_EXCLUDED = {'failed', 'cancelled'}
TERMINAL_FOR_RETURN = {'confirmed', 'failed', 'manual_hold', 'cancelled'}
collision_row = None
blocking_prior_row = None
for row in all_prior_rows:
prior_wallet = str(row.get('recipient_wallet') or '').strip()
prior_status = str(row.get('status') or '').lower()
if prior_status not in INDEX_EXCLUDED:
blocking_prior_row = row
if prior_wallet and normalized_wallet and prior_wallet != normalized_wallet:
collision_row = row
break
# Idempotent early-return only for a live, same-wallet prior row. Terminal
# rows must NOT short-circuit here — otherwise a `failed` prior row is
# handed back to the caller as if it were fresh `pending_confirmation`.
if not collision_row:
active_same_wallet = [
r for r in all_prior_rows
if str(r.get('status') or '').lower() not in TERMINAL_FOR_RETURN
and str(r.get('recipient_wallet') or '').strip() == normalized_wallet
]
if active_same_wallet:
return active_same_wallet[0]
Collision handling — two explicit branches (immediately after the loop):
Branch A — slot reuse after terminal failure (): every prior row is /, so the partial unique index permits a new insert. Fall through to build as normal but then set and . Insert via ; after insert, fire the callback (Step 8).
status IN ('pending_confirmation','queued','processing','submitted','confirmed')
created_at >= now() - interval '24 hours'
Sumamount_usd across results; nulls → 0.0; return float.
Comment: "Supabase REST has no serializable transaction — residual burst window is ~RPC latency (~100-500ms). Manual_hold + admin DM is the fail-closed backstop. Relies on upstream request_payment persisting derived USD for amount_token-only capped callers."
Stub in the inline fakes (Step 13). Default return 0.0.
Step 8: PaymentService cap enforcement with persisted derived USD (src/features/payments/payment_service.py)
Normalize; defaults disable cap logic entirely so existing tests stay green.
Inject cap logic in request_paymentafter amount_token derivation (lines 90-119) and beforecreate_payment_request (line 163). This block covers both the amount_usd and amount_token callers. Critically, when USD is derived from amount_token * token_price_usd for a capped provider, the derived values are persisted into record['amount_usd'] and record['token_price_usd'] so downstream observability (rolling cap helper, success-DM gate) sees the real value.
python
provider_key = str(provider).strip().lower()
cap_usd: Optional[float] = None
derived_usd_for_record: Optional[float] = None
derived_price_for_record: Optional[float] = None
if not is_test and provider_key in self.capped_providers:
if normalized_amount_usd is not None:
cap_usd = normalized_amount_usd
else:
# amount_token-only caller (e.g. admin_chat final payout at
# admin_chat_cog.py:352-365). Derive USD from the provider token
# price so the cap check, rolling-24h helper, and success-DM
# gate all see the same value. Fail-closed to manual_hold if
# the price lookup fails.
price = token_price_usd
if price is None:
try:
price = await payment_provider.get_token_price_usd()
except Exception as exc:
self.logger.warning(
"[PaymentService] token price lookup failed for cap check: %s", exc,
)
price = None
if price and price > 0:
cap_usd = float(amount_token) * float(price)
derived_usd_for_record = cap_usd
derived_price_for_record = float(price)
# else: cap_usd stays None → fail-closed below
Step 9: Admin success DM over threshold (src/features/payments/payment_cog.py)
Scope: Small
ExtendPaymentCog.__init__ to read env inside the constructor:
python
import os
self._admin_success_dm_threshold_usd = float(
os.getenv('ADMIN_PAYMENT_SUCCESS_DM_THRESHOLD_USD', '100')
)
self._admin_success_dm_providers = frozenset(
p.strip().lower()
for p in (os.getenv('ADMIN_PAYMENT_SUCCESS_DM_PROVIDERS', 'solana_payouts').split(','))
if p.strip()
)
Add sibling _dm_admin_payment_success(self, payment) modeled on _dm_admin_payment_failure at payment_cog.py:273-333 but with:
Distinct prefix ✅ **Payment Completed**.
No "requires manual review" line.
Include amount_usd (now populated end-to-end for capped amount_token callers, per Step 8) alongside amount_token.
Wallet redacted via _redact_wallet.
Invoke from _handle_terminal_payment at 267-271, alongside (not replacing) the failure path:
python
if payment.get('status') == 'confirmed' and not payment.get('is_test'):
provider = str(payment.get('provider') or '').lower()
amount_usd = float(payment.get('amount_usd') or 0)
if (
provider in self._admin_success_dm_providers
and amount_usd >= self._admin_success_dm_threshold_usd
):
await self._dm_admin_payment_success(payment)
Do NOT modify _dm_admin_payment_failure.
Step 10: Wire caps + cap-breach DM into main (main.py)
where _bind_cap_breach_dm(bot) returns a small async def closure that looks up bot.get_cog('PaymentCog') and calls _dm_admin_payment_failure(payment) — the failure DM wording already fits ("requires manual review") since cap-breach and collision-blocked rows both land in the admin manual-review queue.
Add a comment block at the very top of sql/payments.sql:
sql
-- RLS posture:
-- * Row-level security is ENABLED on wallet_registry, payment_channel_routes,
-- and payment_requests (see `alter table ... enable row level security` below).
-- * All access is mediated by DatabaseHandler using the Supabase service role,
-- which bypasses RLS. No anon/authenticated clients access these tables.
-- * anon and authenticated roles have ALL privileges revoked; no policies are
-- defined because no non-service-role access path exists.
-- * Writes are parameterized via supabase-py; no raw SQL string interpolation.
-- * Changing this posture (e.g. exposing tables to a browser client) requires
-- writing explicit row-level policies first — do NOT simply grant.
Do NOTALTER TABLE. Comment-only.
Phase 5: Tests
Step 13: Extend PaymentService test suite (tests/test_admin_payments.py, tests/conftest.py, tests/test_social_publish_service.py)
Scope: Medium
Inspecttests/conftest.py and the inline fake-db classes in tests/test_admin_payments.py:497-729 and tests/test_social_publish_service.py:474-685. Extend all three additively with:
upsert_wallet raising WalletUpdateBlockedError when configured.
Import WalletUpdateBlockedError from wherever Step 5 lands it.
Preserve existing assertions that key off amount_usd is None for uncapped providers. Before writing any new test, re-grep amount_usd in both test files and confirm every current assertion uses a non-capped provider name ("solana", "solana_native").
test_request_payment_amount_token_path_stamps_amount_usd — : capped provider, , provider price 1000 → row is created (NOT manual_hold) AND AND . Pins that derived USD is persisted so the rolling helper and success-DM gate see it.
Step 14: Verify scheduler + social publish tests untouched
Scope: Small
Runpytest tests/test_scheduler.py tests/test_social_publish_service.py. These should pass unchanged because:
Scheduler path (claim_due_payment_requests → execute_payment) is untouched.
test_social_publish_service.py constructs PaymentService without the new kwargs → caps default to None → no enforcement → no amount_usd stamping for its uncapped "solana_native" provider, preserving its amount_usd is None assertion.
If either fails, fix the code (not the test) unless the test violates a new invariant.
Phase 3 (rolling 24h helper → cap enforcement with persisted derived USD → success DM sibling → main.py wiring).
Phase 4 (log audit memo + RLS comment).
Phase 5 (targeted tests after each phase, full suite at the end).
Trip-wire subsets between phases:
After Phase 1: pytest tests/test_admin_payments.py -k "confirm or initiate_payment".
After Phase 2: pytest tests/test_admin_payments.py -k "wallet or slot or collision or idempotent".
After Phase 3: pytest tests/test_admin_payments.py -k "cap or success_dm or token_path or stamps or derived" + pytest tests/test_scheduler.py tests/test_social_publish_service.py.
After Phase 5: full pytest tests/.
Validation Order
Unit tests (new + existing) — pytest tests/test_admin_payments.py.
Adjacent suites — pytest tests/test_scheduler.py tests/test_social_publish_service.py (regression pins that caps don't leak into scheduler or social flows, and that uncapped providers still see amount_usd is None).
Full suite — pytest tests/.
Manual read-through — re-audit payment_service.request_payment and both upsert_wallet callers against the invariants list. Specifically: (a) does any path silently drop a final payout, (b) does an amount_token-only capped caller flow its derived USD all the way into the stored row AND the rolling helper AND the success-DM gate, (c) does any wallet swap mid-flow sneak through, (d) does any code attempt a new manual_hold insert while a non-terminal prior row still holds the unique-index slot.
Git-history + log audit memos recorded in the review output.
code
Plan metadata:
{
"version": 3,
"timestamp": "2026-04-10T20:50:46Z",
"hash": "sha256:8ee4a98663a904bc12bc8e7bda5dc12b8200ed7a7554c7902b4367a807f30d79",
"changes_summary": "Fixed the single root cause behind all 8 open flags: derived USD was being kept local to the cap check instead of persisted into the stored payment row. Step 8 now explicitly stamps record['amount_usd'] and record['token_price_usd'] (and the mirrored request_payload fields) when USD is derived from amount_token * token_price_usd for a capped provider \u2014 and only in that branch, so uncapped providers and is_test paths keep their existing amount_usd=None behavior. This makes the rolling-24h helper (Step 7, which sums stored amount_usd) and the success-DM gate (Step 9, which reads payment.get('amount_usd')) both see the real value for admin-chat amount_token-only payouts end-to-end. Verified safety of existing tests: test_request_payment_amount_token at tests/test_admin_payments.py:684-709 uses uncapped provider "solana" and asserts provider.price_calls == 0, so our derivation branch (gated on capped_providers) never fires and the test stays green. Same for test_social_publish_service.py:496, which uses uncapped "solana_native". Added three new tests: test_request_payment_amount_token_path_stamps_amount_usd (pins the persisted derivation), test_request_payment_amount_token_uncapped_provider_preserves_none (regression pin for the existing behavior on uncapped providers), test_request_payment_rolling_daily_cap_sees_derived_usd (end-to-end wiring through the rolling helper), and test_admin_success_dm_sees_derived_usd (end-to-end wiring through the success-DM gate). Updated assumptions to state that derived USD is persisted when the provider is capped. Updated the end-to-end cap-enforcement success criterion to explicitly require persistence so the must matches what the plan actually proves. Added a new invariant forbidding amount_usd stamping for uncapped/is_test paths. No other structural changes; prior fixes to exception-based upsert_wallet blocking, index-aware collision branching, control-flow ordering, and PaymentCog construction-site handling remain unchanged.",
"flags_addressed": [
"FLAG-001",
"issue_hints",
"scope",
"criteria_quality",
"correctness",
"all_locations",
"callers",
"callers-1"
],
"questions": [
"Reporting downstream: does anything beyond PaymentCog and the rolling helper currently key off amount_usd for solana_payouts rows (e.g. Discord notify embeds in the admin channel, analytics dashboards, Supabase views)? If so, those sites will now start seeing populated USD for admin-chat final payouts where they used to see null. Default: treat as a welcome accuracy improvement, not a regression \u2014 but will grep amount_usd across the repo during implementation and flag any site that explicitly depends on the null-for-token-denominated contract.",
"For the amount_token derivation path, if the provider returns a stale cached price, the persisted will be slightly stale too. Is that acceptable, or should we call with a freshness guarantee? Default: accept cached price since the cap check and the success-DM threshold are coarse and the cache is already what grants uses.",
"The Branch-B collision DM includes the blocking prior row's payment_id for operator context; the payload passed to in that branch is the PRIOR row, not a new row (since no insert happens). Is that acceptable, or should we synthesize a lightweight dict with a distinct so the DM template distinguishes it from a real manual_hold? Default: pass the prior row \u2014 the DM is for operator triage and the prior row is what operators need to inspect.",
"Env var names as , , , acceptable? If a different prefix is preferred for consistency with existing env plumbing, flag before landing."
],
"success_criteria": [
{
"criterion": "All existing tests in tests/test_admin_payments.py, tests/test_scheduler.py, and tests/test_social_publish_service.py pass unchanged (default None caps preserve existing PaymentService construction; amount_usd stays None for uncapped providers).",
"priority": "must"
},
{
"criterion": "New test test_confirm_rejects_null_recipient_discord_id passes: confirm_payment with recipient_discord_id=None returns None and logs WARN.",
"priority": "must"
},
{
"criterion": "New test verifying privileged_override=True still bypasses the null-recipient check passes.",
"priority": "must"
},
{
"criterion": "New test test_confirm_rejects_mismatched_user passes: confirm_payment with a non-matching confirmed_by_user_id returns None.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_per_payment_cap_manual_holds passes: amount_usd over per-payment cap lands the row as manual_hold with cap-breach last_error; grants provider unaffected; on_cap_breach invoked.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_amount_token_path_cap_breach passes: capped provider, amount_token with no amount_usd, derived USD (amount_token * token_price_usd) exceeds cap \u2192 manual_hold.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_amount_token_path_stamps_amount_usd passes: capped provider, amount_token within cap, provider returns a valid price \u2192 the created row has and (NOT None). Pins that derived USD is persisted end-to-end.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_amount_token_path_missing_price_holds passes: capped provider, amount_token path, provider returns None/0 for price \u2192 manual_hold with last_error='cap check unavailable'.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_amount_token_uncapped_provider_preserves_none passes: uncapped provider ('solana'), amount_token path \u2192 result['amount_usd'] is None AND provider price lookup is NOT called. Regression pin against existing amount_token test behavior.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_rolling_daily_cap_manual_holds passes: rolling 24h aggregation across non-test solana_payouts rows in (pending_confirmation, queued, processing, submitted, confirmed) drives the cap; grants unaffected.",
"priority": "must"
},
{
"criterion": "New test test_request_payment_rolling_daily_cap_sees_derived_usd passes: prior confirmed capped-provider row whose amount_usd was stamped via the derivation path is correctly summed by get_rolling_24h_payout_usd and a follow-up amount_token request counts against the daily cap accordingly. Pins end-to-end rolling-cap flow for admin-chat payouts.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_collision_detected_after_failure passes: only prior rows are failed/cancelled with a different wallet \u2192 fresh manual_hold row is inserted (Branch A) and on_cap_breach fires.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_collision_blocked_when_prior_active passes: prior row is pending_confirmation/queued/etc with a different wallet \u2192 request_payment returns None without attempting an insert (Branch B), the prior row is NOT replaced, and on_cap_breach fires.",
"priority": "must"
},
{
"criterion": "New test test_slot_reuse_same_wallet_creates_fresh_row_after_failure passes: only terminal prior rows with matching wallet \u2192 new pending_confirmation row is created.",
"priority": "must"
},
{
"criterion": "New test test_idempotent_return_for_nonterminal passes: non-terminal prior row with matching wallet is returned unchanged.",
"priority": "must"
},
{
"criterion": "New test test_upsert_wallet_raises_during_active_intent passes: upsert_wallet raises WalletUpdateBlockedError while a non-terminal payment_requests OR admin_payment_intents row exists; both admin_chat._handle_wallet_received AND grants_cog._start_payment_flow catch it and surface user-facing messages.",
"priority": "must"
},
{
"criterion": "New test test_upsert_wallet_unblocked_after_terminal passes: upsert proceeds when only terminal rows exist AND when the incoming address matches the stored address even while an active intent exists.",
"priority": "must"
},
{
"criterion": "New test test_admin_success_dm_over_threshold passes: confirmed, non-test, solana_payouts, amount_usd >= threshold triggers _dm_admin_payment_success; under-threshold does not; failure DM path is unchanged.",
"priority": "must"
},
{
"criterion": "New test test_admin_success_dm_sees_derived_usd passes: a confirmed payment whose amount_usd came from the Step 8 derivation path (amount_token-only capped caller) reliably triggers _dm_admin_payment_success. Pins end-to-end success-DM wiring for admin-chat payouts.",
"priority": "must"
},
{
"criterion": "New test test_execute_payment_uses_stored_wallet passes: execute_payment passes payment['recipient_wallet'] (frozen) to provider.send even when wallet_registry has been updated.",
"priority": "must"
},
{
"criterion": "New test test_initiate_payment_tool_rejects_wallet_address_arg passes: wallet_address/recipient_wallet keys in params are popped and ignored; wallet is resolved exclusively via db_handler.get_wallet.",
"priority": "must"
},
{
"criterion": "PaymentService constructor accepts per_payment_usd_cap, daily_usd_cap, capped_providers, and on_cap_breach kwargs; all default to None so existing construction sites remain compatible.",
"priority": "must"
},
{
"criterion": "Cap enforcement in PaymentService runs only in request_payment, never in execute_payment. Scheduler path is untouched.",
"priority": "must"
},
{
"criterion": "Cap enforcement covers BOTH amount_usd-supplying callers AND amount_token-only callers end-to-end: for capped providers in the amount_token path, the derived USD is PERSISTED into record['amount_usd'] and record['token_price_usd'] (and their request_payload mirrors) BEFORE create_payment_request, so the rolling-24h aggregation and the success-DM threshold both operate on the real value. Missing price \u2192 manual_hold.",
"priority": "must"
},
{
"criterion": "For uncapped providers (or is_test=True), request_payment does NOT stamp amount_usd on token-denominated requests. Existing tests that assert for the uncapped 'solana' and 'solana_native' providers stay green, and provider.get_token_price_usd() is not called in that path.",
"priority": "must"
},
{
"criterion": "Cap-breach, collision (Branch A insert and Branch B reject), and null-recipient paths trigger an admin DM via on_cap_breach or equivalent path. No silent rejection.",
"priority": "must"
},
{
"criterion": "Collision handling is index-aware: Branch A (prior rows all failed/cancelled) inserts a fresh manual_hold row; Branch B (any prior row in a non-excluded status) returns None without attempting an insert.",
"priority": "must"
},
{
"criterion": "upsert_wallet blocked path raises WalletUpdateBlockedError (not a truthy sentinel). Both admin_chat._handle_wallet_received and grants_cog._start_payment_flow catch the exception.",
"priority": "must"
},
{
"criterion": "upsert_wallet's existing-wallet lookup runs BEFORE the has_active_payment_or_intent guard. Identical-address upserts and upserts with no prior row are never blocked.",
"priority": "must"
},
{
"criterion": "_dm_admin_payment_success is a new sibling method with a distinct prefix ('\u2705 ') and no 'requires manual review' line. _dm_admin_payment_failure is unchanged.",
"priority": "must"
},
{
"criterion": "PaymentCog reads success-DM threshold and provider set from env inside with defaults (500/500, daily=100. capped_providers defaults to frozenset({'solana_payouts'}).",
"Cap-breach admin DM is routed via an async callback wired from main.py, invoking payment_cog._dm_admin_payment_failure (whose wording already fits cap-breach / collision-block semantics).",
"For amount_token-only callers on CAPPED providers, cap enforcement derives USD via provider.get_token_price_usd() * amount_token AND PERSISTS the derived value into record['amount_usd'], record['token_price_usd'], record['request_payload']['amount_usd'], and record['request_payload']['token_price_usd'] BEFORE create_payment_request runs. This makes the rolling helper and success-DM gate see the real USD value end-to-end. If the price lookup fails, the row is held as manual_hold with last_error='cap check unavailable: token price missing'. This is the end-to-end fix for FLAG-001 / correctness / all_locations / callers / issue_hints / scope.",
"For UNCAPPED providers OR is_test=True, amount_usd is NOT stamped on token-denominated requests. Existing tests (test_request_payment_amount_token at tests/test_admin_payments.py:684-709 uses provider 'solana'; tests/test_social_publish_service.py:474-497 uses provider 'solana_native' with is_test=True) both depend on this and assert ; both provider names are outside the default capped_providers set, so the new stamping branch never fires for them.",
"The existing amount_token test at tests/test_admin_payments.py:684-709 also asserts ; the derivation branch is gated on , so the price lookup is never invoked for uncapped providers and the counter stays at 0.",
"upsert_wallet blocked path raises WalletUpdateBlockedError (not a truthy sentinel); both admin_chat and grants_cog catch it explicitly.",
"The unique index uq_payment_requests_active_producer_ref at sql/payments.sql:126-128 is partial WHERE status NOT IN ('failed','cancelled'), so manual_hold IS covered. Collision handling uses two explicit branches (Branch A inserts when all prior rows are failed/cancelled; Branch B returns None without inserting when any prior row is non-excluded).",
"In upsert_wallet, the existing-wallet lookup runs FIRST at db_handler.py:1431, then the has_active_payment_or_intent guard consults the result.",
"Both PaymentCog construction sites (main.py:233 and the setup() hook at payment_cog.py:503) work without modification because the success-DM threshold and provider set are read via os.getenv inside PaymentCog..",
"Inline fake-db glue in tests/test_admin_payments.py:497-729, tests/test_social_publish_service.py:474-685, and tests/conftest.py is extended additively with has_active_payment_or_intent, get_rolling_24h_payout_usd, and WalletUpdateBlockedError stubs.",
"RLS is already enabled on payment_requests/wallet_registry/payment_channel_routes (sql/payments.sql:192-199). Step 12 is comment-only.",
"P0 prompt-injection hardening is verification + defensive pop-and-warn + regression test \u2014 the initiate_payment tool schema at tools.py:580-599 already omits wallet_address.",
"privileged_override=True remains usable; current admin_chat and grants auto-confirms pass matching recipient IDs under the tightened rule.",
"execute_payment's stored-wallet semantics at payment_service.py:244 are code-unchanged; regression-pin test only.",
"Git-history audit and log audit are memo tasks \u2014 priority, not ."
],
"delta_from_previous_percent": 36.82,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "Payments caps: Recurring debt: the revised amount_token fix still keeps derived USD out of the stored payment row, so admin-chat token-denominated payouts do not reliably participate in the rolling daily USD cap or the success-DM threshold.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the revised Step 8 and Step 9 together against the real admin-chat final payout caller at src/features/admin_chat/admin_chat_cog.py:352-365. The plan now derives USD for amount_token-only requests during cap checks, but its own assumptions say that derived USD is kept local and not written back to record['amount_usd']; because get_rolling_24h_payout_usd is defined to sum stored payment_requests.amount_usd and the success-DM gate in Step 9 checks payment.get('amount_usd'), the actual admin-chat payouts would still miss the rolling daily cap and success-DM threshold in the live flow.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: The amount_token issue is broader than the immediate cap check. In this codebase, admin-chat final payouts are token-denominated at creation time, but later observability and rolling-budget logic operate on the stored amount_usd field. Because the revised plan keeps the derived USD local, it fixes the one-request calculation while leaving the broader payment-ledger semantics inconsistent for the same admin payout path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-1",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked the real admin payout caller at src/features/admin_chat/admin_chat_cog.py:352-365; it passes amount_token and omits amount_usd, so any cap logic written around the grants-style USD caller alone will miss the exact caller the brief cares about most.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verification-1",
"concern": "Is there convincing verification for the change?: The planned test list does not include a cap test for the admin-chat final-payment path that passes amount_token without amount_usd, even though that is the live caller in src/features/admin_chat/admin_chat_cog.py:352-365. Without that regression test, the cap feature could still ship green while leaving the primary admin payout path uncapped.",
"status": "open",
"severity": "minor"
},
{
"id": "criteria_quality",
"concern": "Are the success criteria well-prioritized and verifiable?: One must still overstates what the current plan would prove: 'Cap enforcement covers BOTH amount_usd-supplying callers AND amount_token-only callers' reads as an end-to-end guarantee, but the plan's own assumption that derived USD stays out of the stored row means rolling-daily enforcement and success-DM thresholding are still not fully covered for amount_token-only admin-chat payouts.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness",
"concern": "Are the proposed changes technically correct?: There is still a correctness gap in the amount_token path. The plan derives a transient for current-request checks but explicitly keeps that value out of ; as a result, later logic that depends on stored USD, namely the rolling-24h aggregation and the confirmed-payment success-DM threshold, would still behave as if admin-chat token-denominated payouts were worth $0.00.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations",
"concern": "Does the change touch all locations AND supporting infrastructure?: Not all supporting locations are aligned on the amount_token path yet. Step 8 derives USD locally in , Step 7's rolling helper sums stored , and Step 9's success-DM gate reads ; unless the derived USD is persisted or recomputed in the downstream sites too, the feature is still only partially wired across the repository.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked the actual admin payout caller and the downstream consumer. still creates final payouts with only, while the planned success-DM gate in keys off ; with the revised assumption that derived USD stays local instead of being stored, the real caller shape is still not handled end-to-end.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verification",
"concern": "Is there convincing verification for the change?: There is still no test that an amount_token-only admin-chat payout contributes to the rolling-24h USD total or that a confirmed amount_token-only payout can cross the success-DM threshold. Because the revised plan keeps derived USD out of the stored row, those two real behaviors can still be wrong while every newly listed test passes.",
"status": "open",
"severity": "minor"
}
]
code
Known accepted debt grouped by subsystem:
{
"admin-chat-classification": [
{
"id": "DEBT-006",
"concern": "anthropic client may not be initialized when interceptor fires before _ensure_agent.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
}
],
"admin-payments-intent-state": [
{
"id": "DEBT-004",
"concern": "button confirmation path does not directly update admin_payment_intents \u2014 intent sync happens indirectly via handle_payment_result on terminal state.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
},
{
"id": "DEBT-005",
"concern": "no direct bridge from paymentconfirmview to admin_payment_intents.",
"occurrence_count": 1,
"plan_ids": [
"admin-triggered-payments-let-20260410-1448"
]
}
],
"db-handler-social-publications": [
{
"id": "DEBT-001",
"concern": "mixing fluent client, raw sql, and rpc access patterns in one subsystem increases maintenance surface.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
],
"db-handler-supabase-infrastructure": [
{
"id": "DEBT-002",
"concern": "supabase rpc is untested in this codebase and may require dashboard configuration.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
],
"social-channel-routes": [
{
"id": "DEBT-003",
"concern": "route management tooling is absent, leaving the routing system inert until manual db inserts.",
"occurrence_count": 1,
"plan_ids": [
"implement-a-unified-social-20260409-1710"
]
}
]
}
code
Escalated debt subsystems:
[]
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Your output template is at: /Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc/.megaplan/plans/harden-the-solana-payment-20260410-2147/critique_output.json
Read this file first — it contains 8 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 3. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: heavy. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
Not yet included in a published release.
Admin DM path today fires only on failed/manual_hold via payment_cog._dm_admin_payment_failure (payment_cog.py:267-333). No success DM exists. Add a sibling _dm_admin_payment_success called from _handle_terminal_payment when status=='confirmed', not is_test, provider in {'solana_payouts'}, and amount_usd >= ADMIN_SUCCESS_DM_THRESHOLD_USD (default 100). Must be visually differentiated from failure DM (distinct prefix/emoji). (source: src/features/payments/payment_cog.py:267-333; relevance: high)
Two Solana providers are already split and wired in main.py:157-161 ('solana_grants', 'solana_payouts'). grants_cog uses 'solana_grants' exclusively (grants_cog.py:574,686); admin_chat uses 'solana_payouts' (admin_chat_cog.py:238, 358). Cap enforcement must be scoped to 'solana_payouts' so grants are unaffected. Rolling daily window aggregates on (guild_id, provider='solana_payouts', status IN pending_confirmation/queued/processing/submitted/confirmed) within 24h. (source: main.py:157-161; src/features/admin_chat/admin_chat_cog.py:238,358; src/features/grants/grants_cog.py:574,686; relevance: medium)
upsert_wallet in db_handler.py:1417-1465 has no inflight-intent check. It updates wallet_address in place and clears verified_at on change (line 1442). Fix: before UPDATE, call a new helper has_active_payment_or_intent(guild_id, discord_user_id) that queries non-terminal payment_requests rows AND awaiting_* admin_payment_intents rows; abort with a structured error if any exist. Caller (_handle_wallet_received at admin_chat_cog.py:193-218) surfaces the error to the admin review channel. (source: src/common/db_handler.py:1417-1465; src/features/admin_chat/admin_chat_cog.py:193-218; relevance: high)
Existing tests: tests/test_admin_payments.py instantiates a real PaymentService at line 687 with provider dict {'solana': provider} (note: NOT 'solana_payouts'). tests/test_social_publish_service.py:474-685 also uses real PaymentService. Cap config must be injectable via constructor kwargs with sensible defaults (or a capped_providers set) so these tests keep passing without rewrites. conftest.py supplies shared fixtures. Existing tests cover happy paths but NOT the adversarial cases we're adding. (source: tests/test_admin_payments.py:497-729; tests/test_social_publish_service.py:474-685; tests/conftest.py; relevance: medium)
sql/payments.sql currently has no header comment and no documented RLS posture. Given Supabase/Postgres with service-role access from the bot, posture is 'RLS NOT enabled; all access mediated via service-role handlers in db_handler.py; no direct browser/Discord client access; writes parameterized'. Comment-only — do NOT ALTER TABLE ENABLE RLS (requires rewriting policies across the bot). (source: sql/payments.sql:1-12; relevance: medium)
Logging audit targets: src/common/log_handler.py (central logger). Payment logs already redact wallets via _redact_wallet/_redact_wallet_address (payment_cog.py; admin_chat/tools.py:1072-1124). SolanaClient logs recipient+signature only. Grep for SOLANA_PRIVATE_KEY, HELIUS_API_KEY, Keypair.from_bytes tracebacks, os.environ dumps. Document findings; add scrubbing only if a real leak is found. (source: src/common/log_handler.py; src/features/payments/payment_cog.py; src/features/admin_chat/tools.py:1072-1124; relevance: medium)
code
### Relevant Code
| File | Functions | Why |
500/
### Constraints
- Fail-closed: on ANY validation ambiguity (cap, collision, null recipient, inflight wallet change), the payment must NOT execute. Prefer manual_hold + admin DM over silent rejection so the trail is preserved.
Do NOT change the partial-index predicate on uq_payment_requests_active_producer_ref — legitimate retries after a failed payment rely on the failed/cancelled exclusion. Collision detection must live in app code.
Do NOT break grants. Cap enforcement and admin success DM must be scoped to provider='solana_payouts' (or an explicit capped_providers set), not global. grants_cog uses 'solana_grants' with its own semantics.
Do NOT re-read recipient_wallet from wallet_registry in execute_payment. Keep the frozen-string behavior at payment_service.py:244. Add a regression test pinning this.
Do NOT add LLM-sourced wallet parameters anywhere. If a sibling admin_chat tool is found that accepts wallet_address text, remove or harden it in the same plan.
Do NOT widen upsert_wallet's blocking window beyond necessary. Block ONLY while a non-terminal payment_requests row OR an awaiting_* admin_payment_intents row exists for (guild_id, discord_user_id). Completed/failed/cancelled intents must NOT block.
Do NOT log secrets. Any new logging in cap/collision/success-DM paths must redact wallets via existing _redact_wallet helpers and must not log env-var values or key material.
Cap config must be injectable via PaymentService constructor kwargs (not env-only) so existing tests can pass high/infinite caps without env pollution.
Helius RPC and SolanaClient primitives are out of scope per task. Fix only application-layer vectors.
sql/payments.sql RLS documentation is COMMENT-ONLY. Do NOT ALTER TABLE ENABLE RLS — that would require rewriting policies across the bot's service-role access.
Admin success DM must be visually differentiated from failure DM (distinct prefix, emoji, status word). Do NOT overload _dm_admin_payment_failure — add a sibling method.
Default thresholds (env-overridable): per-payment cap 500,dailycap2000/guild, admin success DM threshold $100. Bake defaults into main.py's PaymentService constructor call.
Null-recipient_discord_id fix must preserve privileged_override=True escape hatch for admin auto-advance of test payments (admin_chat_cog.py:258-262). Verify test payments still carry recipient_discord_id and don't hit the null path.
Rolling 24h cap must include in-flight statuses (pending_confirmation/queued/processing/submitted/confirmed) so burst concurrent tool calls cannot all slip under the cap simultaneously. If a serializable transaction is impractical, document the residual burst window in a comment.
P0 prompt-injection task premise is already mostly fixed — the plan must explicitly say 'verification + defensive assertion + test' is the work, not a rewrite, so the review agent does not mark prep as incomplete.
code
### Suggested Approach
Implement in this order so each layer builds on verified foundations. DO NOT delegate understanding of the subtle wallet-swap and idempotency paths.
P1: Admin success DM (payment_cog.py:267-333). Add _dm_admin_payment_success sibling with distinct prefix ('✅ Payment Completed'), called from _handle_terminal_payment when status=='confirmed' AND not is_test AND provider in admin-payout set AND amount_usd >= ADMIN_SUCCESS_DM_THRESHOLD_USD env (default 100). Reuse ADMIN_USER_ID plumbing. Do NOT touch _dm_admin_payment_failure.
P2: Log audit. Grep src/ for os.environ/os.getenv sites near key access, exc_info=True near SolanaClient.from_bytes. Document findings in plan memo. Add a scrubbing filter in log_handler.py ONLY if a real leak path is found.
P2: Git history secret audit. Run git log -p -S 'PRIVATE_KEY' -- ., git log -p -- '**/*.env*', gitleaks if installed. Record findings in plan output. Audit task, not a code fix (unless a leaked secret requires rotation — flag to user separately).
Regression tests. Add all tests from test_expectations. Run pytest tests/ and verify test_admin_payments, test_scheduler, test_social_publish_service remain green. Defaults for new constructor kwargs must keep existing test construction sites passing unchanged.
Main wiring (main.py:157-161). Pass the new kwargs from env vars with documented defaults.
PaymentCog is constructed at two sites: main.py:233 and the setup(bot) extension hook at src/features/payments/payment_cog.py:503. To avoid drift, the success-DM threshold/providers are read insidePaymentCog.__init__ from env (with defaults). Neither construction site needs to change.
Inline fake-db test glue lives in tests/test_admin_payments.py and tests/test_social_publish_service.py (not only tests/conftest.py). Any new DatabaseHandler helper the tests depend on must be stubbed in the same module's fake.
Modify
_start_payment_flow
grants_cog.py:550-565
upsert_wallet
try/except WalletUpdateBlockedError
request_payment
python
try:
wallet_record = self.db.upsert_wallet(...)
except WalletUpdateBlockedError:
await thread.send(
"I cannot register this wallet right now: there is an active payment "
"in progress for your account. Please wait for it to finalize and try again."
)
return
Grepself.db.upsert_wallet( and db_handler.upsert_wallet( and .upsert_wallet( to confirm those are the only two callers. If a third caller is discovered, add equivalent handling there.
Handle collision — two explicit branches (immediately after the loop):
Branch A — slot reuse after terminal failure (blocking_prior_row is None, i.e. every prior row is in failed/cancelled): the partial unique index permits a new insert. Proceed to build record as normal with status='manual_hold', last_error='idempotency collision: prior wallet differs'. Fire admin DM via the cap-breach callback (Step 8). Insert via create_payment_request.
Branch B — prior row still covered by the index (blocking_prior_row is not None): a new insert would violate the unique index. Do NOT attempt the insert. Log WARN, DM admin via the cap-breach callback, and return None. The caller (admin_chat / grants) already handles None as "final payout could not be created" and surfaces to the admin channel. Include a comment explaining that this path intentionally does NOT try to insert — the existing non-terminal row represents a legitimate in-flight payment whose wallet cannot be overwritten mid-flow.
Fallback path at payment_service.py:167-174 (post-insert duplicate re-read for concurrent races): after the re-read, apply the same collision check against the re-read row. If the re-read row has a different wallet, log WARN, fire the cap-breach DM, and return None. If the wallet matches, return the canonical row.
Inline comment at the reorder explaining the invariant: "Terminal rows must not short-circuit idempotent return — otherwise a failed prior row is handed back to the caller as if fresh. Caller expects a live pending_confirmation row or None."
Compute cap_breach and stamp record before the insert:
python
cap_breach: Optional[str] = None
if not is_test and provider.strip().lower() in self.capped_providers:
if cap_usd is None:
cap_breach = "cap check unavailable: token price missing"
else:
if self.per_payment_usd_cap is not None and cap_usd > self.per_payment_usd_cap:
cap_breach = (
f"per-payment cap exceeded: ${cap_usd:.2f} > ${self.per_payment_usd_cap:.2f}"
)
elif self.daily_usd_cap is not None:
rolling = float(
self.db_handler.get_rolling_24h_payout_usd(guild_id, provider.strip().lower()) or 0.0
)
if rolling + cap_usd > self.daily_usd_cap:
cap_breach = (
f"daily cap exceeded: ${rolling:.2f} + ${cap_usd:.2f} > ${self.daily_usd_cap:.2f}"
)
if cap_breach:
self.logger.warning(
"[PaymentService] cap breach for %s:%s — %s", producer, producer_ref, cap_breach,
)
record['status'] = 'manual_hold'
record['last_error'] = cap_breach
Aftercreate_payment_request(record, ...), if cap_breach and created and self._on_cap_breach, await self._on_cap_breach(created). This fires the admin DM for cap-breach AND for the collision Branch-A case (Step 6) — the collision path stamps the same fields and then re-uses this post-insert hook.
Do NOT add cap logic in execute_payment. Verify by running pytest tests/test_scheduler.py after the change (scheduler path unchanged).
test_request_payment_amount_token_path_missing_price_holds — new: amount_token path, provider returns None/0 for price, cap enabled → manual_hold with "cap check unavailable". Fail-closed pin.
test_request_payment_rolling_daily_cap_manual_holds — seed fake with 1900rolling24hofsolanapayoutsat‘confirmed‘;new200 → manual_hold. Solana_grants $5000 seeded → does NOT count.
test_slot_reuse_collision_detected_after_failure — prior row status='failed' with different wallet; new request inserts a fresh manual_hold row (Branch A) + on_cap_breach fires.
test_slot_reuse_collision_blocked_when_prior_active — new: prior row status='pending_confirmation' with different wallet; new request returns None + on_cap_breach fires; the prior row is NOT replaced (pins Branch B — no insert attempt under live unique index).
test_slot_reuse_same_wallet_creates_fresh_row_after_failure — only terminal prior rows with matching wallet; new request creates a fresh pending_confirmation row (pins reordered early-return).
test_idempotent_return_for_nonterminal — non-terminal prior row with matching wallet → returned unchanged.
test_upsert_wallet_raises_during_active_intent — fake db has an active payment_requests row for the user; upsert_wallet raises WalletUpdateBlockedError; a follow-up test confirms _handle_wallet_received catches it and calls _notify_admin_review. A second follow-up confirms _start_payment_flow in grants_cog catches it and sends the thread fallback message.
test_upsert_wallet_unblocked_after_terminal — only terminal prior rows → upsert proceeds normally.
test_admin_success_dm_over_threshold — confirmed, non-test, solana_payouts, amount_usd=150 → _dm_admin_payment_success called. Under threshold → not called. Failure path unchanged.
test_execute_payment_uses_stored_wallet — seed payment row with frozen recipient_wallet='STORED'; mutate wallet_registry to 'NEW'; execute_payment still passes 'STORED' to provider.send.
test_initiate_payment_tool_rejects_wallet_address_arg — call execute_initiate_payment with params={'wallet_address': 'EVIL', ...}; assert wallet resolves via db_handler.get_wallet and the evil string never reaches PaymentService.request_payment.
Verify existing happy-path tests still pass with default (None) caps by running pytest tests/test_admin_payments.py after each adjacent change, not only at the end.
Payment Completed
init
100, 'solana_payouts'), so both construction sites (main.py:233 and src/features/payments/payment_cog.py:503 setup hook) stay in sync without modification.",
"priority": "must"
},
{
"criterion": "main.py wires per_payment_usd_cap, daily_usd_cap, capped_providers=('solana_payouts',), and on_cap_breach into PaymentService from env vars with defaults
2000 and logs effective caps at startup.",
"priority": "must"
},
{
"criterion": "sql/payments.sql has a top-of-file comment block documenting the RLS posture (RLS already enabled, anon/authenticated revoked, service-role bypass). No ALTER TABLE changes.",
"priority": "must"
},
{
"criterion": "Admin success DM is provider-scoped and threshold-gated; solana_grants payouts never trigger admin success DMs.",
"priority": "must"
},
{
"criterion": "Inline fake-db glue in tests/test_admin_payments.py, tests/test_social_publish_service.py, and tests/conftest.py is extended with has_active_payment_or_intent, get_rolling_24h_payout_usd, and WalletUpdateBlockedError stubs additively (no rewrites of existing tests).",
"priority": "must"
},
{
"criterion": "pytest tests/ runs green end-to-end.",
"priority": "must"
},
{
"criterion": "New cap/collision/DM code paths redact wallets via existing _redact_wallet helpers and never log env values or key material.",
"priority": "should"
},
{
"criterion": "has_active_payment_or_intent uses the same non-terminal predicates as existing helpers (('completed','failed','cancelled') for intents; ('confirmed','failed','manual_hold','cancelled') for payments) \u2014 no ad-hoc drift.",
"priority": "should"
},
{
"criterion": "Inline comment at the collision-detection + idempotent-return reorder explains WHY terminal rows must not short-circuit the early return.",
"priority": "should"
},
{
"criterion": "Rolling-24h cap helper includes a comment documenting the residual burst-race window under non-serializable Supabase REST access.",
"priority": "should"
},
{
"criterion": "Git history secret audit commands from Step 3 are run and findings recorded in the review memo (pass-through task; not directly diff-verifiable).",
"priority": "should"
},
{
"criterion": "Log audit grep from Step 11 is performed and findings recorded. If no real leak path is found, no log_handler.py code change.",
"priority": "should"
},
{
"criterion": "Plan output explicitly states that the P0 prompt-injection premise was already substantially satisfied by prior work, so review does not mark prep as incomplete.",
"priority": "should"
},
{
"criterion": "No unrelated refactors or test rewrites beyond what the new behavior strictly requires.",
"priority": "should"
}
],
"assumptions": [
"get_payment_requests_by_producer at db_handler.py:1853 already returns rows across all statuses with no terminal filter, so collision detection can reuse it directly \u2014 no new helper is needed, only a clarifying inline comment.",
"admin_payment_intents 'active' predicate is `status NOT IN ('completed','failed','cancelled')`, matching get_active_intent_for_recipient at db_handler.py:1754.",
"payment_requests 'active/non-terminal' predicate is `status NOT IN ('confirmed','failed','manual_hold','cancelled')`.",
"Rolling 24h cap window includes `confirmed` rows (committed USD) plus non-terminal in-flight rows; excludes manual_hold/failed/cancelled. Documented burst-race residual.",
"Default cap thresholds are per_payment=
2000/guild,successDM=
on_cap_breach
init
init
should
must
upsert_wallet
src/features/grants/grants_cog.py:557-603
admin_chat_cog._handle_wallet_received
PaymentCog(
main.py:233
src/features/payments/payment_cog.py:503
tests/test_admin_payments.py
tests/test_social_publish_service.py
tests/conftest.py
src/features/admin_chat/admin_chat_cog.py:352-365
amount_token
amount_usd
upsert_wallet
src/features/admin_chat/admin_chat_cog.py:193-201
src/features/grants/grants_cog.py:557-562
{'__error__': ...}
{'__error__': 'active_payment_or_intent'}
DatabaseHandler
Optional[Dict]
bool
None
False
src/common/db_handler.py
amount_token
amount_usd
src/features/admin_chat/admin_chat_cog.py:352-365
upsert_wallet
grants_cog
must
must
Admin DM path today fires only on failed/manual_hold via payment_cog._dm_admin_payment_failure (payment_cog.py:267-333). No success DM exists. Add a sibling _dm_admin_payment_success called from _handle_terminal_payment when status=='confirmed', not is_test, provider in {'solana_payouts'}, and amount_usd >= ADMIN_SUCCESS_DM_THRESHOLD_USD (default 100). Must be visually differentiated from failure DM (distinct prefix/emoji). (source: src/features/payments/payment_cog.py:267-333; relevance: high)
Two Solana providers are already split and wired in main.py:157-161 ('solana_grants', 'solana_payouts'). grants_cog uses 'solana_grants' exclusively (grants_cog.py:574,686); admin_chat uses 'solana_payouts' (admin_chat_cog.py:238, 358). Cap enforcement must be scoped to 'solana_payouts' so grants are unaffected. Rolling daily window aggregates on (guild_id, provider='solana_payouts', status IN pending_confirmation/queued/processing/submitted/confirmed) within 24h. (source: main.py:157-161; src/features/admin_chat/admin_chat_cog.py:238,358; src/features/grants/grants_cog.py:574,686; relevance: medium)
upsert_wallet in db_handler.py:1417-1465 has no inflight-intent check. It updates wallet_address in place and clears verified_at on change (line 1442). Fix: before UPDATE, call a new helper has_active_payment_or_intent(guild_id, discord_user_id) that queries non-terminal payment_requests rows AND awaiting_* admin_payment_intents rows; abort with a structured error if any exist. Caller (_handle_wallet_received at admin_chat_cog.py:193-218) surfaces the error to the admin review channel. (source: src/common/db_handler.py:1417-1465; src/features/admin_chat/admin_chat_cog.py:193-218; relevance: high)
Existing tests: tests/test_admin_payments.py instantiates a real PaymentService at line 687 with provider dict {'solana': provider} (note: NOT 'solana_payouts'). tests/test_social_publish_service.py:474-685 also uses real PaymentService. Cap config must be injectable via constructor kwargs with sensible defaults (or a capped_providers set) so these tests keep passing without rewrites. conftest.py supplies shared fixtures. Existing tests cover happy paths but NOT the adversarial cases we're adding. (source: tests/test_admin_payments.py:497-729; tests/test_social_publish_service.py:474-685; tests/conftest.py; relevance: medium)
sql/payments.sql currently has no header comment and no documented RLS posture. Given Supabase/Postgres with service-role access from the bot, posture is 'RLS NOT enabled; all access mediated via service-role handlers in db_handler.py; no direct browser/Discord client access; writes parameterized'. Comment-only — do NOT ALTER TABLE ENABLE RLS (requires rewriting policies across the bot). (source: sql/payments.sql:1-12; relevance: medium)
Logging audit targets: src/common/log_handler.py (central logger). Payment logs already redact wallets via _redact_wallet/_redact_wallet_address (payment_cog.py; admin_chat/tools.py:1072-1124). SolanaClient logs recipient+signature only. Grep for SOLANA_PRIVATE_KEY, HELIUS_API_KEY, Keypair.from_bytes tracebacks, os.environ dumps. Document findings; add scrubbing only if a real leak is found. (source: src/common/log_handler.py; src/features/payments/payment_cog.py; src/features/admin_chat/tools.py:1072-1124; relevance: medium)
code
### Relevant Code
| File | Functions | Why |
500/
### Constraints
- Fail-closed: on ANY validation ambiguity (cap, collision, null recipient, inflight wallet change), the payment must NOT execute. Prefer manual_hold + admin DM over silent rejection so the trail is preserved.
Do NOT change the partial-index predicate on uq_payment_requests_active_producer_ref — legitimate retries after a failed payment rely on the failed/cancelled exclusion. Collision detection must live in app code.
Do NOT break grants. Cap enforcement and admin success DM must be scoped to provider='solana_payouts' (or an explicit capped_providers set), not global. grants_cog uses 'solana_grants' with its own semantics.
Do NOT re-read recipient_wallet from wallet_registry in execute_payment. Keep the frozen-string behavior at payment_service.py:244. Add a regression test pinning this.
Do NOT add LLM-sourced wallet parameters anywhere. If a sibling admin_chat tool is found that accepts wallet_address text, remove or harden it in the same plan.
Do NOT widen upsert_wallet's blocking window beyond necessary. Block ONLY while a non-terminal payment_requests row OR an awaiting_* admin_payment_intents row exists for (guild_id, discord_user_id). Completed/failed/cancelled intents must NOT block.
Do NOT log secrets. Any new logging in cap/collision/success-DM paths must redact wallets via existing _redact_wallet helpers and must not log env-var values or key material.
Cap config must be injectable via PaymentService constructor kwargs (not env-only) so existing tests can pass high/infinite caps without env pollution.
Helius RPC and SolanaClient primitives are out of scope per task. Fix only application-layer vectors.
sql/payments.sql RLS documentation is COMMENT-ONLY. Do NOT ALTER TABLE ENABLE RLS — that would require rewriting policies across the bot's service-role access.
Admin success DM must be visually differentiated from failure DM (distinct prefix, emoji, status word). Do NOT overload _dm_admin_payment_failure — add a sibling method.
Default thresholds (env-overridable): per-payment cap 500,dailycap2000/guild, admin success DM threshold $100. Bake defaults into main.py's PaymentService constructor call.
Null-recipient_discord_id fix must preserve privileged_override=True escape hatch for admin auto-advance of test payments (admin_chat_cog.py:258-262). Verify test payments still carry recipient_discord_id and don't hit the null path.
Rolling 24h cap must include in-flight statuses (pending_confirmation/queued/processing/submitted/confirmed) so burst concurrent tool calls cannot all slip under the cap simultaneously. If a serializable transaction is impractical, document the residual burst window in a comment.
P0 prompt-injection task premise is already mostly fixed — the plan must explicitly say 'verification + defensive assertion + test' is the work, not a rewrite, so the review agent does not mark prep as incomplete.
code
### Suggested Approach
Implement in this order so each layer builds on verified foundations. DO NOT delegate understanding of the subtle wallet-swap and idempotency paths.
P1: Admin success DM (payment_cog.py:267-333). Add _dm_admin_payment_success sibling with distinct prefix ('✅ Payment Completed'), called from _handle_terminal_payment when status=='confirmed' AND not is_test AND provider in admin-payout set AND amount_usd >= ADMIN_SUCCESS_DM_THRESHOLD_USD env (default 100). Reuse ADMIN_USER_ID plumbing. Do NOT touch _dm_admin_payment_failure.
P2: Log audit. Grep src/ for os.environ/os.getenv sites near key access, exc_info=True near SolanaClient.from_bytes. Document findings in plan memo. Add a scrubbing filter in log_handler.py ONLY if a real leak path is found.
P2: Git history secret audit. Run git log -p -S 'PRIVATE_KEY' -- ., git log -p -- '**/*.env*', gitleaks if installed. Record findings in plan output. Audit task, not a code fix (unless a leaked secret requires rotation — flag to user separately).
Regression tests. Add all tests from test_expectations. Run pytest tests/ and verify test_admin_payments, test_scheduler, test_social_publish_service remain green. Defaults for new constructor kwargs must keep existing test construction sites passing unchanged.
Main wiring (main.py:157-161). Pass the new kwargs from env vars with documented defaults.
tests/test_social_publish_service.py
tests/conftest.py
Existing amount_token tests (test_request_payment_amount_token at tests/test_admin_payments.py:684-709 and test_social_publish_service.py:481-497) assert result['amount_usd'] is None. Both use uncapped provider names ('solana', 'solana_native'), so stamping record['amount_usd'] only inside the capped-provider branch leaves them untouched. This is verified by grep prior to implementation.
Grep.upsert_wallet( to confirm these are the only two callers. If a third exists, add equivalent handling.
Branch B — prior row still covered by the index (blocking_prior_row is not None): do NOT attempt the insert. Log WARN, fire on_cap_breach (with the prior row as the payload for operator context), and return None. Include an inline comment explaining the invariant.
Fallback path at payment_service.py:167-174 (post-insert duplicate re-read): apply the same wallet-mismatch check against the re-read row. On mismatch: log WARN, fire on_cap_breach, return None. On match: return the canonical row.
Compute cap_breach:
python
cap_breach: Optional[str] = None
if not is_test and provider_key in self.capped_providers:
if cap_usd is None:
cap_breach = "cap check unavailable: token price missing"
else:
if self.per_payment_usd_cap is not None and cap_usd > self.per_payment_usd_cap:
cap_breach = (
f"per-payment cap exceeded: ${cap_usd:.2f} > ${self.per_payment_usd_cap:.2f}"
)
elif self.daily_usd_cap is not None:
rolling = float(
self.db_handler.get_rolling_24h_payout_usd(guild_id, provider_key) or 0.0
)
if rolling + cap_usd > self.daily_usd_cap:
cap_breach = (
f"daily cap exceeded: ${rolling:.2f} + ${cap_usd:.2f} > ${self.daily_usd_cap:.2f}"
)
Persist derived USD into record BEFORE the insert so it flows through create_payment_request and into request_payload (which mirrors the top-level fields at lines 141-160). Do this only inside the capped-provider + derived branch — uncapped providers and is_test rows keep amount_usd=None as today:
python
if derived_usd_for_record is not None:
record['amount_usd'] = derived_usd_for_record
record['token_price_usd'] = derived_price_for_record
# Keep request_payload mirror in sync so downstream reporting agrees.
record['request_payload']['amount_usd'] = derived_usd_for_record
record['request_payload']['token_price_usd'] = derived_price_for_record
if cap_breach:
self.logger.warning(
"[PaymentService] cap breach for %s:%s — %s", producer, producer_ref, cap_breach,
)
record['status'] = 'manual_hold'
record['last_error'] = cap_breach
Aftercreate_payment_request(record, ...), if cap_breach and created and self._on_cap_breach, await self._on_cap_breach(created). This also handles Step 6 Branch A (which reuses this same record-stamp + post-insert-hook path).
Do NOT add cap logic in execute_payment. Scheduler path untouched.
Verify non-regression of existing amount_token tests before landing:
tests/test_admin_payments.py:684-709 (test_request_payment_amount_token) uses provider "solana" (NOT in capped_providers), asserts result['amount_usd'] is None AND provider.price_calls == 0. Because the derivation branch only runs for capped providers, this test stays green and no extra price call happens.
tests/test_social_publish_service.py:474-497 uses provider "solana_native" and is_test=True; both gates exclude it, so amount_usd stays None.
test_request_payment_amount_token_uncapped_provider_preserves_none — new: uncapped provider ("solana"), amount_token=1.5 → result['amount_usd'] is None AND provider price lookup NOT invoked. Regression pin against the existing test_request_payment_amount_token behavior.
test_request_payment_rolling_daily_cap_manual_holds — seed 1900rolling24hsolanapayoutsconfirmed;new200 → manual_hold. Solana_grants $5000 seeded → does NOT count.
test_request_payment_rolling_daily_cap_sees_derived_usd — new: seed fake with a prior confirmed capped row created via the amount_token path (so its stored amount_usd came from the Step 8 stamp); verify get_rolling_24h_payout_usd returns the stamped total and a follow-up amount_token request accounts for it against the daily cap. Pins the end-to-end flow the critique flagged.
test_slot_reuse_collision_detected_after_failure — Branch A: only failed prior rows with different wallet → fresh manual_hold row inserted + on_cap_breach fires.
test_slot_reuse_collision_blocked_when_prior_active — Branch B: pending_confirmation prior row with different wallet → returns None without attempting insert; prior row untouched; on_cap_breach fires.
test_slot_reuse_same_wallet_creates_fresh_row_after_failure — only terminal prior rows with matching wallet → fresh pending_confirmation row.
test_idempotent_return_for_nonterminal — non-terminal prior row, matching wallet → returned unchanged.
test_upsert_wallet_unblocked_after_terminal — only terminal prior rows → upsert proceeds. Identical-address upsert while active intent exists → upsert proceeds (no block).
test_admin_success_dm_over_threshold — confirmed, non-test, solana_payouts, amount_usd=150 → _dm_admin_payment_success called. Under threshold → not called. Failure path unchanged.
test_admin_success_dm_sees_derived_usd — new: seed a confirmed payment whose amount_usd was stamped via the Step 8 derivation path (amount_token-only capped caller). Passing it through _handle_terminal_payment triggers the success DM because the gate reads payment.get('amount_usd'). Pins the end-to-end wiring.
test_initiate_payment_tool_rejects_wallet_address_arg — evil wallet_address in params popped + WARN; wallet resolves via db_handler.get_wallet.
Verify by running pytest tests/test_admin_payments.py after each phase.
amount_usd
get_token_price_usd()
on_cap_breach
status='blocked_collision'
ADMIN_PAYOUT_PER_PAYMENT_USD_CAP
ADMIN_PAYOUT_DAILY_USD_CAP
ADMIN_PAYMENT_SUCCESS_DM_THRESHOLD_USD
ADMIN_PAYMENT_SUCCESS_DM_PROVIDERS
amount_usd == amount_token * price
token_price_usd == price
amount_usd is None
Payment Completed
init
100, 'solana_payouts'), so both construction sites stay in sync without modification.",
"priority": "must"
},
{
"criterion": "main.py wires per_payment_usd_cap, daily_usd_cap, capped_providers=('solana_payouts',), and on_cap_breach into PaymentService from env vars with defaults
2000 and logs effective caps at startup.",
"priority": "must"
},
{
"criterion": "sql/payments.sql has a top-of-file comment block documenting the RLS posture. No ALTER TABLE changes.",
"priority": "must"
},
{
"criterion": "Admin success DM is provider-scoped and threshold-gated; solana_grants payouts never trigger admin success DMs.",
"priority": "must"
},
{
"criterion": "Inline fake-db glue in tests/test_admin_payments.py, tests/test_social_publish_service.py, and tests/conftest.py is extended additively with has_active_payment_or_intent, get_rolling_24h_payout_usd, and WalletUpdateBlockedError stubs (no rewrites of existing tests).",
"priority": "must"
},
{
"criterion": "pytest tests/ runs green end-to-end.",
"priority": "must"
},
{
"criterion": "New cap/collision/DM code paths redact wallets via existing _redact_wallet helpers and never log env values or key material.",
"priority": "should"
},
{
"criterion": "has_active_payment_or_intent uses the same non-terminal predicates as existing helpers \u2014 no ad-hoc drift.",
"priority": "should"
},
{
"criterion": "Inline comment at the collision-detection + idempotent-return reorder explains WHY terminal rows must not short-circuit the early return.",
"priority": "should"
},
{
"criterion": "Rolling-24h cap helper includes a comment documenting the residual burst-race window AND the upstream-persistence dependency for amount_token-only capped callers.",
"priority": "should"
},
{
"criterion": "Git history secret audit commands from Step 3 are run and findings recorded in the review memo.",
"priority": "should"
},
{
"criterion": "Log audit grep from Step 11 is performed and findings recorded.",
"priority": "should"
},
{
"criterion": "Plan output explicitly states that the P0 prompt-injection premise was already substantially satisfied by prior work.",
"priority": "should"
},
{
"criterion": "No unrelated refactors or test rewrites beyond what the new behavior strictly requires.",
"priority": "should"
}
],
"assumptions": [
"get_payment_requests_by_producer at db_handler.py:1853 returns rows across all statuses with no terminal filter; collision detection reuses it directly.",
"admin_payment_intents 'active' predicate is `status NOT IN ('completed','failed','cancelled')`.",
"payment_requests 'active/non-terminal' predicate is `status NOT IN ('confirmed','failed','manual_hold','cancelled')`.",
"Rolling 24h cap window includes `confirmed` rows plus non-terminal in-flight rows; excludes manual_hold/failed/cancelled. Residual burst-race window is documented.",
"Default cap thresholds: per_payment=