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.
Final polish and gremlin-investigation pass for the Solana payout subsystem. Runs AFTER the cleanup megaplan (payment-subsystem-follow-up-20260410-2339) finishes. Goal: close the remaining gremlin hiding spots, add operator documentation, harden edge cases, and establish ongoing safety monitoring. This is the pass that turns 'meaningfully safer' into 'well-structured and close to gremlin-free'.
Cleanup megaplan CURRENTLY IN FLIGHT: centralizes confirmation auth into PaymentService via PaymentActor enum, introduces PRODUCER_FLOWS registry, adds tx_signature_history column, splits PaymentCog into worker and UI cogs, adds safe_delete_messages primitive
Admin-DM approval feature megaplan PENDING (separate): flips admin_chat flow to admin-DM confirmation, wires AdminApprovalView in DMs
IN SCOPE for this polish pass (fourteen items grouped into phases):
PHASE A — Code refactor (depends on cleanup megaplan landing):
A1. Decompose PaymentService.request_payment into 4-5 named helper methods: _normalize_inputs, _detect_collision_and_idempotent_row, _enforce_caps, _derive_usd_amount, _persist_row. The ~300-line monster method becomes a thin orchestrator. Behavior unchanged. Tests unchanged.
A2. Move the PAYMENT_TEST_AMOUNT_SOL rent-exempt assertion from main.py startup into PaymentService.init itself so it fires on any construction path, not just bot boot.
A3. Consolidate _redact_wallet helper (currently duplicated in payment_service.py, payment_cog.py (or new worker cog), and db_handler.py) into src/common/discord_utils.py or similar. Cleanup megaplan leaves this duplicated; this item consolidates.
Assistant
PHASE B — Correctness fixes:
B4. Gate execute_retry_payment and execute_release_payment in src/features/admin_chat/tools.py on an on-chain getSignatureStatuses recheck of the stored tx_signature BEFORE clearing it and requeuing. Algorithm: if prior sig is confirmed on chain, refuse requeue and reconcile to confirmed; if failed, refuse requeue and reconcile to failed; if not_found AND blockhash is expired, allow requeue; otherwise keep in manual_hold. Closes a double-send hole flagged in the adversarial review.
B5. New !payment-resolve <payment_id> admin-only slash command that reconciles a stuck payment against on-chain truth automatically. Queries getSignatureStatuses, decides the right action (confirmed / failed / allow_requeue / keep_in_hold), writes the audit entry, and notifies the operator with the decision.
B6. Provider name migration path: detect legacy provider='solana' rows in payment_requests on worker startup, map to the correct split provider (solana_grants for producer='grants', solana_payouts for producer='admin_chat'), log a migration notice per row. If a row can't be mapped (unknown producer), mark it manual_hold with a clear reason.
PHASE C — Robustness edge cases:
C7. Dynamic priority fees via getRecentPrioritizationFees in solana_client.py. Use the 75th percentile of recent fees with a floor of SOLANA_PRIORITY_FEE_MICRO_LAMPORTS (currently the static value) and a ceiling to prevent runaway costs. Falls back to static floor on RPC error. This item is parallel-safe with cleanup because solana_client.py is not touched by cleanup.
C8. DM delivery fallback: if admin DM fails with discord.Forbidden or rate limit, post the same message to a configurable fallback channel via new env var ADMIN_FALLBACK_CHANNEL_ID. If neither path works, log at ERROR level so at least the ops monitoring catches it. Apply to both failure DMs and success DMs in the new PaymentWorkerCog.
C9. RPC-down vs timeout distinction: when both confirm_transaction and check_status fail with connection errors (not status.err), route to a more specific manual_hold with error type 'rpc_unreachable' so the operator runbook can tell this apart from legitimate confirmation timeouts. The current 'timeout' lumps them together.
PHASE D — Gremlin investigation (read-only verification, produces proof OR fix):
D10. Verify the recover_inflight-vs-worker-loop race is safe. Read claim_due_payment_requests' FOR UPDATE SKIP LOCKED semantics in sql/payments.sql:158-190. Write a test that simulates simultaneous recovery and worker claim on the same payment row. Either prove safety with the test or identify the race and fix it.
D11. Verify concurrent admin operations for the same recipient don't mis-collide. producer_ref format for admin_chat is f'{guild_id}{recipient_user_id}{int(time.time())}' at second granularity. Two admins issuing payments to the same user in the same second = collision. Check interaction with idempotency detection. Write a test that reproduces the race or prove it's handled. Fix if broken.
D12. Property-based tests over the post-cleanup PaymentService state machine using hypothesis library. Generate random sequences of (create payment, confirm, execute, recover, release, requeue) and assert invariants: every 'confirmed' row has a non-null tx_signature with on-chain err=null; no payment can transition from a terminal state backward; caps are never exceeded; fail-closed semantics hold under all sequences.
PHASE E — Documentation:
E13. docs/payments.md (new): architecture doc covering the payment state machine (with an ASCII diagram), the authorization model (PaymentActor kinds and who can confirm what per producer), the cap enforcement model, the fail-closed contract, where each invariant lives in code with file:line references, and the list of known non-obvious constraints (rent-exempt test amount, priority fees, etc.).
E14. docs/runbook-payments.md (new): operator runbook covering every non-happy-path scenario: payment in manual_hold (how to use !payment-resolve, when to escalate), payment in failed (when to retry, when to write off), wallet ghost-verified (how to clear and re-verify), admin DM not received (fallback channel, escalation), RPC down (degraded mode, what gets queued), budget cap hit (when to raise the cap, how to audit). Include the SQL audit queries from scripts/audit_ghost_confirmed_payments.py.
PHASE F — Observability / safety monitoring:
F15. scripts/check_payment_invariants.py (new): productionized version of the audit script designed to run daily via CI or cron. Checks: (a) every status=confirmed Solana row has tx_signature with err=null on-chain; (b) no row has been in pending_confirmation or processing for more than 24 hours; (c) every wallet with verified_at has a corresponding confirmed test payment with amount >= 0.001 SOL; (d) no wallet_registry row has wallet_address matching another user's address (detect address reuse); (e) daily cap aggregates match between recent payment_requests rows and cache state if any. Exit nonzero on any violation so CI fails and alerts.
F16. Structured logging of the full RPC status object at the 'payment confirmed' decision point (solana_client.py confirm_tx success path) so future regressions are visible in logs instead of silently lying to the worker. Use logger.info with a 'tx_confirm_decision' event key so log aggregation can alert.
OUT OF SCOPE:
Anything the cleanup megaplan already handles (wait for it to land)
The admin-DM approval feature (separate megaplan)
New chains, providers, or wallets
UI changes to existing views
Rewriting solana_client.py / solana_provider.py beyond the specific items above
DEPENDENCIES:
Phase A items depend on the cleanup megaplan landing (because they operate on the post-cleanup shape of payment_service.py and the new worker/UI cogs)
Phase B, C, D, E, F items can be implemented in any order after cleanup lands, but should be grouped for commit cohesion
This plan should run AFTER the admin-DM feature megaplan too, so that gremlin investigation (D12) sees the final state machine including admin_dm authorization
SUCCESS CRITERIA:
All fourteen items either land or are explicitly deferred with a written justification
No regression in existing grants or admin_chat payment flows; tests pass
Phase D produces a written verdict per gremlin item: 'proven safe via test' or 'fixed with commit'
docs/payments.md and docs/runbook-payments.md are committed and readable by a new engineer in under 15 minutes
scripts/check_payment_invariants.py runs successfully against prod DB and fails on synthetic violations
After this pass, the payment subsystem is close enough to gremlin-free that an operator can sleep at night with real money in the wallets
Think carefully about items D10, D11, D12 — they are investigation tasks, not implementation tasks. The output might be 'this is proven safe by the attached test' or 'this was broken; here is the fix.' Both outcomes are acceptable deliverables.
User notes and answers:
Operator answered all 7 open questions with 'no strong opinion, you decide'. Orchestrator decisions: (1) C7/F16 target src/features/grants/solana_client.py — the existing shared SolanaClient class used by both providers. Do NOT create a new file. (2) A3 shared _redact_wallet helper lives in a NEW src/common/redaction.py module, not discord_utils.py — the helper is chain-agnostic so a dedicated module is honest about scope. (3) A3 does NOT unify admin_chat/tools.py's _redact_wallet_address / _redact_wallet_row / _redact_payment_row helpers — different signatures and behaviors, separate follow-up. (4) F15 ships the script plus a scheduler-wire-up section in docs/runbook-payments.md flagged as an operator decision (Railway cron vs GitHub Actions vs external scheduler). Do NOT add a CI workflow or Railway config file as part of this pass. (5) D10 fix direction IF the recover-vs-worker race turns out to be real: conditional update gated on submitted_at/updated_at older than 150 seconds (5x the 30s worker tick interval). The investigation must first prove the race is real — if FOR UPDATE SKIP LOCKED already handles it, no fix is required. Report the proof-or-fix outcome clearly. (6) D11 fix direction IF same-second admin collision is real: millisecond precision in producer_ref (Option A from the question). Full UUID suffix (Option B) is REJECTED because it would permanently break idempotency on legitimate replay paths, which is a worse outcome. (7) B4 blockhash-expired heuristic: submitted_at older than 150 seconds. Do NOT add a getLatestBlockhash round-trip — the 150s heuristic is 2x the max blockhash lifetime, conservative enough. Plan should remain at state 'planned' after incorporating these decisions — do not auto-advance to critique or execute without an explicit user nudge.
code
Plan:
# Implementation Plan: Final Polish & Gremlin-Investigation Pass for Solana Payout Subsystem
Overview
This is the fourth pass on the payouts subsystem, landing AFTER the in-flight cleanup megaplan (payment-subsystem-follow-up-20260410-2339) and the pending admin-DM approval megaplan. Goal: close remaining gremlin-hiding spots, harden edge cases, produce ops documentation, and establish daily safety monitoring.
Current repo shape (verified 2026-04-11):
src/features/payments/payment_service.py — ~600 lines; request_payment is a single ~250-line function (lines 69–316) that will be the refactor target (A1). Already has PaymentActor/PaymentActorKind, _authorize_actor, confirm_payment, execute_payment, recover_inflight. Has a local _redact_wallet at line 33.
src/features/payments/payment_cog.py — ~580 lines, still monolithic worker+UI+DM. The cleanup megaplan will split this into PaymentWorkerCog and PaymentUICog; the C8 DM fallback and A3 redact consolidation target the post-split worker cog.
src/features/payments/producer_flows.py — already exists with PRODUCER_FLOWS registry and get_flow.
src/features/payments/solana_provider.py — thin adapter around src/features/grants/solana_client.py. The idea text says "solana_client.py" for C7/F16 and it is src/features/grants/solana_client.py (not inside payments/). F16 logging lives in SolanaClient.confirm_tx (grants/solana_client.py:139–175) and C7 getRecentPrioritizationFees lives in SolanaClient (grants/solana_client.py:52–54 current static floor, send_sol at 67–137).
src/features/admin_chat/tools.py — execute_retry_payment at 2355–2370 and execute_release_payment at 2392–2413 are the B4 targets. execute_initiate_payment at 2438+ constructs producer_ref = f"{guild_id}_{recipient_user_id}_{int(time.time())}" at line 2486 — the B-item-free (D11) collision target.
sql/payments.sql — claim_due_payment_requests RPC at lines 166–198 with FOR UPDATE SKIP LOCKED; tx_signature_history column already added at line 209+. payment_requests has unique index on tx_signature (line 138), a partial-unique index on (producer, producer_ref, is_test) excluding failed/cancelled (line 134).
main.py:167–209 — the rent-exempt guard (A2 target) currently lives at boot, not in PaymentService.__init__. Providers are constructed as solana_grants and solana_payouts (already split).
scripts/audit_ghost_confirmed_payments.py — existing audit script, the seed for F15 productionized invariant checker.
docs/ — no existing payments doc; docs/payments.md and docs/runbook-payments.md are new.
tests/test_admin_payments.py — uses FakeAdminPaymentService; tests/test_solana_client.py already exists. No property-based (hypothesis) tests yet; hypothesis is not in requirements.txt.
Constraints that matter:
Sequencing: Phase A depends on cleanup landing because file shapes change. Phases B–F can ship in parallel after cleanup. This plan assumes cleanup + admin-DM megaplan are merged before execution starts.
Fail-closed semantics are non-negotiable. Every change must preserve them. Phase D items are investigation-first — acceptable outputs are "proven safe via test" or "fixed with commit".
Read-only audits must never mutate payment state.
B4's on-chain recheck is the teeth of the plan — it closes the current double-send hole where execute_retry_payment nulls tx_signature and requeues without verifying the prior signature didn't land.
Phase A: Code refactor (post-cleanup shape)
Step 1: Decompose PaymentService.request_payment into named helpers (src/features/payments/payment_service.py)
Scope: Medium
Extract the following pure-ish helpers from request_payment (currently payment_service.py:69–316), keeping behavior and signatures unchanged from the caller's perspective:
_normalize_inputs(**kwargs) -> NormalizedRequest — returns a dataclass with wallet, producer, producer_ref, chain, provider_key, etc., or None on validation failure. Absorbs lines 91–98 and the provider normalization at 139.
_persist_row(record, normalized, guild_id, is_test, collision_row, blocking_prior_row) -> Optional[dict] — absorbs the create_payment_request + duplicate re-read fallback at lines 286–316.
Rewriterequest_payment as a thin orchestrator (~40 lines) calling the helpers in sequence. Keep public signature identical.
Do not change any return semantics, log messages, or side-effect ordering. This is a behavior-preserving refactor.
Runtests/test_admin_payments.py and any existing payment_service tests unchanged — they must pass without modification.
Step 2: Move rent-exempt guard into PaymentService.__init__ (src/features/payments/payment_service.py, main.py)
Scope: Small
Add a module-level constant MIN_TEST_LAMPORTS = 2_000_000 and RENT_EXEMPT_LAMPORTS = 890_880 in payment_service.py.
Validate in PaymentService.__init__ (line 45+): compute int(self.test_payment_amount * 1_000_000_000) and raise ValueError with the same message currently at main.py:178–184 if below MIN_TEST_LAMPORTS.
Remove the duplicate check from main.py:173–184, keeping only the env var read. Comment can stay as a one-liner pointing to PaymentService for the reason.
Add a unit test in tests/test_admin_payments.py (or a new tests/test_payment_service.py) that asserts PaymentService(test_payment_amount=0.0001, ...) raises ValueError.
Addredact_wallet(wallet: Optional[str]) -> str to src/common/discord_utils.py (or a new src/common/redaction.py if the user prefers non-Discord-specific placement — see Question 2).
Replace the local _redact_wallet definitions at payment_service.py:33, payment_cog.py:18 (and any post-cleanup worker cog variant), and db_handler.py:13 with an import.
Do not consolidate admin_chat/tools.py:_redact_wallet_address — it handles dict rows and has a distinct signature; flag for a follow-up if the user wants that unified (see Question 3).
Phase B: Correctness fixes
Step 4: On-chain recheck gate for retry/release (src/features/admin_chat/tools.py, src/features/payments/payment_service.py)
Scope: Medium
Add a new PaymentService.reconcile_with_chain(payment_id, *, guild_id) -> ReconcileDecision method. Logic:
Fetch payment row; if no tx_signature, return decision='allow_requeue' (nothing to double-send).
Call provider.check_status(tx_signature).
If 'confirmed': call mark_payment_confirmed and return decision='reconciled_confirmed'.
If 'failed': call mark_payment_failed (if not already) and return decision='reconciled_failed'.
If 'not_found': check blockhash-expiry heuristic — since we can't cheaply check blockhash expiry from here, treat not_found as safe to requeue only ifsubmitted_at is older than a conservative window (e.g. 150 seconds, longer than Solana's ~90s blockhash lifetime). Otherwise return decision='keep_in_hold' with reason 'signature not_found but too recent to be safe'.
On provider exception: return decision='keep_in_hold' with reason 'RPC unreachable during reconcile'.
Gateexecute_retry_payment at tools.py:2355–2370: call payment_service.reconcile_with_chain first; only proceed to db_handler.requeue_payment if decision is allow_requeue. For reconciled_confirmed/reconciled_failed, return a clear success message reporting the reconciliation; for keep_in_hold, call mark_payment_manual_hold with the reason and return a non-success result.
Gateexecute_release_payment at tools.py:2392–2413 the same way — before release_payment_hold, reconcile; if on-chain state says confirmed/failed, refuse the release and return the reconciled truth instead.
Test in tests/test_admin_payments.py:
Fake provider returning 'confirmed' → retry refuses requeue, marks confirmed.
Fake provider returning 'failed' → retry refuses requeue, marks failed.
Fake provider returning 'not_found' with recent submitted_at → keep_in_hold.
Fake provider returning 'not_found' with old submitted_at → allow requeue.
Fake provider raising → keep_in_hold.
Step 5: New !payment-resolve <payment_id> admin-only command (src/features/payments/payment_cog.py or post-cleanup UI cog, src/features/admin_chat/tools.py)
Scope: Small
Add a slash command /payment-resolve (admin-only via @app_commands.checks.has_permissions(administrator=True) or ADMIN_USER_ID check) that accepts payment_id, calls payment_service.reconcile_with_chain from Step 4, writes an audit entry to tx_signature_history, and replies with the decision.
Also expose it as an admin_chat tool execute_payment_resolve that wraps the same service method, so the agent can trigger it from chat.
Append to tx_signature_history on every reconcile action with reason='admin_resolve'.
Test: call reconcile_with_chain against a fixture that mocks on-chain states and assert the audit entry is appended and the reply string matches each decision branch.
Step 6: Provider name migration path (src/features/payments/payment_service.py, src/common/db_handler.py)
Scope: Small
AddPaymentService.migrate_legacy_provider_rows(guild_ids) -> int that:
Queries payment_requests for rows with provider='solana' in writable guilds (new db_handler.get_legacy_provider_payment_requests).
For each row: producer='grants' → rewrite provider to solana_grants; producer='admin_chat' → solana_payouts; unknown → mark_payment_manual_hold with reason 'legacy provider could not be mapped: unknown producer={producer}'.
Log one logger.warning per row at INFO level with before/after for observability.
Call it once at worker startup from PaymentWorkerCog.cog_load (post-cleanup) or PaymentCog.cog_load (today).
Test: fake DB with three legacy rows (grants, admin_chat, unknown); assert correct rewrites and one manual_hold.
Phase C: Robustness edge cases
Step 7: Dynamic priority fees via getRecentPrioritizationFees (src/features/grants/solana_client.py)
Scope: Medium
AddSolanaClient._get_dynamic_priority_fee(client) -> int that calls client.get_recent_prioritization_fees() (or raw RPC if the SDK method doesn't exist — verify at implementation time), computes the 75th percentile of non-zero fees from the returned array, and returns clamp(percentile, floor=self.priority_fee_micro_lamports, ceiling=int(os.getenv('SOLANA_PRIORITY_FEE_CEILING_MICRO_LAMPORTS', '1000000'))).
On RPC error or empty response, fall back to self.priority_fee_micro_lamports (current static floor) and log at WARNING.
Call it inside send_sol at solana_client.py:94–98 to replace the static compute_unit_price = self.priority_fee_micro_lamports with the dynamic value; log the chosen value alongside the existing priority-fee log.
Test in tests/test_solana_client.py: mock get_recent_prioritization_fees; assert 75th percentile math, floor clamp, ceiling clamp, and fallback-on-error behavior.
AddADMIN_FALLBACK_CHANNEL_ID env read in __init__.
Refactor_dm_admin_payment_success (payment_cog.py:288–344) and _dm_admin_payment_failure (payment_cog.py:346–406) to share a helper _deliver_admin_alert(message: str):
Try DM to ADMIN_USER_ID.
On discord.Forbidden or discord.HTTPException rate-limit: post to ADMIN_FALLBACK_CHANNEL_ID via safe_send_message.
On both failing: logger.error('[PaymentCog] admin alert undeliverable', extra={'message_preview': ...}).
Test: fake bot where DM raises Forbidden; assert fallback channel send is called. Fake bot where both fail; assert ERROR log.
Step 9: RPC-down vs timeout distinction (src/features/payments/payment_service.py, src/features/payments/solana_provider.py)
Scope: Small
Add a new sentinel status 'rpc_unreachable' alongside 'timeout' in SolanaProvider.confirm_tx and .check_status. Return it only when the underlying RPC call raises a connection-error family exception (aiohttp.ClientConnectionError, asyncio.TimeoutError on the connect phase, solana.rpc.core.RPCException with a connection subtype — verify exact types at impl time).
UpdatePaymentService._confirm_submitted_payment (line 548+) to branch on 'rpc_unreachable': mark_payment_manual_hold with reason 'rpc_unreachable: confirmation RPC offline' — distinct from the existing 'Confirmation timed out after submission' message.
Do the same in PaymentService.recover_inflight (line 458+) for the submitted branch.
Step 10: Verify recover_inflight vs worker-loop race (sql/payments.sql, tests/test_payment_race.py new)
Scope: Medium — investigation first
Readclaim_due_payment_requests at sql/payments.sql:166–198. The RPC filters status = 'queued' (line 178), which means it cannot claim a processing or submitted row. recover_inflight only touches processing/submitted rows. Initial hypothesis: these cannot collide. Verify this is true under the worker-loop's execute_payment transition from processing → submitted → confirmed:
Worker claims a queued row and transitions it to processing inside the RPC (line 188).
While the worker is mid-send, restart happens.
New process recover_inflight sees the row in processing and moves it to manual_hold or failed+queued.
Meanwhile, the worker that survived (or a second worker) might also be writing to the same row.
Writetests/test_payment_race.py::test_recover_inflight_race using a fake DB handler that tracks call order to mark_payment_*: simulate execute_payment mid-flight and recover_inflight running simultaneously; assert the row ends in a consistent terminal state (no double-mark_payment_confirmed, no processing→confirmed-from-stale-read).
Deliverable: a written verdict comment at the top of the test file (# VERDICT 2026-04-11: proven safe by this test or # VERDICT: gremlin found — fixed in Step N). If a race is discovered, add a fix: e.g., wrap recover_inflight in a conditional update that requires status IN ('processing','submitted') AND updated_at < now() - interval '2 minutes' to avoid stealing a row a live worker is actively handling.
Reproduce: write a test where two calls to execute_initiate_payment with the same (guild_id, recipient_user_id) within the same wall-clock second both compute the same producer_ref at tools.py:2486. Run both through PaymentService.request_payment.
Analyze the existing collision logic at payment_service.py:99–122: if both requests are the same wallet, idempotent return hands back the same row — not a double-send. If the two admin requests are for different amounts to the same wallet in the same second, the second request silently gets the first request's row. This may be a gremlin — two different amounts collapse to one.
Deliverable: If the test confirms the collision collapses two distinct amounts, either:
Fix option A: change producer_ref to include microsecond precision: f"{guild_id}_{recipient_user_id}_{int(time.time() * 1000)}". Cheapest fix, matches current semantics.
Fix option B: include a random UUID suffix: f"{guild_id}_{recipient_user_id}_{uuid4().hex[:8]}" — strongest, breaks all idempotency on this path (which is acceptable because admin-initiated payments aren't meant to be retried via idempotency).
Prefer Option A unless the test shows millisecond collisions are plausible. Commit the chosen fix and a regression test.
Step 12: Property-based tests with hypothesis (tests/test_payment_state_machine.py new, requirements.txt)
Scope: Medium
Addhypothesis to requirements.txt.
Writetests/test_payment_state_machine.py that uses hypothesis.stateful.RuleBasedStateMachine with a fake DatabaseHandler backing store. Rules: create_payment, confirm_payment, execute_payment, recover_inflight, release_payment_hold, requeue_payment.
Invariants (checked after every rule):
Every status='confirmed' row has tx_signature (non-null) AND the fake provider's check_status returns 'confirmed' for it.
No transition from a terminal state (confirmed, cancelled) back to queued/processing/submitted.
sum(amount_usd for status='confirmed' in last 24h for capped provider) <= daily_usd_cap + per_payment_usd_cap (allowing one-in-flight slack).
is_test rows never populate amount_usd or token_price_usd.
Fail-closed: if execute_payment returns early because a provider raised, the row is never left in processing without a manual_hold reason.
Runpytest tests/test_payment_state_machine.py --hypothesis-show-statistics to get output.
Deliverable: the test suite passing, or the gremlin caught and fixed with the offending rule-sequence recorded in the test.
State machine: ASCII diagram covering pending_confirmation → queued → processing → submitted → {confirmed, failed, manual_hold, cancelled}. Include arrows for failed → queued (requeue) and manual_hold → failed.
Authorization model: table of PaymentActorKind × producer with who can confirm what (read from producer_flows.py:16–30). Note that AUTO is the test-payment confirmer and RECIPIENT_CLICK/RECIPIENT_MESSAGE/ADMIN_DM are real-payment confirmers, gated by producer.
Cap enforcement: per_payment_usd_cap + daily_usd_cap + capped_providers with file:line to payment_service.py:192–223.
Fail-closed contract: enumerated invariants with file:line pointers.
Non-obvious constraints: rent-exempt test amount minimum (0.002 SOL), static+dynamic priority fees (post-Phase C), two-wallet split (solana_grants vs solana_payouts), idempotency index excludes failed/cancelled.
Length target: ≤400 lines; readable in ≤15 minutes.
Portaudit_ghost_confirmed_payments.py as a superset. Add checks:
(a) Every status='confirmed' solana row has tx_signature AND on-chain getSignatureStatuses returns err=null.
(b) No row has been in pending_confirmation or processing for more than 24 hours (updated_at < now() - interval '24 hours').
(c) Every wallet_registry row with verified_at has a corresponding confirmedis_test=true payment with amount_token >= 0.001 SOL.
(d) No two wallet_registry rows share the same wallet_address across different discord_user_id (detect address reuse).
(e) Daily cap aggregate: sum(amount_usd) where status='confirmed' and provider='solana_payouts' and completed_at > now() - interval '24 hours' compared against ADMIN_PAYOUT_DAILY_USD_CAP — flag if ≥90% (warning) or ≥100% (error).
Exit nonzero on any violation. Print a structured report to stdout.
Add a GitHub Actions workflow or README note wiring this into daily CI (see Question 4). For now, the script itself is sufficient; the scheduling wire-up is info-priority.
Test: a synthetic-violation fixture — a seeded test DB with one row violating each invariant, asserting each violation is reported.
Also log on the error branches (lines 163–172) with decision='not_found' / decision='errored' and the full err repr.
Test: patch logger and assert the extra dict contains 'event': 'tx_confirm_decision'.
Execution Order
Preflight (before any changes): confirm cleanup megaplan has landed on main by checking for the split worker/UI cogs and PaymentActor usage in the worker path. If not yet landed, pause Phase A until it is. Phases B/C/D/E/F can start regardless.
Phase B first (B4 → B5 → B6) — highest-value correctness (closes the retry double-send hole).
Phase A (A1 → A2 → A3) — behavior-preserving refactor is safer once B has added its tests.
Phase C (C7 → C8 → C9) — parallelizable after B lands.
Phase D (D10 → D11 → D12) — investigation; fixes feed back into B/C if found.
Phase E (E13 → E14) — docs finalize once code shape is stable.
Phase F (F15 → F16) — monitoring over the settled state.
Validation Order
Per-step: run pytest tests/test_admin_payments.py tests/test_solana_client.py after each code change.
Phase B complete: targeted pytest tests/test_admin_payments.py -k "retry or release or resolve or migration".
Phase A complete: full pytest to verify refactor didn't break anything.
Phase D complete: pytest tests/test_payment_race.py tests/test_payment_state_machine.py + hypothesis statistics banner.
Phase F complete: run python scripts/check_payment_invariants.py against a local test DB (and against prod read-replica if available, with user approval) and confirm it fails on synthetic violations and passes on a clean DB.
Final: full pytest suite green + manual smoke of /payment-resolve in a dev guild.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-10T22:25:28Z",
"hash": "sha256:7a067b48c7d266fe107f7c19889692110594f1f0a153ffdf9bde0fe8801c5fb4",
"questions": [
"The idea text references 'solana_client.py' for items C7 (dynamic priority fees) and F16 (structured confirm logging). There is no file at src/features/payments/solana_client.py \u2014 the relevant file is src/features/grants/solana_client.py (the shared SolanaClient class used by both grants and payouts providers). The plan targets src/features/grants/solana_client.py. Is that the right target, or did you intend to create a new solana_client.py inside src/features/payments/?",
"A3 (consolidate _redact_wallet): should the shared helper live in src/common/discord_utils.py, or in a new src/common/redaction.py module? discord_utils.py has the right import graph but is Discord-specific; the redaction helper itself is chain-agnostic. My default is discord_utils.py (minimal churn) unless you prefer a new module.",
"A3: admin_chat/tools.py has a separate _redact_wallet_address helper with a different signature (accepts Any, not just Optional[str]) and additional _redact_wallet_row/_redact_payment_row wrappers. Should this pass also unify those, or leave them as a separate follow-up? My default is to leave them alone (they are distinct behavior).",
"F15 asks for the invariant checker to run 'daily via CI or cron'. This repo uses Railway \u2014 should I add a scripts/ cron entry, a GitHub Actions workflow, or just ship the script and leave wiring as an operator task? My default is to ship the script plus a README note in docs/runbook-payments.md and leave the scheduler wire-up as an info-priority follow-up.",
"D10 investigation: if the race between recover_inflight and the worker loop turns out to be real, my default fix is a conditional update that only reclaims processing/submitted rows older than 2 minutes. Is 2 minutes acceptable, or is there a tighter bound you want (e.g. matching worker tick interval)? If you want a different mechanism entirely (e.g., a generation counter on the row), tell me and I'll plan for that.",
"D11: the preferred fix for same-second admin collision is millisecond precision in producer_ref (Option A). Acceptable, or do you want full randomness (Option B with uuid suffix) to permanently break idempotency on this path?",
"B4: my heuristic for 'blockhash expired' in the reconcile_with_chain method is 'submitted_at older than 150 seconds'. Solana's blockhash lifetime is ~60\u201390 seconds; 150 is a safety margin. Is that margin acceptable, or do you want a real getLatestBlockhash-based check (more RPC calls but authoritative)?"
],
"success_criteria": [
{
"criterion": "All 14 polish items from the idea are either implemented or explicitly deferred with a written justification in the plan artifact.",
"priority": "must"
},
{
"criterion": "A1: PaymentService.request_payment is decomposed into the 5 named helpers; public signature and return values unchanged; all existing tests pass without modification.",
"priority": "must"
},
{
"criterion": "A2: PaymentService.init raises ValueError when test_payment_amount is below 2_000_000 lamports; duplicate guard removed from main.py; new unit test covers this.",
"priority": "must"
},
{
"criterion": "A3: _redact_wallet is defined exactly once in src/common/ and imported by payment_service.py, payment_cog.py (or post-cleanup worker cog), and db_handler.py.",
"priority": "must"
},
{
"criterion": "B4: execute_retry_payment and execute_release_payment call reconcile_with_chain before mutating state; the four decision branches (reconciled_confirmed, reconciled_failed, allow_requeue, keep_in_hold) are each covered by a unit test.",
"priority": "must"
},
{
"criterion": "B5: /payment-resolve slash command (admin-only) and admin_chat execute_payment_resolve tool both exist, call reconcile_with_chain, and append to tx_signature_history.",
"priority": "must"
},
{
"criterion": "B6: Worker startup migrates legacy provider='solana' rows to solana_grants or solana_payouts; unknown producers go to manual_hold; unit test covers all three branches.",
"priority": "must"
},
{
"criterion": "C7: SolanaClient.send_sol uses a dynamic priority fee (75th percentile of recent fees) clamped to [floor, ceiling] with fallback-on-error; unit test covers percentile math, clamps, and fallback.",
"priority": "must"
},
{
"criterion": "C8: Admin DM failure falls back to ADMIN_FALLBACK_CHANNEL_ID; both-failed path logs at ERROR level; unit test covers Forbidden and double-failure paths.",
"priority": "must"
},
{
"criterion": "C9: A distinct 'rpc_unreachable' manual_hold reason is emitted when the confirmation RPC is unreachable (as opposed to a legitimate confirmation timeout); unit test covers the distinction.",
"priority": "must"
},
{
"criterion": "D10: tests/test_payment_race.py exists and passes; a written verdict ('proven safe' or 'fixed with commit N') is recorded as a file-level comment.",
"priority": "must"
},
{
"criterion": "D11: A regression test reproduces or refutes the same-second admin collision; if reproduced, producer_ref precision is upgraded and the test becomes a regression guard.",
"priority": "must"
},
{
"criterion": "D12: tests/test_payment_state_machine.py uses hypothesis RuleBasedStateMachine; hypothesis is added to requirements.txt; all five invariants are asserted.",
"priority": "must"
},
{
"criterion": "docs/payments.md and docs/runbook-payments.md are committed with the specified sections.",
"priority": "must"
},
{
"criterion": "scripts/check_payment_invariants.py exists, implements all five checks (a\u2013e), exits nonzero on any violation, and has a fixture-based test for synthetic violations.",
"priority": "must"
},
{
"criterion": "F16: SolanaClient.confirm_tx emits a structured log with event='tx_confirm_decision' on all three decision branches (confirmed, not_found, errored).",
"priority": "must"
},
{
"criterion": "Full pytest suite passes after every phase lands.",
"priority": "must"
},
{
"criterion": "No regression in existing grants or admin_chat payment flows (verified via tests/test_admin_payments.py and tests/test_solana_client.py).",
"priority": "must"
},
{
"criterion": "Phase A refactor does not introduce any behavior change \u2014 same inputs produce same outputs and same log messages.",
"priority": "should"
},
{
"criterion": "docs/payments.md readable by a new engineer in under 15 minutes (target \u2264400 lines).",
"priority": "should"
},
{
"criterion": "docs/runbook-payments.md covers every non-happy-path scenario listed in the idea.",
"priority": "should"
},
{
"criterion": "scripts/check_payment_invariants.py runs successfully against prod DB (or a production-like snapshot) and reports no false positives on a healthy dataset.",
"priority": "info"
},
{
"criterion": "After this pass, an operator can sleep at night with real money in the wallets \u2014 subjective, operator-reported confidence.",
"priority": "info"
},
{
"criterion": "Daily CI or cron wire-up for check_payment_invariants.py is in place (deferred to operator as a follow-up per Question 4).",
"priority": "info"
}
],
"assumptions": [
"The cleanup megaplan (payment-subsystem-follow-up-20260410-2339) will have landed before Phase A starts, producing PaymentWorkerCog + PaymentUICog split and the PaymentActor-based confirm_payment signature. If cleanup has not landed when this plan executes, Phase A is paused until it has.",
"The admin-DM approval megaplan will have landed before Phase D (specifically D12) runs, so the hypothesis state machine sees the final set of PaymentActorKind values including ADMIN_DM.",
"The idea's reference to 'solana_client.py' in items C7 and F16 means src/features/grants/solana_client.py (the shared SolanaClient), not a new file inside src/features/payments/. The SolanaClient is the thing that actually calls the RPC.",
"_redact_wallet consolidation lands in src/common/discord_utils.py (smallest graph change) unless the user requests a dedicated redaction module.",
"B4 blockhash-expiry heuristic uses a 150-second submitted_at age as a safe approximation of Solana's ~90s blockhash lifetime, avoiding an extra getLatestBlockhash RPC call per reconcile. If the user wants an authoritative check, swap in Question 7's alternative.",
"D11 fix defaults to millisecond-precision producer_ref (Option A) rather than a random UUID suffix (Option B); cheapest fix and preserves idempotency for legitimate retries.",
"scripts/check_payment_invariants.py is shipped as a standalone script; daily scheduling wire-up (cron, GitHub Actions, Railway scheduled job) is deferred to the operator as an info-priority follow-up.",
"Property-based tests use hypothesis's RuleBasedStateMachine against a fake DB handler, not a live Supabase instance \u2014 so the test suite remains hermetic and fast.",
"admin_chat/tools.py's separate _redact_wallet_address helper is out of scope for the A3 consolidation because it has a different signature and wrapper semantics.",
"F16's structured log uses Python's standard logging 'extra' dict; downstream log aggregation (if any) will pick up the event key without further wiring \u2014 if the bot's log handler strips 'extra', a follow-up is needed but is out of scope here.",
"D10's fix-if-gremlin-found is a conditional update restricting recover_inflight to rows with updated_at older than 2 minutes, not a generation counter or schema change. If a more invasive fix is required, it becomes a follow-up."
],
"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"
]
}
],
"payment-service-confirmation": [
{
"id": "DEBT-007",
"concern": "success criterion bundles null-recipient dm wiring with cap-breach/collision dm wiring; step 1 only does log+return-none for null-recipient.",
"occurrence_count": 1,
"plan_ids": [
"harden-the-solana-payment-20260410-2147"
]
}
],
"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/final-polish-and-gremlin-20260411-0020/critique_output.json
Review the plan with a broad scope. Consider whether the approach is correct, whether it covers
all the places it needs to, whether it would break callers or violate codebase conventions,
and whether its verification strategy is adequate.
Place any concrete concerns in the flags array in the template file using the standard format
(id, concern, category, severity_hint, evidence). Leave checks as an empty array.
Workflow: read the file → investigate → read file again → add findings → write file back.
code
Additional guidelines:
- Robustness level: light. Be pragmatic. Only flag issues that would cause real failures. Ignore style, minor edge cases, and issues the executor will naturally resolve.
- 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":[],"flags":[{"id":"FLAG-001","concern":"Payment reconciliation: B4/B5 cannot actually reconcile failed/manual_hold rows with the current DB transition guards.","category":"correctness","severity_hint":"likely-significant","evidence":"The plan's reconcile_with_chain flow calls mark_payment_confirmed / mark_payment_failed for rows reached from retry/release/manual-hold paths, but db_handler only allows mark_payment_confirmed from submitted and mark_payment_failed from processing/submitted (src/common/db_handler.py, src/common/db_handler.py). retry_payment and release_payment operate on failed/manual_hold rows (src/features/admin_chat/tools.py, src/features/admin_chat/tools.py), so the proposed 'reconciled_confirmed' / 'reconciled_failed' branches will no-op unless the plan also adds explicit DB transitions for those starting states."},{"id":"FLAG-002","concern":"Admin chat payment tools: B4/B5 under-specify the plumbing needed for retry/release/resolve to reach PaymentService.","category":"completeness","severity_hint":"likely-significant","evidence":"Today execute_retry_payment and execute_release_payment only accept db_handler and call straight DB mutations (src/features/admin_chat/tools.py, src/features/admin_chat/tools.py). The dispatcher also passes only db_handler for those tool names (src/features/admin_chat/tools.py). The plan says these tool paths will call payment_service.reconcile_with_chain, but it does not include the required signature/dispatcher changes or equivalent access path to bot.payment_service, so the operator-facing tool route is incomplete as written."},{"id":"FLAG-003","concern":"Admin-chat idempotency: D11's proposed reproduction path targets the wrong layer and can falsely 'prove safe.'","category":"correctness","severity_hint":"likely-significant","evidence":"The plan says to reproduce the collision with two calls to execute_initiate_payment and then run both through PaymentService.request_payment. In the actual repo, execute_initiate_payment stops at creating an admin_payment_intent and dedupes per (guild_id, source_channel_id, recipient_user_id) before producer_ref is even used (src/features/admin_chat/tools.py, src/features/admin_chat/tools.py). PaymentService.request_payment happens later in AdminChatCog._start_admin_payment_flow and handle_payment_result when test/final payment rows are created from the intent's stored producer_ref (src/features/admin_chat/admin_chat_cog.py, src/features/admin_chat/admin_chat_cog.py). A same-channel initiate test will be absorbed by intent dedupe and miss the real collision surface; the investigation needs to exercise distinct channels or the downstream payment-creation stage."}],"verified_flag_ids":[],"disputed_flag_ids":[]}