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
Prepared the engineering brief after investigating the existing grants payout flow, the Solana client, the DB helpers, the admin surfaces, and the existing social-publication queue pattern.
### Key Evidence
- Current grant payouts are still executed inline from `GrantsCog` and use mutable `grant_applications` status fields instead of a reusable ledger. (source: src/features/grants/grants_cog.py; relevance: high)
The repo already contains an atomic queue/worker pattern with FOR UPDATE SKIP LOCKED via social_publications, which is the strongest template for the new payment subsystem. (source: sql/social_publications.sql; src/common/db_handler.py; src/features/sharing/sharing_cog.py; relevance: high)
Admin chat currently exposes grant_applications through generic query_table, so any new secret-bearing payment/wallet tables must be kept off that surface or explicitly redacted. (source: src/features/admin_chat/tools.py; relevance: high)
code
### Relevant Code
| File | Functions | Why |
| --- | --- | --- |
| /Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc/.megaplan/plans/build-a-fail-closed-20260409-2327/prep.json | - | Final brief written here. |
code
User
Assistant
I’m re-running the critique against the revised plan now. First I’m reopening the critique template and rechecking the repo points that the plan claims to have fixed, then I’ll update the findings and verified flag list.
Assistant
I’ve isolated the first-pass fixes from the revised plan. I’m checking two likely remaining gaps now: whether “route-configured” actually became a real config lookup instead of hardcoded thread IDs, and whether the new payment state-machine contracts are internally consistent.
Assistant
I’ve finished the comparison. The revised plan clearly fixes most of the first-pass structural issues, but there are still a few concrete gaps: the route-config story is still not a real config lookup, the payment failure contract is internally inconsistent, and verification is still mostly service-level rather than end-to-end.
Assistant
Updated critique_output.json.
I marked 17 prior flags as verified and left 6 concerns open. The remaining material gaps are: the plan still does not define a real route-configuration source for payment destinations, the revised payment failure API is internally inconsistent (mark_payment_failed precondition vs later calls), the test-payment amount semantics still drift between “fixed dust” and USD, and verification is still mostly service-level rather than end-to-end.
Validation: JSON parses successfully.
User
Assistant
I’m reviewing the third revision against the repo now. First I’m reopening the critique template and checking the specific items the plan says it fixed: route resolution, the cross-cog handoff pattern, and the remaining verification gaps.
Assistant
The third revision fixes the substantive design issues from the first two rounds. What’s left is almost entirely verification risk: the plan is now aligned with the repo’s routing and cross-cog patterns, but it still relies too heavily on one service-level test file plus manual smoke checks for the Discord/persistent-view pieces.
Assistant
Updated critique_output.json.
This revision closes the substantive design gaps from the earlier rounds. I verified the routing, fixed-SOL test payment, corrected state-machine contract, and repo-native bot.get_cog() handoff. The only concerns I left open are verification-related: there is still no automated coverage for route resolution / route CRUD / grants integration, and persistent-view restart behavior is still only covered by manual smoke testing.
Validation: JSON parses successfully.
### Test Expectations
- [pass_to_pass] prep.json: Brief file exists and is valid JSON.
### Constraints
- The requested output had to be written to the specified megaplan prep path.
The brief needed investigation because the task spans multiple subsystems and files.
code
### Suggested Approach
Use the written prep brief as the planning context for the next step.
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:
Build a fail-closed generalized payment subsystem for ArcCompute-style payouts on Solana. Replace direct grant sends with a reusable payment ledger, provider abstraction, wallet registry, Discord confirmation flow, manual hold/retry controls, and restart-safe recovery. Critical requirements: no automatic double-payment after tx submission unless chain definitively reports failure; ambiguous chain state freezes to manual hold; private keys never enter DB/logs/admin-chat; atomic worker claiming; separate test-payment and final-payment attempts; grants becomes a producer into the payment system.
User notes and answers:
Locked decisions from user: test payment is a fixed tiny global amount; confirmation destination is route-configured and may be the source thread/forum post or a specific payments channel/forum; manual admin controls for retry/hold/release/cancel/status are required; do not auto-fallback from Codex to Claude on backend connection failures.
The bot currently processes Solana grant payouts inline inside GrantsCog._process_payment(), with payment state baked into grant_applications columns (payment_status, wallet_address, tx_signature, etc.). This works but is non-reusable, tightly coupled, and has limited admin controls.
The goal is a standalone payment subsystem modeled on the existing social_publications queue pattern: a ledger table, atomic worker claiming via FOR UPDATE SKIP LOCKED, a provider abstraction layer, Discord confirmation flow, manual hold/retry admin controls, and restart-safe recovery. Grants becomes just a producer that enqueues payment requests.
Critical safety invariant: After a transaction is submitted to the chain, it is never automatically retried unless the chain definitively reports failed. Unknown/ambiguous status (not_found) freezes the payment to manual_hold — an admin must resolve it. Private keys never touch DB, logs, or admin chat.
Repo patterns to follow:
sql/social_publications.sql — schema + claim_due_* RPC function template
src/features/sharing/sharing_cog.py — @tasks.loop worker, claim → process → mark
src/features/sharing/social_publish_service.py — service layer between producer and queue
src/common/db_handler.py — Supabase client wrappers with _gate_check()
Createsql/payments.sql with two tables and one RPC function:
payment_requests table — the ledger:
payment_id UUID PK (gen_random_uuid)
guild_id bigint NOT NULL
producer text NOT NULL — e.g. 'grants', future: 'bounties', 'arccompute'
producer_ref text NOT NULL — e.g. grant thread_id, links back to source
recipient_wallet text NOT NULL — Solana address
amount_usd numeric NOT NULL
amount_token numeric — computed SOL amount at send time
token_price_usd numeric — spot price at send time
chain text NOT NULL DEFAULT 'solana' — future extensibility
provider text NOT NULL DEFAULT 'solana_native'
status text NOT NULL DEFAULT 'pending_confirmation' CHECK in ('pending_confirmation', 'queued', 'processing', 'submitted', 'confirmed', 'failed', 'manual_hold', 'cancelled')
is_test boolean NOT NULL DEFAULT false — distinguishes test-payment from final
attempt_count integer NOT NULL DEFAULT 0
tx_signature text — set after chain submission
last_error text
retry_after timestamptz
hold_reason text — human note when in manual_hold
confirmed_by text — Discord user ID who confirmed (or 'auto')
created_at, updated_at, completed_at timestamptz
deleted_at timestamptz — soft delete
Key indexes:
idx_payment_requests_due_queue on (retry_after, created_at) WHERE status = 'queued' AND deleted_at IS NULL
idx_payment_requests_producer on (producer, producer_ref)
Unique partial index on (producer, producer_ref, is_test) WHERE status NOT IN ('failed', 'cancelled') — prevents double-enqueue of active payments
Mirrors claim_due_social_publications exactly — CTE with FOR UPDATE SKIP LOCKED, atomically sets status = 'processing', increments attempt_count
Note: No wallet registry table in v1. Recipient wallets are just text on each payment request. A registry (mapping Discord users → verified wallets) can be added later when there are multiple producers that share recipients. For now, grants already collects wallets inline.
Security:payment_requests gets RLS enabled, anon/authenticated revoked (same pattern as social_publications). The table is not added to QUERYABLE_TABLES in admin chat — step 7 adds a dedicated redacted admin tool instead.
Step 2: Add DB handler methods (src/common/db_handler.py)
Scope: Medium
Add methods mirroring the social publications pattern:
create_payment_request(record, guild_id) — insert with _gate_check()
get_payment_request(payment_id) — fetch single
get_payment_requests_by_producer(producer, producer_ref) — fetch by source
claim_due_payment_requests(limit, guild_ids) — RPC call to claim function
mark_payment_submitted(payment_id, tx_signature, amount_token, token_price_usd, guild_id) — set status='submitted', store tx sig
mark_payment_confirmed(payment_id, guild_id) — set status='confirmed', completed_at
mark_payment_failed(payment_id, error, guild_id) — set status='failed', completed_at
mark_payment_manual_hold(payment_id, reason, guild_id) — set status='manual_hold', hold_reason
requeue_payment(payment_id, retry_after, guild_id) — set status='queued', retry_after
cancel_payment(payment_id, guild_id) — set status='cancelled'
get_inflight_payments_for_recovery() — fetch status IN ('processing', 'submitted') for restart recovery
Pattern: Each method follows existing db_handler conventions — Supabase client calls, guild_id scoping, error logging, return dict or None.
KeepSolanaClient unchanged — it still works, the provider is a thin adapter.
Key: The provider holds the SolanaClient instance in memory. The keypair never leaves the SolanaClient object. No serialization, no DB storage, no logging of key material.
Step 5: Create payment service (src/features/payments/payment_service.py)
Scope: Medium
CreatePaymentService class — the core orchestrator between producers and the worker.
Constructor takes db_handler and a dict of {provider_name: PaymentProvider}.
CreatePaymentCog(commands.Cog) following sharing_cog.py pattern:
@tasks.loop(seconds=30) worker that calls db_handler.claim_due_payment_requests() then processes each via payment_service.execute_payment().
On startup (cog_load): call payment_service.recover_inflight().
Configurable via env: PAYMENT_CLAIM_LIMIT (default 5), PAYMENT_WORKER_INTERVAL (default 30s).
Discord confirmation flow — when a producer calls payment_service.request_payment(), it gets back a payment record in pending_confirmation status. The producer (e.g. grants cog) sends a Discord message with a confirm button. The button handler calls payment_service.confirm_payment() to queue it.
For test payments (is_test=True): auto-confirm, no button needed. This lets grants do a dry-run to validate wallet + amount before the real payment.
For final payments: require explicit Discord confirmation from the applicant or admin.
Result notifications: After execute_payment() completes, the worker sends a DM or thread message with tx status + explorer link. On manual_hold, it pings the admin mention.
Add new admin chat tools (do NOT add payment_requests to QUERYABLE_TABLES):
query_payments — dedicated tool that returns payment records with tx_signature visible but wallet addresses partially redacted (show first 4 + last 4 chars). Never returns any key material (there is none in DB, but defense in depth).
hold_payment — sets a payment to manual_hold with a reason string.
retry_payment — requeues a failed or manual_hold payment (sets status='queued', clears tx_signature, increments attempt). Only works if current status is failed or manual_hold — cannot retry submitted (that would risk double-pay).
cancel_payment — sets status='cancelled'. Only from pending_confirmation, queued, failed, or manual_hold.
Add tool definitions to TOOLS list and handler functions.
Key safety: The retry_payment tool clears tx_signature before requeue so the worker treats it as a fresh attempt. A payment in submitted state cannot be retried — admin must first resolve to failed or manual_hold via chain check.
Phase 4: Grants Producer Integration
Step 8: Refactor grants to produce payment requests (src/features/grants/grants_cog.py)
Scope: Medium
Replace_process_payment() (lines 678-779) with a call to payment_service.request_payment():
Send Discord confirmation message with payment details + confirm button.
On confirm callback: payment_service.confirm_payment(payment_id, confirmed_by=user_id).
Replace_recover_inflight_payments() (lines 87-193) — this is now handled by PaymentCog.cog_load → payment_service.recover_inflight(). Remove the grants-specific recovery code entirely.
Updategrant_applications status flow:
Remove payment_status, wallet_address, sol_amount, sol_price_usd, tx_signature columns from grant usage (they can stay in the table for historical data but new payments go through payment_requests).
Grant statuses simplify to: reviewing → needs_info/needs_review/rejected/spam → approved → awaiting_wallet → payment_requested → paid.
payment_requested: set when payment_service.request_payment() succeeds. Store payment_id in a new payment_ref column on grant_applications.
paid: set when payment_cog notifies grants (via callback or event) that payment is confirmed.
Wire notification: payment_cog emits a Discord event or calls a callback when a payment reaches terminal state. Grants listens and updates its status + sends the thread message.
Test payment flow: When grant is approved and wallet submitted, first enqueue a test payment (is_test=True, amount = 0 or minimal dust amount like 0.000001 SOL). If test confirms, auto-enqueue the real payment with Discord confirmation. This validates the wallet is receivable before committing real funds.
Step 9: Register cog and wire startup (main.py)
Scope: Small
InstantiateSolanaProvider wrapping the existing SolanaClient.
InstantiatePaymentService with db_handler and {'solana_native': solana_provider}.
LoadPaymentCog with payment_service and db_handler.
UpdateGrantsCog constructor to accept payment_service instead of solana_client directly.
Phase 5: Tests & Validation
Step 10: Unit tests (tests/test_payment_service.py)
Scope: Medium
Createtests/test_payment_service.py with FakeSupabase pattern from existing tests/test_social_route_tools.py:
Test idempotent request_payment — calling twice with same producer+ref returns same record.
Test confirm_payment transitions from pending_confirmation → queued.
Test execute_payment ambiguous: provider.check_status() returns not_found → manual_hold (the critical fail-closed test).
Test execute_payment failure: provider.send() raises → failed.
Test recover_inflight with various stuck states.
Test admin controls: retry only from failed/manual_hold, cancel restrictions, no retry from submitted.
Test double-payment prevention: unique constraint prevents two active payments for same producer_ref.
Runpytest tests/test_payment_service.py -v.
Step 11: Integration smoke test
Scope: Small
Verify existing grant tests (if any) still pass — grants_cog changes should not break assessment/review flow.
Run full pytest suite to check for regressions.
Manual verification points (documented for human tester):
Deploy to staging, create a grant application, approve it, submit wallet, observe test-payment → confirmation → real-payment flow.
Kill bot mid-payment, restart, verify recovery picks up correctly.
Use admin chat hold_payment / retry_payment / cancel_payment tools.
Execution Order
Phase 1 first — DB schema is the foundation everything depends on.
Phase 2 next — provider abstraction and service layer, testable in isolation.
Phase 3 — worker cog and admin tools, depends on Phase 2.
Phase 4 — grants integration, depends on Phase 3.
Phase 5 throughout — write tests alongside each phase, run full suite at the end.
Validation Order
SQL migration is syntactically valid (can be reviewed, applied to staging).
Unit tests for payment_service pass (Phase 2 + Phase 5 step 10).
Admin tools respond correctly to various payment states.
Grants cog compiles and loads without errors.
Full pytest suite green.
Manual smoke test on staging (info-level, cannot automate).
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-09T21:35:22Z",
"hash": "sha256:9bed5b34d492af03515f5177ae15cc4b2a39faa2a402f30e654a562cf236b5b0",
"questions": [
"Should test payments send actual dust (e.g. 0.000001 SOL) to validate the wallet is receivable on-chain, or just validate the address format locally? Real dust costs a tx fee (~0.000005 SOL) per grant but gives true chain-level validation.",
"Is there a preference for how the Discord confirmation flow works \u2014 a button/reaction on the thread message, or a DM to the applicant? Currently grants collect the wallet inline in the forum thread.",
"Should the payment worker support multiple concurrent providers (e.g. future SPL token payouts, USDC on Solana), or is native SOL the only chain target for v1? This affects whether the provider dict is overkill vs. just right.",
"For the admin retry flow: should retry re-fetch the current SOL price (amount may differ from original) or use the originally quoted price? Re-fetching is safer for the org but the applicant sees a different amount.",
"Is there an existing Supabase migration workflow (e.g. a migrations directory, a CI step that applies SQL), or is sql/ just reference scripts applied manually?"
],
"success_criteria": [
{
"criterion": "payment_requests table exists with all specified columns, constraints, indexes, and RLS policies",
"priority": "must"
},
{
"criterion": "claim_due_payment_requests RPC uses FOR UPDATE SKIP LOCKED and atomically transitions status to processing",
"priority": "must"
},
{
"criterion": "After tx submission (status=submitted), ambiguous chain status (not_found) transitions to manual_hold \u2014 never auto-retry",
"priority": "must"
},
{
"criterion": "Only chain-definitive failure (status check returns 'failed') allows automatic transition to failed state",
"priority": "must"
},
{
"criterion": "Private keys never appear in DB columns, log messages, or admin chat tool responses",
"priority": "must"
},
{
"criterion": "payment_requests table is NOT in QUERYABLE_TABLES; dedicated query_payments tool redacts wallet addresses",
"priority": "must"
},
{
"criterion": "Admin retry_payment only works from failed or manual_hold states \u2014 submitted state is blocked",
"priority": "must"
},
{
"criterion": "Unique partial index prevents two active (non-failed, non-cancelled) payments for the same producer + producer_ref + is_test combination",
"priority": "must"
},
{
"criterion": "On bot restart, recover_inflight correctly resolves processing (no tx_sig \u2192 requeue) and submitted (check chain \u2192 confirm/fail/hold) states",
"priority": "must"
},
{
"criterion": "Grants cog produces payment requests instead of calling solana_client directly; grant status flow updated accordingly",
"priority": "must"
},
{
"criterion": "All new unit tests pass (pytest tests/test_payment_service.py)",
"priority": "must"
},
{
"criterion": "Full pytest suite passes with no regressions",
"priority": "must"
},
{
"criterion": "PaymentProvider ABC is minimal \u2014 only send, check_status, get_token_price_usd, token_name methods",
"priority": "should"
},
{
"criterion": "Worker loop follows sharing_cog pattern: @tasks.loop, claim batch, sequential process, env-configurable interval and batch size",
"priority": "should"
},
{
"criterion": "New files stay under ~300 lines each; payment_service.py may be up to ~400 given the state machine complexity",
"priority": "should"
},
{
"criterion": "Test and final payment flows are distinct: is_test flag on payment_requests, test payments can auto-confirm",
"priority": "should"
},
{
"criterion": "Discord confirmation uses button interaction (not just message reply) for better UX",
"priority": "should"
},
{
"criterion": "Manual staging smoke test: full grant \u2192 test-payment \u2192 confirm \u2192 final-payment \u2192 confirmed flow",
"priority": "info"
},
{
"criterion": "Manual staging test: kill bot mid-payment, restart, verify recovery",
"priority": "info"
}
],
"assumptions": [
"v1 targets native SOL transfers only \u2014 SPL token support (USDC etc.) is a future extension, but the provider abstraction accommodates it without code changes.",
"No separate wallet_registry table in v1. Recipient wallets are stored per-payment. A shared wallet registry can be layered on later when multiple producers need it.",
"The existing SolanaClient class remains unchanged; SolanaProvider is a thin adapter wrapping it.",
"grant_applications columns (payment_status, wallet_address, tx_signature, sol_amount, sol_price_usd) are left in the table for historical records but new payments flow through payment_requests exclusively.",
"SQL migrations are applied manually to Supabase \u2014 there is no automated migration runner in CI.",
"The Discord confirmation flow uses the existing forum thread (where the grant lives) rather than DMs \u2014 consistent with current UX where wallet submission happens in-thread.",
"Test payments send real dust (0.000001 SOL) on-chain to validate the wallet, not just local format checks \u2014 the cost is trivial and the assurance is high.",
"The payment worker runs in the same bot process as the sharing worker \u2014 no separate deployment.",
"Admin chat tools follow the existing Anthropic tool-call format used by other tools in tools.py."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{
"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/build-a-fail-closed-20260409-2327/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.
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.
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
Prepared the engineering brief after investigating the existing grants payout flow, the Solana client, the DB helpers, the admin surfaces, and the existing social-publication queue pattern.
### Key Evidence
- Current grant payouts are still executed inline from `GrantsCog` and use mutable `grant_applications` status fields instead of a reusable ledger. (source: src/features/grants/grants_cog.py; relevance: high)
The repo already contains an atomic queue/worker pattern with FOR UPDATE SKIP LOCKED via social_publications, which is the strongest template for the new payment subsystem. (source: sql/social_publications.sql; src/common/db_handler.py; src/features/sharing/sharing_cog.py; relevance: high)
Admin chat currently exposes grant_applications through generic query_table, so any new secret-bearing payment/wallet tables must be kept off that surface or explicitly redacted. (source: src/features/admin_chat/tools.py; relevance: high)
code
### Relevant Code
| File | Functions | Why |
| --- | --- | --- |
| /Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc/.megaplan/plans/build-a-fail-closed-20260409-2327/prep.json | - | Final brief written here. |
code
### Test Expectations
- [pass_to_pass] prep.json: Brief file exists and is valid JSON.
### Constraints
- The requested output had to be written to the specified megaplan prep path.
The brief needed investigation because the task spans multiple subsystems and files.
code
### Suggested Approach
Use the written prep brief as the planning context for the next step.
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:
Build a fail-closed generalized payment subsystem for ArcCompute-style payouts on Solana. Replace direct grant sends with a reusable payment ledger, provider abstraction, wallet registry, Discord confirmation flow, manual hold/retry controls, and restart-safe recovery. Critical requirements: no automatic double-payment after tx submission unless chain definitively reports failure; ambiguous chain state freezes to manual hold; private keys never enter DB/logs/admin-chat; atomic worker claiming; separate test-payment and final-payment attempts; grants becomes a producer into the payment system.
User notes and answers:
Locked decisions from user: test payment is a fixed tiny global amount; confirmation destination is route-configured and may be the source thread/forum post or a specific payments channel/forum; manual admin controls for retry/hold/release/cancel/status are required; do not auto-fallback from Codex to Claude on backend connection failures.
The bot currently processes Solana grant payouts inline inside GrantsCog._process_payment() (src/features/grants/grants_cog.py:678-779), with payment state baked into grant_applications columns. This works but is non-reusable, tightly coupled, and has limited admin controls.
The goal is a standalone payment subsystem modeled on the existing social_publications queue pattern (sql/social_publications.sql): a payment ledger table, wallet registry, atomic worker claiming via FOR UPDATE SKIP LOCKED, a provider abstraction layer, Discord confirmation flow with restart-safe persistent views, manual admin controls (hold/release/retry/cancel/status), and restart-safe recovery. Grants becomes just a producer that enqueues payment requests.
Critical safety invariant: After a transaction is submitted to the chain, it is never automatically retried. The provider contract distinguishes pre-submit failures (safe to mark failed) from post-submit ambiguity (must freeze to manual_hold). Unknown/ambiguous status requires admin resolution via release_payment before retry is allowed. Private keys never touch DB, logs, or admin chat.
Key design decisions (locked by user):
Test payment amount: fixed tiny global amount (not per-grant)
Confirmation destination: route-configured per payment request (stored in ledger), not hardcoded to grant thread
Admin controls: retry, hold, release, cancel, status — all required
No auto-fallback from Codex to Claude on backend failures
Repo patterns to follow:
sql/social_publications.sql — schema + claim_due_* RPC function template
src/features/sharing/sharing_cog.py — @tasks.loop worker, claim → process → mark
src/features/sharing/social_publish_service.py — service layer between producer and queue
src/common/db_handler.py — Supabase client wrappers with _gate_check()
Createsql/payments.sql with three tables, one RPC function, and triggers. Follow the sql/social_publications.sql template exactly for structure (CREATE TABLE, indexes, RLS, triggers, RPC).
wallet_registry table — maps Discord users to verified wallets:
wallet_id UUID PK (gen_random_uuid)
guild_id bigint NOT NULL
discord_user_id bigint NOT NULL
chain text NOT NULL DEFAULT 'solana'
address text NOT NULL
label text — optional human name e.g. "main wallet"
verified_at timestamptz — null until a test payment confirms to this address
created_at timestamptz NOT NULL DEFAULT now()
updated_at timestamptz NOT NULL DEFAULT now()
Unique index on (guild_id, discord_user_id, chain) — one wallet per user per chain per guild
payment_requests table — the ledger:
payment_id UUID PK (gen_random_uuid)
guild_id bigint NOT NULL
producer text NOT NULL — e.g. 'grants', future: 'bounties', 'arccompute'
producer_ref text NOT NULL — e.g. grant thread_id, links back to source
recipient_discord_id bigint — optional, links to wallet_registry
recipient_wallet text NOT NULL — Solana address (denormalized from registry or direct)
wallet_id UUID REFERENCES wallet_registry(wallet_id) — optional FK
amount_usd numeric NOT NULL
amount_token numeric — computed SOL amount at send time
token_price_usd numeric — spot price at send time
chain text NOT NULL DEFAULT 'solana'
provider text NOT NULL DEFAULT 'solana_native'
status text NOT NULL DEFAULT 'pending_confirmation' CHECK in ('pending_confirmation', 'queued', 'processing', 'submitted', 'confirmed', , , )
Step 2: Add DB handler methods (src/common/db_handler.py)
Scope: Medium
Add wallet registry methods:
upsert_wallet(guild_id, discord_user_id, chain, address) — insert or update, returns wallet record
mark_wallet_verified(wallet_id, guild_id) — set verified_at to now
Add payment request methods mirroring the social publications pattern:
create_payment_request(record, guild_id) — insert with _gate_check()
get_payment_request(payment_id) — fetch single
get_payment_requests_by_producer(producer, producer_ref, is_test=None) — fetch by source, optionally filter by is_test
claim_due_payment_requests(limit, guild_ids) — RPC call to claim function
mark_payment_submitted(payment_id, tx_signature, amount_token, token_price_usd, send_phase, guild_id) — set status='submitted', store tx sig and send_phase
mark_payment_confirmed(payment_id, guild_id) — set status='confirmed', completed_at
mark_payment_failed(payment_id, error, send_phase, guild_id) — set status='failed', send_phase, completed_at. Only callable when send_phase='pre_submit' (definitive pre-send failure).
mark_payment_manual_hold(payment_id, reason, guild_id) — set status='manual_hold', hold_reason
requeue_payment(payment_id, retry_after, guild_id) — set status='queued', clear tx_signature, clear send_phase, set retry_after. Precondition check: current status must be 'failed' — never from 'manual_hold' or 'submitted'.
release_payment_hold(payment_id, new_status, guild_id) — transitions from 'manual_hold' to either 'confirmed', 'failed', or back to 'manual_hold'. This is the only path out of manual_hold.
cancel_payment(payment_id, guild_id) — set status='cancelled'. Only from pending_confirmation, queued, failed, or manual_hold.
get_inflight_payments_for_recovery() — fetch status IN ('processing', 'submitted') for restart recovery
get_pending_confirmation_payments(guild_ids) — fetch status='pending_confirmation' for button re-registration on restart
Pattern: Each method follows existing db_handler conventions — Supabase client calls, guild_id scoping, error logging, return dict or None.
Createsrc/features/payments/__init__.py (empty) and src/features/payments/provider.py.
Define a structured send result:
python
@dataclass
class SendResult:
signature: Optional[str] # tx sig if we got one back
phase: str # 'pre_submit' | 'submitted' | 'ambiguous'
error: Optional[str] # error message if any
phase='pre_submit' + error → definitive failure before tx was broadcast (bad address, insufficient balance). Safe to mark failed and allow retry.
phase='submitted' + signature → tx was broadcast, got signature back. Proceed to confirmation.
phase='ambiguous' + error → network error or exception after tx may have been broadcast. Must freeze to manual_hold — never auto-retry.
Key difference from v1: The send() method returns instead of a bare signature string, and is a separate method that polls/waits (wrapping ), distinct from the one-shot used only for recovery.
Wrap the existing SolanaClient (src/features/grants/solana_client.py) into SolanaProvider(PaymentProvider).
send() implementation — the critical safety wrapper:
Catch pre-send errors (address validation, balance check at solana_client.py:70-75) and return SendResult(signature=None, phase='pre_submit', error=str(e)).
For the actual send_sol() call: wrap in try/except. If send_sol() returns a signature, return SendResult(signature=sig, phase='submitted', error=None). If send_sol() raises, we cannot know if the tx was broadcast (the exception could be a network timeout after broadcast — see solana_client.py:97-114 where exceptions from send_transaction don't prove the chain rejected). Return SendResult(signature=None, phase='ambiguous', error=str(e)).
Implementation detail: To distinguish pre-submit from ambiguous, split the send_sol logic: do balance check separately (pre-submit failures), then call send_sol. Any exception from send_sol itself is ambiguous because the retry loop at solana_client.py:85-114 may have successfully submitted on an earlier attempt before a later retry raised.
confirm_tx() → delegates to solana_client.confirm_tx() (solana_client.py:118-124). Returns 'confirmed' on success, 'timeout' if the await times out, 'failed' if chain reports error.
check_status() → delegates to solana_client.check_tx_status() (solana_client.py:126-140). Returns 'confirmed', 'failed', or 'not_found'.
get_token_price_usd() → delegates to pricing.get_sol_price_usd().
KeepSolanaClient unchanged — it still works, the provider is a thin adapter.
Key: The provider holds the SolanaClient instance in memory. The keypair never leaves the SolanaClient object. No serialization, no DB storage, no logging of key material.
Step 5: Create payment service (src/features/payments/payment_service.py)
Scope: Medium
CreatePaymentService class — the core orchestrator between producers and the worker.
Constructor takes db_handler, a dict of {provider_name: PaymentProvider}, and a test_payment_amount float (the fixed tiny global test amount, e.g. 0.000001 SOL equivalent in USD).
Transitions from 'pending_confirmation' → 'queued'. Sets confirmed_by.
For test payments (is_test=True), the caller may pass confirmed_by='auto' to auto-confirm without a button interaction.
execute_payment(payment_id) method — called by the worker after claiming:
Fetch payment record.
Resolve provider from self.providers[record['provider']].
Fetch token price → compute amount_token from amount_usd.
Call provider.send(recipient_wallet, amount_token) → get SendResult.
If result.phase == 'pre_submit': definitive pre-send failure → mark_payment_failed(payment_id, result.error, send_phase='pre_submit'). This payment can be retried via admin.
If result.phase == 'ambiguous': post-send ambiguity → mark_payment_manual_hold(payment_id, reason=f"Ambiguous send error: {result.error}"). Never auto-retry.
CreatePaymentCog(commands.Cog) following sharing_cog.py pattern:
@tasks.loop(seconds=30) worker that calls db_handler.claim_due_payment_requests() then processes each via payment_service.execute_payment().
Configurable via env: PAYMENT_CLAIM_LIMIT (default 5), PAYMENT_WORKER_INTERVAL (default 30s).
Startup recovery in cog_load:
Call payment_service.recover_inflight().
Call payment_service.get_pending_confirmations(guild_ids) and re-register persistent views for each (see step 6.4).
Discord confirmation flow — when a producer calls payment_service.request_payment(), it gets back a payment record. The producer (e.g. grants cog) creates a PaymentConfirmView and sends it to the confirm_channel_id/confirm_thread_id from the payment record.
Persistent views for restart safety:
Define PaymentConfirmView(discord.ui.View) with timeout=None and a custom_id derived from the payment_id (e.g. f"payment_confirm:{payment_id}").
On cog_load, call bot.add_view(PaymentConfirmView(payment_id=pid)) for each pending_confirmation payment. This re-registers the button handler so it survives bot restarts.
The confirm button callback calls payment_service.confirm_payment(payment_id, confirmed_by=interaction.user.id).
Result notifications: After execute_payment() completes, the worker sends a message to notify_channel_id/notify_thread_id with tx status + explorer link. On manual_hold, it pings the configured admin mention.
Test payment auto-confirm: For is_test=True payments, the producer calls payment_service.confirm_payment(payment_id, confirmed_by='auto') immediately after request — no Discord button needed. A notification is still sent to the notification target when the test completes.
Add new admin chat tools (do NOT add payment_requests or wallet_registry to QUERYABLE_TABLES):
query_payments(filters) — dedicated tool that returns payment records with tx_signature visible but wallet addresses partially redacted (show first 4 + last 4 chars). Returns status, producer, amount, timestamps, hold_reason. Never returns any key material.
check_payment_status(payment_id) — re-checks chain for any payment with a tx_signature (status submitted or manual_hold). Calls provider.check_status() and reports current on-chain state without changing DB state. Admin uses this to decide next action.
hold_payment(payment_id, reason) — sets a payment to manual_hold with a reason string. Works from any non-terminal status.
release_payment(payment_id, resolution) — the only path out of manual_hold. Admin provides resolution: 'confirmed' (payment went through — mark confirmed), 'failed' (payment definitively did not go through — mark failed, now eligible for retry), or 'hold' (stay on hold with updated reason). This prevents accidental retry of ambiguously-submitted payments.
retry_payment(payment_id) — requeues a failed payment (sets status='queued', clears tx_signature and send_phase). Only works from failed status — cannot retry from manual_hold or submitted. Admin must first release_payment with resolution='failed' to move from hold to failed before retrying.
cancel_payment(payment_id, reason) — sets status='cancelled'. Only from pending_confirmation, queued, failed, or manual_hold.
query_wallets(discord_user_id?, guild_id?) — lists registered wallets with verified status.
Updatesrc/features/admin_chat/agent.py system prompt (agent.py:33-52) to include the new payment tools in the hand-written tool catalog. Add under a new Payments: heading:
code
Phase 4: Grants Producer Integration
Step 8: Refactor grants to produce payment requests (src/features/grants/grants_cog.py)
Scope: Medium
Replace_process_payment() (grants_cog.py:678-779) with calls to the payment service:
After wallet validation (grants_cog.py:367-380), register wallet in registry: db.upsert_wallet(guild_id, applicant_discord_id, 'solana', wallet).
Send PaymentConfirmView button to the confirmation target channel/thread.
On final payment confirmed: notification handler updates grant status to paid and archives thread.
Replace_recover_inflight_payments() (grants_cog.py:87-193) — remove entirely. Recovery is now handled by PaymentCog.cog_load → payment_service.recover_inflight().
Updategrant_applications status flow:
Old columns (payment_status, wallet_address, sol_amount, sol_price_usd, tx_signature) left in table for historical data. New payments flow through payment_requests exclusively.
payment_requested: set when payment_service.request_payment() succeeds for the test payment. No payment_ref column needed — the payment ledger is queried by (producer='grants', producer_ref=thread_id).
Step 9: Register cog and wire startup (main.py)
Scope: Small
InstantiateSolanaProvider wrapping the existing SolanaClient.
InstantiatePaymentService with db_handler, {'solana_native': solana_provider}, and test_payment_amount from env (e.g. PAYMENT_TEST_AMOUNT_USD, default 0.001).
LoadPaymentCog with payment_service, db_handler, and bot reference.
UpdateGrantsCog constructor to accept payment_service instead of solana_client directly.
Phase 5: Tests & Validation
Step 10: Unit tests (tests/test_payment_service.py)
Scope: Medium
Createtests/test_payment_service.py with FakeSupabase pattern from existing tests/test_social_route_tools.py:
Test idempotent request_payment — calling twice with same producer+ref+is_test returns same record.
Test confirm_payment transitions from pending_confirmation → queued.
Test recover_inflight: processing with no tx_sig → requeue; processing with ambiguous phase → hold; submitted with tx_sig → check chain → confirm/fail/hold.
Test admin controls: retry_payment only from failed (not manual_hold, not submitted). release_payment only from manual_hold. cancel_payment blocked from submitted and confirmed.
Test double-payment prevention: unique constraint prevents two active payments for same producer+ref+is_test.
Test wallet registry: upsert, get, verify.
Test routing columns: request_payment stores confirm/notify channel/thread IDs correctly.
Runpytest tests/test_payment_service.py -v.
Step 11: Integration smoke test
Scope: Small
Verify existing grant tests (if any) still pass — grants_cog changes should not break assessment/review flow.
Run full pytest suite to check for regressions.
Manual verification points (documented for human tester):
Deploy to staging, create a grant application, approve it, submit wallet, observe test-payment → auto-confirm → real-payment → button confirm → confirmed flow.
Kill bot mid-payment, restart, verify recovery picks up correctly and persistent views re-register.
Use admin chat: query_payments, check_payment_status, hold_payment, release_payment (with all three resolutions), retry_payment, cancel_payment.
Verify an applicant cannot open a second grant while payment is in payment_requested status.
Execution Order
Phase 1 first — DB schema is the foundation everything depends on.
Phase 2 next — provider abstraction and service layer, testable in isolation.
Phase 3 — worker cog and admin tools, depends on Phase 2.
Phase 4 — grants integration, depends on Phase 3.
Phase 5 throughout — write tests alongside each phase, run full suite at the end.
Validation Order
SQL schema is syntactically valid (review, apply to staging).
Unit tests for payment_service pass (Phase 2 + Phase 5 step 10).
Admin tools respond correctly to various payment states, and are reachable from admin chat (agent prompt updated).
Persistent views re-register on restart for pending_confirmation payments.
Grants cog compiles and loads without errors; active-grant checks include payment_requested.
Full pytest suite green.
Manual smoke test on staging (info-level, cannot automate).
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-04-09T21:51:21Z",
"hash": "sha256:a833ee969117cb99ee40a392d757c4f792a461b760ad17c1a44fa512914b7465",
"changes_summary": "Revised the plan to address all 19 significant flags from the gate critique. The major design changes are:\n\n1. Provider send() contract redesigned (FLAG-001, correctness-1): send() now returns a SendResult dataclass with a phase field (pre_submit, submitted, ambiguous) instead of a bare string. Only pre_submit failures can be marked as failed and auto-retried. ambiguous errors (where tx may have been broadcast) always go to manual_hold.\n\n2. Post-submit confirmation flow fixed (correctness-2): Added confirm_tx() as a separate provider method that polls/waits for confirmation (wrapping the existing SolanaClient.confirm_tx), used immediately after successful submission. The one-shot check_status() is reserved for recovery only. Timeout goes to manual_hold, not failed.\n\n3. Route-configured confirmation destinations (FLAG-002, callers-1, scope-2): Added confirm_channel_id, confirm_thread_id, notify_channel_id, notify_thread_id, and metadata columns to the ledger. The request_payment() API requires these routing parameters so producers declare where confirmation and notifications go.\n\n4. Wallet registry added (FLAG-006, issue_hints-2): New wallet_registry table with (guild_id, discord_user_id, chain) uniqueness. payment_requests has an optional FK to it. Wallets are marked verified_at when a test payment to that address confirms.\n\n5. Active-grant checks updated (FLAG-003, scope-1): get_active_grants_for_applicant() now includes payment_requested in the active status list. Assessor prompt updated to match.\n\n6. Admin controls expanded (FLAG-004, issue_hints-1): Added release_payment (the only exit from manual_hold \u2014 admin declares confirmed/failed/hold), check_payment_status (read-only chain check), and query_wallets. retry_payment restricted to failed status only \u2014 cannot retry from manual_hold.\n\n7. Restart-safe Discord buttons (FLAG-005, all_locations-1): PaymentConfirmView uses with payment_id-derived . calls for each payment.\n\n8. (all_locations-2): Explicit step to update the hand-written tool catalog in .\n\n9. (callers-2, criteria_quality-2): No column \u2014 grants queries the payment ledger by to find both test and final payments.\n\n10. (all_locations-3): Follows the directory pattern.\n\n11. (criteria_quality-1, criteria_quality-2): Added must-criteria for route-configured destinations, release/status admin controls, wallet registry, restart-safe views, and active-grant blocking.",
"flags_addressed": [
"FLAG-001",
"FLAG-002",
"FLAG-003",
"FLAG-004",
"FLAG-005",
"FLAG-006",
"issue_hints-1",
"issue_hints-2",
"correctness-1",
"correctness-2",
"scope-1",
"scope-2",
"all_locations-1",
"all_locations-2",
"all_locations-3",
"callers-1",
"callers-2",
"criteria_quality-1",
"criteria_quality-2"
],
"questions": [
"Should test payments send actual dust (e.g. 0.000001 SOL worth ~0.001) per grant but gives true chain-level validation.",
"For the admin release_payment flow: when admin declares 'confirmed' (payment went through), should the system also mark the wallet as verified in the registry automatically, or should that remain a separate step?",
"For the wallet_registry: should it support multiple wallets per user per chain (e.g. a user might want different wallets for different grants), or is one-wallet-per-user-per-chain sufficient for v1?",
"Is there an existing env var pattern for the test payment amount, or should we define a new one like PAYMENT_TEST_AMOUNT_USD?",
"For the payment result notification in grant threads: should the bot post both test-payment and final-payment results to the thread, or only the final payment result?"
],
"success_criteria": [
{
"criterion": "payment_requests table exists with all specified columns including routing (confirm_channel_id, confirm_thread_id, notify_channel_id, notify_thread_id, metadata) and send_phase tracking",
"priority": "must"
},
{
"criterion": "wallet_registry table exists with (guild_id, discord_user_id, chain) uniqueness and verified_at timestamp",
"priority": "must"
},
{
"criterion": "claim_due_payment_requests RPC uses FOR UPDATE SKIP LOCKED and atomically transitions status to processing",
"priority": "must"
},
{
"criterion": "Provider send() returns SendResult with phase field (pre_submit/submitted/ambiguous); only pre_submit failures are marked failed; ambiguous always goes to manual_hold",
"priority": "must"
},
{
"criterion": "After tx submission (status=submitted), confirm_tx polls/waits for confirmation; timeout goes to manual_hold, never auto-retry",
"priority": "must"
},
{
"criterion": "Only chain-definitive failure (confirm_tx returns 'failed' or check_status returns 'failed') allows transition to failed state",
"priority": "must"
},
{
"criterion": "Private keys never appear in DB columns, log messages, or admin chat tool responses",
"priority": "must"
},
{
"criterion": "payment_requests and wallet_registry tables are NOT in QUERYABLE_TABLES; dedicated query_payments tool redacts wallet addresses",
"priority": "must"
},
{
"criterion": "Admin controls include all five required operations: hold_payment, release_payment (only exit from manual_hold), retry_payment (only from failed), cancel_payment, check_payment_status (read-only chain check)",
"priority": "must"
},
{
"criterion": "release_payment is the only path out of manual_hold \u2014 admin must explicitly declare confirmed, failed, or keep holding",
"priority": "must"
},
{
"criterion": "retry_payment only works from failed status \u2014 submitted and manual_hold states are blocked from direct retry",
"priority": "must"
},
{
"criterion": "Unique partial index prevents two active (non-failed, non-cancelled) payments for the same producer + producer_ref + is_test combination",
"priority": "must"
},
{
"criterion": "On bot restart, recover_inflight correctly resolves: processing/no-tx-sig \u2192 requeue, processing/ambiguous \u2192 hold, submitted/tx-sig \u2192 check chain \u2192 confirm/fail/hold",
"priority": "must"
},
{
"criterion": "Confirmation destinations are route-configured via confirm_channel_id/confirm_thread_id on payment_requests; request_payment API requires these parameters",
"priority": "must"
},
{
"criterion": "Restart-safe Discord confirmation: PaymentConfirmView uses timeout=None with payment_id-derived custom_id; cog_load calls bot.add_view() for each pending_confirmation payment",
"priority": "must"
},
{
"criterion": "get_active_grants_for_applicant includes payment_requested in active statuses; assessor prompt updated to match",
"priority": "must"
},
{
"criterion": "Grants cog produces payment requests (test then final) instead of calling solana_client directly; grant status flow uses payment_requested and paid",
"priority": "must"
},
{
"criterion": "Grants queries payment ledger by (producer='grants', producer_ref=thread_id, is_test) \u2014 no single payment_ref column needed",
"priority": "must"
},
{
"criterion": "Admin agent.py system prompt tool catalog updated with all payment tools so they are reachable from admin chat",
"priority": "must"
},
{
"criterion": "All new unit tests pass (pytest tests/test_payment_service.py)",
"priority": "must"
},
{
"criterion": "Full pytest suite passes with no regressions",
"priority": "must"
},
{
"criterion": "PaymentProvider ABC has exactly: send (returns SendResult), confirm_tx, check_status, get_token_price_usd, token_name",
"priority": "should"
},
{
"criterion": "Worker loop follows sharing_cog pattern: @tasks.loop, claim batch, sequential process, env-configurable interval and batch size",
"priority": "should"
},
{
"criterion": "New files stay under ~300 lines each; payment_service.py may be up to ~400 given the state machine complexity",
"priority": "should"
},
{
"criterion": "Test and final payment flows are distinct: is_test flag on payment_requests, test payments auto-confirm with confirmed_by='auto'",
"priority": "should"
},
{
"criterion": "Manual staging smoke test: full grant \u2192 test-payment \u2192 auto-confirm \u2192 final-payment \u2192 button confirm \u2192 confirmed flow",
"priority": "info"
},
{
"criterion": "Manual staging test: kill bot mid-payment, restart, verify recovery and button re-registration",
"priority": "info"
},
{
"criterion": "Manual staging test: admin chat hold/release/retry/cancel/status cycle",
"priority": "info"
}
],
"assumptions": [
"v1 targets native SOL transfers only \u2014 SPL token support (USDC etc.) is a future extension, but the provider abstraction accommodates it without code changes.",
"The existing SolanaClient class remains unchanged; SolanaProvider is a thin adapter wrapping it.",
"grant_applications columns (payment_status, wallet_address, tx_signature, sol_amount, sol_price_usd) are left in the table for historical records but new payments flow through payment_requests exclusively.",
"SQL reference scripts go in sql/ following the social_publications.sql pattern. Formal migrations in supabase/migrations/ can be derived from these.",
"The Discord confirmation flow uses persistent views (timeout=None + bot.add_view) for restart safety. This is a new pattern for this repo \u2014 no existing code uses bot.add_view.",
"Test payments send real dust on-chain to validate the wallet. The test amount is a fixed global env var, not per-grant.",
"The payment worker runs in the same bot process as the sharing worker \u2014 no separate deployment.",
"Admin chat tools follow the existing Anthropic tool-call format used by other tools in tools.py, and the hand-written tool catalog in agent.py must be updated for new tools to be reachable.",
"Grants queries the payment ledger by (producer, producer_ref, is_test) to find both test and final payments \u2014 no payment_ref column on grant_applications.",
"wallet_registry stores one wallet per user per chain per guild. Multiple wallets per user would require a schema change."
],
"delta_from_previous_percent": 58.06,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "Payments execution: the planned send() contract cannot distinguish definite pre-submit failure from ambiguous post-submit failure, so automatic retries can still double-pay.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Payments routing: the plan hardcodes grant-thread confirmation behavior and does not persist route-configured confirmation or notification targets.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-003",
"concern": "Grants state machine: new pending-payment statuses are not propagated into the existing active-grant checks, so applicants could open another grant while payment is still unresolved.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-004",
"concern": "Payments admin controls: the plan omits the required release/status controls and allows retry from manual_hold, which is unsafe when manual_hold came from ambiguous submitted transactions.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-005",
"concern": "Discord interactions: the planned button confirmation flow is not restart-safe because it does not include persistent view registration or another reattachment mechanism.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-006",
"concern": "Payments recipient model: explicitly deferring a wallet registry leaves the new subsystem less generalized than the task brief requires.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-1",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Compared the locked user notes to Steps 6-8 of the plan: the plan still assumes confirmations happen in the grant thread and that test payments can auto-confirm, but the user already fixed the confirmation destination as route-configured and required manual release/status controls; Step 7 only adds query/hold/retry/cancel, so that requirement is only partially covered.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-2",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the v1 scope statement against the task brief and found a direct narrowing: the task asks for a generalized payment subsystem with a wallet registry, but Step 1 explicitly defers any wallet registry and keeps recipient wallets as per-payment text only, which leaves the design closer to the current grants-only flow than the brief calls for.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: Compared Step 5 with src/features/grants/solana_client.py:59-116: the proposed provider.send() plus except -> mark failed contract cannot distinguish a definite pre-submit failure from an ambiguous network error after send_transaction, so auto-retrying after a raised exception can still violate the fail-closed invariant and double-pay.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: Compared the planned post-submit flow with the existing client behavior and found a timing bug: the repo currently waits on after submission, but the plan replaces that with one immediate call and sends straight to ; on Solana a freshly submitted signature can be briefly absent from , so healthy payments could be frozen routinely.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-1",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Searched the rest of the grants subsystem and found that active-grant logic is broader than : still treats only and as active, and tells Claude the same thing, so introducing or without updating those paths would reopen duplicate-application holes.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-2",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Looked at the proposed 'generalized' subsystem against the actual producer surface and found the ledger scope too narrow: the schema only stores and , but no durable confirmation route, result-notification target, or wallet-verification state, which means future producers would still need producer-specific side channels instead of using the payment ledger end to end.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-1",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked the supporting Discord glue and found a restart gap: button-based confirmation is not just a ledger change, because restart-safe Discord buttons need persistent views or another re-registration path; the repo has classes in features like social notifications, but there is no registration anywhere and the plan does not add one.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-2",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked admin-chat integration surfaces and found more wiring than the plan names: adding payment tools requires more than functions in because contains a hand-written tool catalog the LLM reads; the plan mentions updating but not the agent prompt text, so the new controls could be unreachable in practice.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-3",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked schema placement against repo infrastructure and found the application path underspecified: the social queue pattern does use , but still documents as the canonical migration home, so putting payments only in leaves the actual rollout path ambiguous.",
"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?: Traced the current payment caller in : the only live caller hands a forum thread, the current grant row, and the applicant-supplied wallet string, but the planned signature does not take any confirmation-destination metadata even though the locked behavior now depends on route-configured destinations.",
"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?: Traced the grant DB callers that would consume the new linkage and found a modeling gap: Step 8 adds a single column on , but the same plan also requires separate test and final payment attempts, so one pointer is not enough to represent both ledger rows or tell the grant flow which phase is current after restart.",
"status": "addressed",
"severity": "significant"
},
{
"id": "conventions",
"concern": "Does the approach match how the codebase solves similar problems?: Compared the cross-cog integration style to the rest of the codebase and found the handoff still underspecified: existing features usually wire shared services through bot attributes or direct cog construction in , whereas Step 8 says 'emit a Discord event or call a callback' without choosing one concrete repo pattern for the critical payment-to-grants update.",
"status": "open",
"severity": "minor"
},
{
"id": "verification-1",
"concern": "Is there convincing verification for the change?: Searched and found no grant or payment coverage at all today, so a single new file is not convincing by itself; the riskiest regressions here are in grants integration, route-configured confirmation delivery, and restart-time recovery inside the Discord cog lifecycle.",
"status": "open",
"severity": "minor"
},
{
"id": "verification-2",
"concern": "Is there convincing verification for the change?: Checked the locked behaviors against the proposed validation list and did not see tests for the required release/status admin controls or for confirmation interactions surviving a restart, so two user-facing failure modes would still rely on manual smoke testing alone.",
"status": "open",
"severity": "minor"
},
{
"id": "criteria_quality-1",
"concern": "Are the success criteria well-prioritized and verifiable?: The success criteria omit several locked requirements entirely: there is no criterion for route-configured confirmation destinations, manual and controls, or a wallet registry, so the gate would have no direct yes-or-no check for several user-mandated behaviors.",
"status": "addressed",
"severity": "significant"
},
{
"id": "criteria_quality-2",
"concern": "Are the success criteria well-prioritized and verifiable?: The criterion saying the grants cog should produce payment requests and update the grant status flow is still too broad for review because it does not spell out how two payments per grant are represented or which non-terminal statuses must remain blocking for duplicate-grant checks.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{
"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/build-a-fail-closed-20260409-2327/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.
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
Prepared the engineering brief after investigating the existing grants payout flow, the Solana client, the DB helpers, the admin surfaces, and the existing social-publication queue pattern.
### Key Evidence
- Current grant payouts are still executed inline from `GrantsCog` and use mutable `grant_applications` status fields instead of a reusable ledger. (source: src/features/grants/grants_cog.py; relevance: high)
The repo already contains an atomic queue/worker pattern with FOR UPDATE SKIP LOCKED via social_publications, which is the strongest template for the new payment subsystem. (source: sql/social_publications.sql; src/common/db_handler.py; src/features/sharing/sharing_cog.py; relevance: high)
Admin chat currently exposes grant_applications through generic query_table, so any new secret-bearing payment/wallet tables must be kept off that surface or explicitly redacted. (source: src/features/admin_chat/tools.py; relevance: high)
code
### Relevant Code
| File | Functions | Why |
| --- | --- | --- |
| /Users/user_c042661f/Documents/banodoco-workspace/brain-of-bndc/.megaplan/plans/build-a-fail-closed-20260409-2327/prep.json | - | Final brief written here. |
code
### Test Expectations
- [pass_to_pass] prep.json: Brief file exists and is valid JSON.
### Constraints
- The requested output had to be written to the specified megaplan prep path.
The brief needed investigation because the task spans multiple subsystems and files.
code
### Suggested Approach
Use the written prep brief as the planning context for the next step.
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:
Build a fail-closed generalized payment subsystem for ArcCompute-style payouts on Solana. Replace direct grant sends with a reusable payment ledger, provider abstraction, wallet registry, Discord confirmation flow, manual hold/retry controls, and restart-safe recovery. Critical requirements: no automatic double-payment after tx submission unless chain definitively reports failure; ambiguous chain state freezes to manual hold; private keys never enter DB/logs/admin-chat; atomic worker claiming; separate test-payment and final-payment attempts; grants becomes a producer into the payment system.
User notes and answers:
Locked decisions from user: test payment is a fixed tiny global amount; confirmation destination is route-configured and may be the source thread/forum post or a specific payments channel/forum; manual admin controls for retry/hold/release/cancel/status are required; do not auto-fallback from Codex to Claude on backend connection failures.
The bot currently processes Solana grant payouts inline inside GrantsCog._process_payment() (src/features/grants/grants_cog.py:678-779), with payment state baked into grant_applications columns. This works but is non-reusable, tightly coupled, and has limited admin controls.
The goal is a standalone payment subsystem modeled on the existing social_publications queue pattern (sql/social_publications.sql): a payment ledger table, wallet registry, payment route configuration, atomic worker claiming via FOR UPDATE SKIP LOCKED, a provider abstraction layer, Discord confirmation flow with restart-safe persistent views, manual admin controls (hold/release/retry/cancel/status), and restart-safe recovery. Grants becomes just a producer that enqueues payment requests.
Critical safety invariant: After a transaction is submitted to the chain, it is never automatically retried unless the chain definitively reports failure. The provider contract distinguishes pre-submit failures (safe to mark failed) from post-submit ambiguity (must freeze to manual_hold). Unknown/ambiguous status requires admin resolution via release_payment before retry is allowed. Private keys never touch DB, logs, or admin chat.
Key design decisions (locked by user):
Test payment amount: fixed tiny global SOL amount (e.g. 0.000001 SOL), not USD-derived — the on-chain transfer is always the same dust amount regardless of price
Confirmation destination: route-configured per producer via payment_channel_routes table (same pattern as social_channel_routes), with fallback to source thread
Admin controls: retry, hold, release, cancel, status — all required
No auto-fallback from Codex to Claude on backend failures
Add payment request methods mirroring the social publications pattern:
create_payment_request(record, guild_id) — insert with _gate_check()
get_payment_request(payment_id) — fetch single
get_payment_requests_by_producer(producer, producer_ref, is_test=None) — fetch by source, optionally filter by is_test
claim_due_payment_requests(limit, guild_ids) — RPC call to claim function
mark_payment_submitted(payment_id, tx_signature, amount_token, token_price_usd, send_phase, guild_id) — set status='submitted', store tx sig and send_phase
mark_payment_confirmed(payment_id, guild_id) — set status='confirmed', completed_at
mark_payment_failed(payment_id, error, send_phase, guild_id) — set status='failed', store send_phase, completed_at. Callable for any send_phase value — the safety invariant is enforced at the service layer (ambiguous phase → manual_hold, never failed). The DB method records the phase for admin visibility but does not gate on it. This allows both pre-submit failures and chain-definitive post-submit failures to be marked failed.
mark_payment_manual_hold(payment_id, reason, guild_id) — set status='manual_hold', hold_reason
requeue_payment(payment_id, retry_after, guild_id) — set status='queued', clear tx_signature, clear send_phase, set retry_after. Precondition check: current status must be 'failed' — never from 'manual_hold' or 'submitted'.
release_payment_hold(payment_id, new_status, guild_id) — transitions from 'manual_hold' to either 'confirmed', 'failed', or back to 'manual_hold'. This is the only path out of manual_hold.
Step 3: Add route resolver to ServerConfig (src/common/server_config.py)
Scope: Small
Addresolve_payment_route(guild_id, channel_id, producer) method to ServerConfig, mirroring resolve_social_route() (server_config.py:183-222):
Calls resolve_payment_route() to get the route record
Extracts confirm_channel_id, confirm_thread_id, notify_channel_id, notify_thread_id from route_config JSONB
Returns a dict {'route_key': route_id, 'confirm_channel_id': ..., 'confirm_thread_id': ..., 'notify_channel_id': ..., 'notify_thread_id': ...} or None if no route found
Createsrc/features/payments/__init__.py (empty) and src/features/payments/provider.py.
Define a structured send result:
python
@dataclass
class SendResult:
signature: Optional[str] # tx sig if we got one back
phase: str # 'pre_submit' | 'submitted' | 'ambiguous'
error: Optional[str] # error message if any
phase='pre_submit' + error → definitive failure before tx was broadcast (bad address, insufficient balance). Safe to mark failed and allow retry.
phase='submitted' + signature → tx was broadcast, got signature back. Proceed to confirmation.
phase='ambiguous' + error → network error or exception after tx may have been broadcast. Must freeze to manual_hold — never auto-retry.
Wrap the existing SolanaClient (src/features/grants/solana_client.py) into SolanaProvider(PaymentProvider).
send() implementation — the critical safety wrapper:
Catch pre-send errors (address validation, balance check at solana_client.py:70-75) and return SendResult(signature=None, phase='pre_submit', error=str(e)).
For the actual send_sol() call: wrap in try/except. If send_sol() returns a signature, return SendResult(signature=sig, phase='submitted', error=None). If send_sol() raises, we cannot know if the tx was broadcast (the exception could be a network timeout after broadcast — see solana_client.py:97-114 where exceptions from send_transaction don't prove the chain rejected). Return SendResult(signature=None, phase='ambiguous', error=str(e)).
Implementation detail: To distinguish pre-submit from ambiguous, split the send_sol logic: do balance check separately (pre-submit failures), then call send_sol. Any exception from send_sol itself is ambiguous because the retry loop at solana_client.py:85-114 may have successfully submitted on an earlier attempt before a later retry raised.
confirm_tx() → delegates to solana_client.confirm_tx() (solana_client.py:118-124). Returns 'confirmed' on success, 'timeout' if the await times out, 'failed' if chain reports error.
check_status() → delegates to solana_client.check_tx_status() (solana_client.py:126-140). Returns 'confirmed', 'failed', or 'not_found'.
get_token_price_usd() → delegates to pricing.get_sol_price_usd().
KeepSolanaClient unchanged — it still works, the provider is a thin adapter.
Key: The provider holds the SolanaClient instance in memory. The keypair never leaves the SolanaClient object. No serialization, no DB storage, no logging of key material.
Step 6: Create payment service (src/features/payments/payment_service.py)
Scope: Medium
CreatePaymentService class — the core orchestrator between producers and the worker.
Constructor takes db_handler, a dict of {provider_name: PaymentProvider}, and test_payment_amount_sol: float (the fixed tiny global test amount, e.g. 0.000001 SOL).
All required parameters appear before all optional parameters. Keyword-only (*) to prevent positional mistakes.
amount_usd is required for is_test=False payments (raises ValueError if None). For is_test=True, amount_usd is ignored.
Checks for existing active payment for same (producer, producer_ref, is_test) — returns it if found (idempotent).
For is_test=True: sets amount_token to self.test_payment_amount_sol directly, leaves amount_usd=None and token_price_usd=None on the record. The on-chain transfer is always exactly this fixed dust amount.
For is_test=False: stores amount_usd; amount_token and token_price_usd are computed at send time by execute_payment().
Creates payment_requests row with status 'pending_confirmation' and all routing columns populated.
Returns the payment record (caller uses payment_id for Discord confirmation flow).
CreatePaymentCog(commands.Cog) following sharing_cog.py pattern:
@tasks.loop(seconds=30) worker that calls db_handler.claim_due_payment_requests() then processes each via payment_service.execute_payment().
Configurable via env: PAYMENT_CLAIM_LIMIT (default 5), PAYMENT_WORKER_INTERVAL (default 30s).
Startup recovery in cog_load:
Call payment_service.recover_inflight().
Call payment_service.get_pending_confirmations(guild_ids) and re-register persistent views for each (see step 7.4).
Discord confirmation flow — when a producer calls payment_service.request_payment(), it gets back a payment record. The producer (e.g. grants cog) creates a PaymentConfirmView and sends it to the confirm_channel_id/confirm_thread_id from the payment record.
Persistent views for restart safety:
Define PaymentConfirmView(discord.ui.View) with timeout=None and a custom_id derived from the payment_id (e.g. f"payment_confirm:{payment_id}").
On cog_load, call bot.add_view(PaymentConfirmView(payment_id=pid)) for each pending_confirmation payment. This re-registers the button handler so it survives bot restarts.
The confirm button callback calls payment_service.confirm_payment(payment_id, confirmed_by=interaction.user.id).
Result notifications and producer callback: After execute_payment() completes, the worker:
Sends a message to notify_channel_id/notify_thread_id with tx status + explorer link. On manual_hold, it pings the configured admin mention.
Calls back into the producer cog via bot.get_cog() — the repo-native cross-cog communication pattern (see ReactorCog → LoggerCog at src/features/reacting/). Specifically:
If producer == 'grants': grants_cog = self.bot.get_cog("GrantsCog") → grants_cog.handle_payment_result(payment_record).
Other producers register handlers the same way; PaymentCog has a dict.
Add payment ledger and wallet tools (do NOT add payment_requests, wallet_registry, or payment_channel_routes to QUERYABLE_TABLES):
query_payments(filters) — dedicated tool that returns payment records with tx_signature visible but wallet addresses partially redacted (show first 4 + last 4 chars). Returns status, producer, amount, timestamps, hold_reason. Never returns any key material.
check_payment_status(payment_id) — re-checks chain for any payment with a tx_signature (status submitted or manual_hold). Calls provider.check_status() and reports current on-chain state without changing DB state. Admin uses this to decide next action.
hold_payment(payment_id, reason) — sets a payment to manual_hold with a reason string. Works from any non-terminal status.
release_payment(payment_id, resolution) — the only path out of manual_hold. Admin provides resolution: 'confirmed' (payment went through — mark confirmed), 'failed' (payment definitively did not go through — mark failed, now eligible for retry), or 'hold' (stay on hold with updated reason). This prevents accidental retry of ambiguously-submitted payments.
retry_payment(payment_id) — requeues a failed payment (sets status='queued', clears tx_signature and send_phase). Only works from failed status — cannot retry from manual_hold or submitted. Admin must first release_payment with resolution='failed' to move from hold to failed before retrying.
cancel_payment(payment_id, reason) — sets status='cancelled'. Only from , , , or .
Phase 4: Grants Producer Integration
Step 9: Refactor grants to produce payment requests (src/features/grants/grants_cog.py)
Scope: Medium
Replace_process_payment() (grants_cog.py:678-779) with calls to the payment service. Route resolution happens at the caller site — grants resolves the payment route before calling request_payment():
python
# Resolve payment destinations from configured route
server_config = self.bot.db_handler.server_config
destinations = server_config.resolve_payment_destinations(
guild_id=guild_id,
channel_id=thread.parent_id, # the forum channel containing this grant thread
producer='grants'
)
# Fallback to source thread if no route configured
if destinations is None:
destinations = {
'route_key': None,
'confirm_channel_id': thread.parent_id,
'confirm_thread_id': thread.id,
'notify_channel_id': thread.parent_id,
'notify_thread_id': thread.id,
}
After wallet validation (grants_cog.py:367-380), register wallet: db.upsert_wallet(guild_id, applicant_discord_id, 'solana', wallet).
Addhandle_payment_result(self, payment_record) method to GrantsCog — the callback called by PaymentCog via bot.get_cog("GrantsCog"):
If payment_record['is_test'] == True and payment_record['status'] == 'confirmed': test succeeded → enqueue real payment:
Step 10: Register cog and wire startup (main.py)
Scope: Small
InstantiateSolanaProvider wrapping the existing SolanaClient.
InstantiatePaymentService with db_handler, {'solana_native': solana_provider}, and test_payment_amount_sol from env (e.g. PAYMENT_TEST_AMOUNT_SOL, default 0.000001).
Attachpayment_service to bot.payment_service (repo convention for shared services).
LoadPaymentCog — it accesses bot.payment_service and bot.db_handler via getattr(self.bot, ...) (repo convention — cogs resolve services from bot, not constructor injection).
No change to GrantsCog constructor — it accesses bot.payment_service via getattr(self.bot, 'payment_service') at runtime.
Phase 5: Tests & Validation
Step 11: Unit tests (tests/test_payment_service.py)
Scope: Medium
Createtests/test_payment_service.py with FakeSupabase pattern from existing tests/test_social_route_tools.py:
Test idempotent request_payment — calling twice with same producer+ref+is_test returns same record.
Test confirm_payment transitions from pending_confirmation → queued.
Test execute_payment chain-definitive failure: provider.send() returns submitted, confirm_tx returns failed → payment marked failed with send_phase='submitted' (tests that post-submit chain failures are allowed).
Test recover_inflight: processing with no tx_sig → requeue; processing with ambiguous phase → hold; submitted with tx_sig → check chain → confirm/fail/hold.
Test admin controls: retry_payment only from failed (not manual_hold, not submitted). release_payment only from manual_hold. cancel_payment blocked from submitted and confirmed.
Test double-payment prevention: unique constraint prevents two active payments for same producer+ref+is_test.
Test wallet registry: upsert, get, verify.
Test routing columns: request_payment stores confirm/notify channel/thread IDs and route_key correctly.
Test test-payment amount: for is_test=True, amount_token equals test_payment_amount_sol regardless of any USD value; amount_usd and token_price_usd are None.
Step 12: Integration smoke test
Scope: Small
Verify existing grant tests (if any) still pass — grants_cog changes should not break assessment/review flow.
Run full pytest suite to check for regressions.
Manual verification points (documented for human tester):
Deploy to staging, configure a payment route for grants via admin chat (create_payment_route with confirm/notify destinations), then create a grant application, approve it, submit wallet, observe test-payment → auto-confirm → real-payment → button confirm → confirmed flow.
Test with no payment route configured — verify fallback to source thread works.
Kill bot mid-payment, restart, verify recovery picks up correctly and persistent views re-register.
Use admin chat: list_payment_routes, create_payment_route, query_payments, check_payment_status, hold_payment, release_payment (with all three resolutions), retry_payment, cancel_payment.
Verify an applicant cannot open a second grant while payment is in payment_requested status.
Execution Order
Phase 1 first — DB schema (including routes table) and ServerConfig resolver are the foundation everything depends on.
Phase 2 next — provider abstraction and service layer, testable in isolation.
Phase 3 — worker cog, Discord integration, and admin tools (including route CRUD), depends on Phase 2.
Phase 4 — grants integration with route resolution at caller site, depends on Phase 3.
Phase 5 throughout — write tests alongside each phase, run full suite at the end.
Validation Order
SQL schema is syntactically valid (review, apply to staging).
resolve_payment_destinations() returns correct hierarchical results (manual or unit test).
Unit tests for payment_service pass (Phase 2 + Phase 5 step 11).
Admin route CRUD tools and payment control tools respond correctly, and are reachable from admin chat (agent prompt updated).
Persistent views re-register on restart for pending_confirmation payments.
Grants cog resolves routes via resolve_payment_destinations(), falls back to source thread, and calls handle_payment_result on terminal events.
Active-grant checks include payment_requested.
Full pytest suite green.
Manual smoke test on staging with configured route AND without route (fallback) (info-level, cannot automate).
code
Plan metadata:
{
"version": 3,
"timestamp": "2026-04-09T22:03:20Z",
"hash": "sha256:f5d6886f8cd41425e304cb3ac3fb61e7cbf75753341011fcd9b708a3203d1ac4",
"changes_summary": "Revised the plan to address all 13 remaining significant flags. The major changes are:\n\n1. Payment route configuration system (FLAG-002, issue_hints-1, scope, all_locations, callers, criteria_quality-1): Added payment_channel_routes table mirroring social_channel_routes (same schema pattern with guild_id/channel_id/producer uniqueness). Added resolve_payment_route() and resolve_payment_destinations() to ServerConfig, mirroring resolve_social_route(). Added CRUD admin tools (list/create/update/delete_payment_routes). Grants caller now resolves route via server_config.resolve_payment_destinations(guild_id, channel_id, producer='grants') before calling request_payment(), with fallback to source thread only when no route is configured.\n\n2. Test payment amount fixed to SOL (issue_hints-2, FLAG-008, criteria_quality-2): Changed from USD to fixed SOL amount. Env var is now PAYMENT_TEST_AMOUNT_SOL (default 0.000001). For is_test=True payments, amount_token is set directly to this value, price lookup is skipped, and amount_usd/token_price_usd are stored as None. Added success criterion pinning this behavior.\n\n3. State machine contradiction resolved (correctness-2, FLAG-007): mark_payment_failed() DB method now accepts any send_phase value \u2014 it records the phase for admin visibility but does not gate on it. The safety invariant is enforced at the service layer: only pre_submit failures and chain-definitive submitted failures (where confirm_tx returns 'failed') are marked failed. ambiguous phase always goes to manual_hold. Added a dedicated test case for chain-definitive post-submit failures.\n\n4. Python signature fixed (correctness-1): request_payment() is now keyword-only (*) with all required parameters before optional ones: producer, producer_ref, guild_id, recipient_wallet, chain, provider, is_test, confirm_channel_id, notify_channel_id are required; amount_usd, recipient_discord_id, wallet_id, confirm_thread_id, notify_thread_id, route_key, metadata are optional with defaults.\n\n5. Grants handoff pattern unified (conventions): Chose single concrete pattern \u2014 bot.get_cog() direct method call (the same pattern used by ReactorCog \u2192 LoggerCog). PaymentCog calls after terminal state. GrantsCog implements with clear branching on is_test \u00d7 status. No listeners, no custom events, no callbacks \u2014 just the repo-native cog-to-cog method call.",
"flags_addressed": [
"FLAG-002",
"issue_hints-1",
"issue_hints-2",
"correctness-1",
"correctness-2",
"conventions",
"criteria_quality-1",
"criteria_quality-2",
"FLAG-007",
"FLAG-008",
"scope",
"all_locations",
"callers"
],
"questions": [
"Should test payments send actual dust (e.g. 0.000001 SOL) to validate the wallet is receivable on-chain, or just validate the address format locally? Real dust costs a tx fee (~$0.001) per grant but gives true chain-level validation.",
"For the admin release_payment flow: when admin declares 'confirmed' (payment went through), should the system also mark the wallet as verified in the registry automatically, or should that remain a separate step?",
"For the wallet_registry: should it support multiple wallets per user per chain (e.g. a user might want different wallets for different grants), or is one-wallet-per-user-per-chain sufficient for v1?",
"For the payment result notification in grant threads: should the bot post both test-payment and final-payment results to the thread, or only the final payment result?",
"Should the payment_channel_routes.route_config JSONB also support a 'require_admin_confirm' boolean to force admin-only confirmation buttons for high-value payments, or is that a v2 feature?"
],
"success_criteria": [
{
"criterion": "payment_requests table exists with all specified columns including routing (route_key, confirm_channel_id, confirm_thread_id, notify_channel_id, notify_thread_id, metadata) and send_phase tracking",
"priority": "must"
},
{
"criterion": "wallet_registry table exists with (guild_id, discord_user_id, chain) uniqueness and verified_at timestamp",
"priority": "must"
},
{
"criterion": "payment_channel_routes table exists mirroring social_channel_routes schema: guild_id, channel_id (nullable for defaults), producer, route_config JSONB, enabled; with uniqueness indexes matching the social routes pattern",
"priority": "must"
},
{
"criterion": "ServerConfig has resolve_payment_route() and resolve_payment_destinations() methods using the same hierarchical resolution as resolve_social_route(): exact channel \u2192 parent channel \u2192 guild default",
"priority": "must"
},
{
"criterion": "Grants caller resolves payment destinations via server_config.resolve_payment_destinations() before calling request_payment(), with fallback to source thread only when no route is configured",
"priority": "must"
},
{
"criterion": "Admin CRUD tools for payment routes (list, create, update, delete) exist and follow the social_channel_routes tool pattern",
"priority": "must"
},
{
"criterion": "claim_due_payment_requests RPC uses FOR UPDATE SKIP LOCKED and atomically transitions status to processing",
"priority": "must"
},
{
"criterion": "Provider send() returns SendResult with phase field (pre_submit/submitted/ambiguous); only pre_submit failures and chain-definitive submitted failures are marked failed; ambiguous always goes to manual_hold",
"priority": "must"
},
{
"criterion": "After tx submission (status=submitted), confirm_tx polls/waits for confirmation; timeout goes to manual_hold, never auto-retry",
"priority": "must"
},
{
"criterion": "mark_payment_failed DB method accepts any send_phase value (records it for audit); the service layer enforces that ambiguous phase never calls mark_payment_failed",
"priority": "must"
},
{
"criterion": "Private keys never appear in DB columns, log messages, or admin chat tool responses",
"priority": "must"
},
{
"criterion": "payment_requests, wallet_registry, and payment_channel_routes tables are NOT in QUERYABLE_TABLES; dedicated query_payments tool redacts wallet addresses",
"priority": "must"
},
{
"criterion": "Admin controls include all required operations: hold_payment, release_payment (only exit from manual_hold), retry_payment (only from failed), cancel_payment, check_payment_status (read-only chain check)",
"priority": "must"
},
{
"criterion": "release_payment is the only path out of manual_hold \u2014 admin must explicitly declare confirmed, failed, or keep holding",
"priority": "must"
},
{
"criterion": "retry_payment only works from failed status \u2014 submitted and manual_hold states are blocked from direct retry",
"priority": "must"
},
{
"criterion": "Unique partial index prevents two active (non-failed, non-cancelled) payments for the same producer + producer_ref + is_test combination",
"priority": "must"
},
{
"criterion": "On bot restart, recover_inflight correctly resolves: processing/no-tx-sig \u2192 requeue, processing/ambiguous \u2192 hold, submitted/tx-sig \u2192 check chain \u2192 confirm/fail/hold",
"priority": "must"
},
{
"criterion": "Restart-safe Discord confirmation: PaymentConfirmView uses timeout=None with payment_id-derived custom_id; cog_load calls bot.add_view() for each pending_confirmation payment",
"priority": "must"
},
{
"criterion": "get_active_grants_for_applicant includes payment_requested in active statuses; assessor prompt updated to match",
"priority": "must"
},
{
"criterion": "Grants cog produces payment requests (test then final) instead of calling solana_client directly; grant status flow uses payment_requested and paid",
"priority": "must"
},
{
"criterion": "Grants queries payment ledger by (producer='grants', producer_ref=thread_id, is_test) \u2014 no single payment_ref column needed",
"priority": "must"
},
{
"criterion": "Admin agent.py system prompt tool catalog updated with all payment tools AND payment route tools so they are reachable from admin chat",
"priority": "must"
},
{
"criterion": "Test payment amount is a fixed global SOL amount (PAYMENT_TEST_AMOUNT_SOL env var, e.g. 0.000001 SOL), set directly as amount_token; price lookup is skipped; amount_usd and token_price_usd are None for test payments",
"priority": "must"
},
{
"criterion": "request_payment() uses keyword-only parameters with all required params before optional ones; amount_usd is required for is_test=False and ignored for is_test=True",
"priority": "must"
},
{
"criterion": "PaymentCog calls producer cog via bot.get_cog() on terminal payment events; GrantsCog.handle_payment_result() handles test-confirmed \u2192 enqueue-real, final-confirmed \u2192 mark-paid, failed \u2192 post-error, manual_hold \u2192 post-hold-notice",
"priority": "must"
},
{
"criterion": "All new unit tests pass (pytest tests/test_payment_service.py)",
"priority": "must"
},
{
"criterion": "Full pytest suite passes with no regressions",
"priority": "must"
},
{
"criterion": "PaymentProvider ABC has exactly: send (returns SendResult), confirm_tx, check_status, get_token_price_usd, token_name",
"priority": "should"
},
{
"criterion": "Worker loop follows sharing_cog pattern: @tasks.loop, claim batch, sequential process, env-configurable interval and batch size",
"priority": "should"
},
{
"criterion": "New files stay under ~300 lines each; payment_service.py may be up to ~400 given the state machine complexity",
"priority": "should"
},
{
"criterion": "Test and final payment flows are distinct: is_test flag on payment_requests, test payments auto-confirm with confirmed_by='auto'",
"priority": "should"
},
{
"criterion": "Manual staging smoke test: configure payment route via admin chat, then full grant \u2192 test-payment \u2192 auto-confirm \u2192 final-payment \u2192 button confirm \u2192 confirmed flow",
"priority": "info"
},
{
"criterion": "Manual staging smoke test: verify fallback to source thread when no payment route is configured",
"priority": "info"
},
{
"criterion": "Manual staging test: kill bot mid-payment, restart, verify recovery and button re-registration",
"priority": "info"
},
{
"criterion": "Manual staging test: admin chat route CRUD + hold/release/retry/cancel/status cycle",
"priority": "info"
}
],
"assumptions": [
"v1 targets native SOL transfers only \u2014 SPL token support (USDC etc.) is a future extension, but the provider abstraction accommodates it without code changes.",
"The existing SolanaClient class remains unchanged; SolanaProvider is a thin adapter wrapping it.",
"grant_applications columns (payment_status, wallet_address, tx_signature, sol_amount, sol_price_usd) are left in the table for historical records but new payments flow through payment_requests exclusively.",
"SQL reference scripts go in sql/ following the social_publications.sql pattern. Formal migrations in supabase/migrations/ can be derived from these.",
"The Discord confirmation flow uses persistent views (timeout=None + bot.add_view) for restart safety. This is a new pattern for this repo \u2014 no existing code uses bot.add_view.",
"Test payments send real dust on-chain to validate the wallet. The test amount is a fixed global SOL amount (env var), not USD-derived.",
"The payment worker runs in the same bot process as the sharing worker \u2014 no separate deployment.",
"Admin chat tools follow the existing Anthropic tool-call format used by other tools in tools.py, and the hand-written tool catalog in agent.py must be updated for new tools to be reachable.",
"Grants queries the payment ledger by (producer, producer_ref, is_test) to find both test and final payments \u2014 no payment_ref column on grant_applications.",
"wallet_registry stores one wallet per user per chain per guild. Multiple wallets per user would require a schema change.",
"payment_channel_routes follows the same hierarchical resolution as social_channel_routes: exact channel \u2192 parent channel \u2192 guild default. The route_config JSONB stores confirm/notify destination channel/thread IDs.",
"When no payment route is configured for a guild/channel/producer combination, grants falls back to the source thread as both confirmation and notification destination. This is acceptable for v1 \u2014 admins can configure a dedicated payments channel via admin chat when desired."
],
"delta_from_previous_percent": 22.59,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-002",
"concern": "Payment routing: the revision persists routing columns, but it still never defines a configuration source or resolver for those routes, and the concrete grants example hardcodes the source thread again.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-1",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the revised routing story against the locked user note and the concrete grants example, and the plan still stops short of a real route-configured solution: Step 8 now passes routing columns into the ledger, but the only concrete caller example still hardcodes confirm_channel_id=thread.parent_id, confirm_thread_id=thread.id, notify_channel_id=thread.parent_id, and notify_thread_id=thread.id, so the promised payments-channel/forum override is still not designed end to end.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-2",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the test-payment amount handling against the locked 'fixed tiny global amount' decision and found the plan internally inconsistent: Step 5 models the test amount as amount_usd, and Step 9 proposes PAYMENT_TEST_AMOUNT_USD, which would make the on-chain SOL amount vary with price instead of staying fixed if the user's intent was a fixed dust transfer on Solana.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: Checked the revised request_payment(...) signature in Step 5 and found it is not valid Python as written, because required parameters (confirm_channel_id, notify_channel_id) appear after defaulted parameters (recipient_discord_id=None, wallet_id=None); this is a concrete implementation error in the plan text, not just a stylistic issue.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: Checked the revised payment state-machine contracts and found an internal contradiction: Step 2 says mark_payment_failed(...) is only callable for send_phase='pre_submit', but Step 5 and recovery logic still call it for chain-definitive failures after submission (send_phase='submitted'), so the DB API contract and the service flow cannot both be true.",
"status": "addressed",
"severity": "significant"
},
{
"id": "conventions",
"concern": "Payments integration: the grants handoff still mixes notification-handler, listener, and callback language without choosing one concrete repo-native integration pattern.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verification-1",
"concern": "Is there convincing verification for the change?: Checked the revised test plan against the repo's risk profile and the main gap remains: the plan still centers verification on one new file, but the riskiest regressions are in grants integration, cog startup wiring in , and the producer-specific transition from successful test payment to queued final payment.",
"status": "open",
"severity": "minor"
},
{
"id": "verification-2",
"concern": "Is there convincing verification for the change?: Checked the restart-safe interaction claims against the proposed tests and found they are still not automated: the plan says to smoke-test button re-registration after restart, but it does not add even a lightweight unit test around , , or the registration path.",
"status": "open",
"severity": "minor"
},
{
"id": "criteria_quality-1",
"concern": "Are the success criteria well-prioritized and verifiable?: The routing criterion is still too weak for the actual user requirement: a build could satisfy 'Confirmation destinations are route-configured via confirm_channel_id/confirm_thread_id on payment_requests' merely by storing caller-supplied IDs, without implementing any real configuration source or override mechanism, so the gate can pass even if grants still hardcodes the source thread.",
"status": "addressed",
"severity": "significant"
},
{
"id": "criteria_quality-2",
"concern": "Are the success criteria well-prioritized and verifiable?: There is still no criterion that pins down the test-payment amount semantics despite that being user-locked; the plan can technically pass all listed checks while using a price-derived USD test amount instead of a fixed tiny global on-chain amount.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-007",
"concern": "Payment state machine: the revised DB API says is only for , but the service flow still uses it for definitive failures after submission.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-008",
"concern": "Test payment amount: the revision says the test payment is a fixed tiny global amount, but it models that amount as USD, which makes the on-chain SOL transfer variable.",
"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?: Checked the wider routing problem across the repo and found the plan still scoped it too narrowly: routed behavior in this codebase normally comes with a resolver plus admin-managed config surface ( and the CRUD tools), but the payment plan adds only per-request channel IDs and no equivalent payment-route lookup or configuration path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked the remaining supporting infrastructure for route-configured destinations and found it still missing: the plan does not touch , add a payment-route table, or define admin tooling comparable to , so there is still no actual configuration source for the route values the ledger is supposed to store.",
"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?: Traced the live grants caller again at and found the revised plan still lacks the crucial caller-side resolution step: the new API accepts confirm and notify targets, but the only concrete grants example still derives those directly from the current thread rather than from any configurable route source, so the caller handling remains incomplete for the user's override requirement.",
"status": "addressed",
"severity": "significant"
},
{
"id": "conventions-1",
"concern": "Does the approach match how the codebase solves similar problems?: Compared the cross-cog handoff language to the rest of the repo and the same maintainability gap remains: the revision still alternates between 'notification handler', 'PaymentCog listens', and callback-style wording for the grants follow-up path instead of choosing one concrete repo-native integration pattern such as direct bot-attached service usage or explicit cog references wired in .",
"status": "open",
"severity": "minor"
},
{
"id": "conventions-2",
"concern": "Does the approach match how the codebase solves similar problems?: Compared the routing design to existing routed features and found the revision diverges from established practice: this codebase already represents 'route-configured destination' with a resolver plus admin CRUD table ( and tools), but the payment plan substitutes raw channel IDs on each row without adding an analogous payment-route abstraction.",
"status": "open",
"severity": "minor"
}
]
code
Known accepted debt grouped by subsystem:
{
"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/build-a-fail-closed-20260409-2327/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.
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.
'failed'
'manual_hold'
'cancelled'
is_test boolean NOT NULL DEFAULT false — distinguishes test-payment from final
attempt_count integer NOT NULL DEFAULT 0
tx_signature text — set after chain submission
send_phase text — 'pre_submit', 'submitted', 'ambiguous' — records what happened during last send attempt, drives whether auto-retry is safe
last_error text
retry_after timestamptz
hold_reason text — human note when in manual_hold
confirmed_by text — Discord user ID who confirmed (or 'auto' for test payments)
confirm_channel_id bigint — where to post the confirmation button/message
confirm_thread_id bigint — optional thread within confirm channel
notify_channel_id bigint — where to post payment result notifications
notify_thread_id bigint — optional thread within notify channel
metadata jsonb NOT NULL DEFAULT '{}'::jsonb — producer-specific data bag (e.g. grant details for the notification message)
created_at, updated_at, completed_at timestamptz
deleted_at timestamptz — soft delete
Key indexes:
idx_payment_requests_due_queue on (retry_after, created_at) WHERE status = 'queued' AND deleted_at IS NULL
idx_payment_requests_producer on (producer, producer_ref)
Unique partial index on (producer, producer_ref, is_test) WHERE status NOT IN ('failed', 'cancelled') — prevents double-enqueue of active payments
Mirror claim_due_social_publications exactly (sql/social_publications.sql:93-126) — CTE with FOR UPDATE SKIP LOCKED, atomically sets status = 'processing', increments attempt_count.
RLS & permissions: Both tables get RLS enabled, anon/authenticated revoked. Neither table is added to QUERYABLE_TABLES.
Triggers:updated_at trigger on both tables, same pattern as social_publications.sql:3-11.
Note on schema placement: Follow the sql/ directory pattern used by social_publications.sql. This is the live reference-script convention. The supabase/migrations/ directory also exists for formal migrations but the reference script in sql/ is the authoritative template.
Call provider.confirm_tx(result.signature) — this polls/waits for confirmation (wraps SolanaClient.confirm_tx which calls client.confirm_transaction).
'confirmed' → mark_payment_confirmed(). If wallet_id present, call mark_wallet_verified(wallet_id).
'failed' → mark_payment_failed(payment_id, 'chain rejected', send_phase='submitted') — note: even though status is 'failed', the send_phase='submitted' means admin must be cautious.
'timeout' → mark_payment_manual_hold(payment_id, reason='confirmation timed out after submission') — fail closed, never auto-retry.
Returns result dict with status + tx_sig.
recover_inflight() method — called on startup:
Fetch all status IN ('processing', 'submitted').
For 'processing' with no tx_signature: crashed before send → requeue (safe because nothing was submitted).
For 'processing' with send_phase='ambiguous': crashed after ambiguous send → manual_hold.
For 'submitted' with tx_signature: check chain status via provider.check_status() (one-shot, with search_transaction_history=True as the existing client does at solana_client.py:133):
'confirmed' → mark confirmed.
'failed' → mark failed.
'not_found' → mark manual_hold — fail closed. (This is recovery, not immediate post-submit, so not_found is genuinely ambiguous here.)
get_pending_confirmations(guild_ids) method — returns pending_confirmation payments for button re-registration.
- query_payments — search payment ledger. Wallet addresses are redacted. Filters: payment_id, producer, producer_ref, status, is_test.
- check_payment_status — re-check on-chain status for a submitted/held payment. Read-only.
- hold_payment — freeze a payment to manual_hold with a reason.
- release_payment — resolve a manual_hold: confirmed (went through), failed (did not), or hold (keep holding).
- retry_payment — requeue a failed payment for another attempt. Only works from failed status.
- cancel_payment — cancel a pending/queued/failed/held payment.
- query_wallets — list registered wallets for a user.
Add tool definitions to TOOLS list and handler functions in tools.py.
Key safety: The state machine enforced by the DB handler methods means:
manual_hold → can only go to confirmed, failed, or stay on hold via release_payment
failed → can go to queued via retry_payment, or cancelled via cancel_payment
submitted → cannot be retried or cancelled directly; admin must wait or use hold_payment first
paid: set when the payment_cog notification reports the final (non-test) payment as confirmed.
Change get_active_grants_for_applicant() to include payment_requested in the active status list: .in_('status', ['reviewing', 'awaiting_wallet', 'payment_requested']).
This prevents duplicate grant applications while payment is in progress.
Change the active-grant description to: "Be VERY hesitant to approve someone who already has an open/active grant (status: reviewing, awaiting_wallet, payment_requested)."
Wire payment result callback: PaymentCog listens for confirmed/failed payments where producer='grants'. On confirmed final payment → update grant to paid, send thread message, archive. On failed → send thread message with admin mention.
producer_ref text NOT NULL — e.g. grant thread_id, links back to source
recipient_discord_id bigint — optional, links to wallet_registry
recipient_wallet text NOT NULL — Solana address (denormalized from registry or direct)
wallet_id UUID REFERENCES wallet_registry(wallet_id) — optional FK
amount_usd numeric — the requested USD amount (null for test payments)
amount_token numeric — for test payments: set directly from env; for real payments: computed from amount_usd at send time
token_price_usd numeric — spot price at send time (null for test payments)
chain text NOT NULL DEFAULT 'solana'
provider text NOT NULL DEFAULT 'solana_native'
status text NOT NULL DEFAULT 'pending_confirmation' CHECK in ('pending_confirmation', 'queued', 'processing', 'submitted', 'confirmed', 'failed', 'manual_hold', 'cancelled')
is_test boolean NOT NULL DEFAULT false — distinguishes test-payment from final
attempt_count integer NOT NULL DEFAULT 0
tx_signature text — set after chain submission
send_phase text — 'pre_submit', 'submitted', 'ambiguous' — records what happened during last send attempt
last_error text
retry_after timestamptz
hold_reason text — human note when in manual_hold
confirmed_by text — Discord user ID who confirmed (or 'auto' for test payments)
route_key UUID — FK to payment_channel_routes.id; the resolved route used, for audit
confirm_channel_id bigint — resolved destination for confirmation button
confirm_thread_id bigint — optional thread within confirm channel
notify_channel_id bigint — resolved destination for result notifications
notify_thread_id bigint — optional thread within notify channel
metadata jsonb NOT NULL DEFAULT '{}'::jsonb — producer-specific data bag
created_at, updated_at, completed_at timestamptz
deleted_at timestamptz — soft delete
Key indexes:
idx_payment_requests_due_queue on (retry_after, created_at) WHERE status = 'queued' AND deleted_at IS NULL
idx_payment_requests_producer on (producer, producer_ref)
Unique partial index on (producer, producer_ref, is_test) WHERE status NOT IN ('failed', 'cancelled') — prevents double-enqueue of active payments
Mirror claim_due_social_publications exactly (sql/social_publications.sql:93-126) — CTE with FOR UPDATE SKIP LOCKED, atomically sets status = 'processing', increments attempt_count.
RLS & permissions: All three tables get RLS enabled, anon/authenticated revoked. None are added to QUERYABLE_TABLES.
Triggers:updated_at trigger on all tables, same pattern as social_publications.sql:3-11.
Note on schema placement: Follow the sql/ directory pattern used by social_publications.sql. This is the live reference-script convention. The supabase/migrations/ directory also exists for formal migrations but the reference script in sql/ is the authoritative template.
cancel_payment(payment_id, guild_id) — set status='cancelled'. Only from pending_confirmation, queued, failed, or manual_hold.
get_inflight_payments_for_recovery() — fetch status IN ('processing', 'submitted') for restart recovery
get_pending_confirmation_payments(guild_ids) — fetch status='pending_confirmation' for button re-registration on restart
Pattern: Each method follows existing db_handler conventions — Supabase client calls, guild_id scoping, error logging, return dict or None.
amount_token
amount_usd / token_price_usd
For test payments: amount_token is already set on the record; skip price lookup.
Call provider.send(recipient_wallet, amount_token) → get SendResult.
If result.phase == 'pre_submit': definitive pre-send failure → mark_payment_failed(payment_id, result.error, send_phase='pre_submit'). This payment can be retried via admin.
If result.phase == 'ambiguous': post-send ambiguity → mark_payment_manual_hold(payment_id, reason=f"Ambiguous send error: {result.error}"). Never mark failed, never auto-retry.
If result.phase == 'submitted': tx was broadcast.
Immediately mark_payment_submitted(payment_id, result.signature, amount_token, token_price_usd, send_phase='submitted') — write tx_sig to DB before doing anything else.
Call provider.confirm_tx(result.signature) — this polls/waits for confirmation.
'confirmed' → mark_payment_confirmed(). If wallet_id present, call mark_wallet_verified(wallet_id).
'failed' → mark_payment_failed(payment_id, 'chain rejected tx', send_phase='submitted') — chain definitively reported failure, so this is safe to mark failed. The send_phase='submitted' is recorded for admin visibility.
'timeout' → mark_payment_manual_hold(payment_id, reason='confirmation timed out after submission') — fail closed, never auto-retry.
Returns result dict with status + tx_sig.
State machine safety summary: The service layer enforces the invariant: only pre_submit and chain-definitive submitted failures → failed. Ambiguous phase and confirmation timeout → manual_hold. The DB mark_payment_failed() method accepts any send_phase (it records it for audit) but is never called by the service for ambiguous states.
recover_inflight() method — called on startup:
Fetch all status IN ('processing', 'submitted').
For 'processing' with no tx_signature: crashed before send → requeue (safe because nothing was submitted).
For 'processing' with send_phase='ambiguous': crashed after ambiguous send → manual_hold.
For 'submitted' with tx_signature: check chain status via provider.check_status() (one-shot, with search_transaction_history=True as the existing client does at solana_client.py:133):
'confirmed' → mark confirmed.
'failed' → mark failed (chain definitively rejected).
'not_found' → mark manual_hold — fail closed. (This is recovery, not immediate post-submit, so not_found is genuinely ambiguous.)
get_pending_confirmations(guild_ids) method — returns pending_confirmation payments for button re-registration.
producer_cog_map = {'grants': 'GrantsCog'}
This is the single concrete pattern for producer notification — no listeners, no custom events, no callbacks. Direct method call via bot.get_cog().
Test payment auto-confirm: For is_test=True payments, the producer calls payment_service.confirm_payment(payment_id, confirmed_by='auto') immediately after request — no Discord button needed. A notification is still sent to the notification target when the test completes.
pending_confirmation
queued
failed
manual_hold
query_wallets(discord_user_id?, guild_id?) — lists registered wallets with verified status.
Updatesrc/features/admin_chat/agent.py system prompt (agent.py:33-52) to include all new tools in the hand-written tool catalog. Add under two new headings:
Payment Routes:
code
- list_payment_routes — list configured payment routes for a guild/producer.
- create_payment_route — create a payment route with confirm/notify destinations.
- update_payment_route — update an existing payment route.
- delete_payment_route — delete a payment route.
Payments:
code
- query_payments — search payment ledger. Wallet addresses are redacted. Filters: payment_id, producer, producer_ref, status, is_test.
- check_payment_status — re-check on-chain status for a submitted/held payment. Read-only.
- hold_payment — freeze a payment to manual_hold with a reason.
- release_payment — resolve a manual_hold: confirmed (went through), failed (did not), or hold (keep holding).
- retry_payment — requeue a failed payment for another attempt. Only works from failed status.
- cancel_payment — cancel a pending/queued/failed/held payment.
- query_wallets — list registered wallets for a user.
Add tool definitions to TOOLS list and handler functions in tools.py.
Key safety: The state machine enforced by the DB handler methods means:
manual_hold → can only go to confirmed, failed, or stay on hold via release_payment
failed → can go to queued via retry_payment, or cancelled via cancel_payment
submitted → cannot be retried or cancelled directly; admin must wait or use hold_payment first
Re-resolve route (same resolve_payment_destinations() call) for the real payment.
Send PaymentConfirmView button to the confirmation target channel/thread.
If payment_record['is_test'] == True and payment_record['status'] == 'failed': test failed → post error to thread, admin can retry via admin chat.
If payment_record['is_test'] == False and payment_record['status'] == 'confirmed': final payment confirmed → update grant to paid, archive thread.
If payment_record['is_test'] == False and payment_record['status'] == 'failed': final payment failed → post error to thread with admin mention.
If payment_record['status'] == 'manual_hold': post hold notice to thread with admin mention.
Replace_recover_inflight_payments() (grants_cog.py:87-193) — remove entirely. Recovery is now handled by PaymentCog.cog_load → payment_service.recover_inflight().
Updategrant_applications status flow:
Old columns (payment_status, wallet_address, sol_amount, sol_price_usd, tx_signature) left in table for historical data. New payments flow through payment_requests exclusively.
payment_requested: set when payment_service.request_payment() succeeds for the test payment. No payment_ref column needed — the payment ledger is queried by (producer='grants', producer_ref=thread_id).
paid: set when handle_payment_result receives confirmed final (non-test) payment.
Change get_active_grants_for_applicant() to include payment_requested in the active status list: .in_('status', ['reviewing', 'awaiting_wallet', 'payment_requested']).
Change the active-grant description to: "Be VERY hesitant to approve someone who already has an open/active grant (status: reviewing, awaiting_wallet, payment_requested)."
Test request_payment signature: amount_usd is required for is_test=False (raises ValueError if None), optional for is_test=True.