Enterprise-grade Autonomous Revenue Recovery Infrastructure for India's Fintech & Recurring Payments Ecosystem.
Chakra is an autonomous revenue recovery engine built specifically for recurring Indian payment flows, subscription mandates, invoices, and checkout drop-offs. Unlike legacy dunning software that retries transactions blindly on naive timersβcausing customer harassment, bank card blacklisting, and regulatory non-complianceβChakra operates as an intelligent, safety-gated decision pipeline.
- AI Proposes: LLMs (Google Gemini) analyze ambiguous failure codes without ever having direct authority to execute.
- Policy Decides: The Non-Overridable Safety Gate deterministically enforces RBI e-mandate rules, network retry caps, and intervention budgets.
- Executor Acts: Approved actions (retries, payment links, voice notes, reminders) are dispatched with strict idempotency.
- Provider Confirms: Money is never assumed to be recovered when a link is created or a retry scheduled. Only provider-verified capture registers as
RECOVERED. - Chakra Measures: Mathematical invariants ensure that revenue recovered never exceeds revenue attempted, and every rupee is traceable via tamper-proof audit trails.
Chakra strictly processes events through an 11-stage auditable conceptual pipeline:
flowchart TD
subgraph S1["1. INGESTION & CONTEXT"]
RAR["Revenue at Risk"] --> ES["Event Sources\n(Webhooks, Invoices, Orders)"]
ES --> EC["Event-Specific Context\n(Failure reason, mandate ID, overdue days)"]
EC --> CB["Context Builder"]
CB --> RC["RecoveryCase\n(Unified State Object)"]
end
subgraph S2["2. TRIAGE & DIAGNOSIS"]
RC --> TE["Triage Engine\n(Deterministic Diagnosis)"]
TE -. Ambiguous Cases Only .-> AIF["AI Fallback (Google Gemini)\n[PII-Redacted, Safe Structured Output]"]
TE --> PR["Mandate / Policy Router"]
AIF --> PR
end
subgraph S3["3. COMPLIANCE & SAFETY FIREWALL"]
PR --> CD["Candidate Decision Proposed"]
CD --> SG{{"NON-OVERRIDABLE SAFETY GATE\n(RBI AFA Limits, Network Caps, Budgets, Fraud Checks)"}}
SG -- Blocked --> BLK["Status: BLOCKED\n(Audit Reason Logged)"]
SG -- Escalated --> ESC["Status: ESCALATED\n(Human Ops Routing)"]
SG -- Allowed / Modified --> AD["Approved Recovery Decision\n(e.g., AFA_PAYMENT_LINK, RETRY_NOW)"]
end
subgraph S4["4. EXECUTION & VERIFICATION"]
AD --> RE["Recovery Executor\n(Idempotency Guarded)"]
RE --> PA["Provider Adapter\n(Razorpay Test Mode / Synthetic Gateway)"]
PA --> OE["Outcome Evaluator\n(Zero False-Recovery Verification)"]
OE --> AT["Append-Only Audit Trail (JSONL)"]
OE --> MA["Metrics Aggregator\n(Invariant-Enforced Accounting)"]
end
style SG fill:#ef4444,stroke:#7f1d1d,stroke-width:2px,color:#fff
style AIF fill:#8b5cf6,stroke:#4c1d95,stroke-width:2px,color:#fff
style OE fill:#10b981,stroke:#047857,stroke-width:2px,color:#fff
style RC fill:#3b82f6,stroke:#1d4ed8,stroke-width:2px,color:#fff
- Revenue at Risk: The raw loss potential detected across payment attempts, overdue invoices, and dropped checkouts.
- Event Sources: Real-time webhooks from gateways (Razorpay, mock providers), subscription billing events, and invoice feeds.
- Context Builder: A single unified builder that ingests event-specific context (failure reason, payment method, overdue days, mandate ID, retry counts) and normalizes it into a consistent format.
- RecoveryCase: The authoritative domain model encapsulating customer state, transaction amount, current lifecycle state, and risk flags.
- Triage Engine: Evaluates failure codes with sub-millisecond deterministic rules. Classifies issues into transient failures, hard declines, customer friction, or compliance blocks.
- AI Fallback (Google Gemini): Triggered only when triage encounters ambiguous, unrecognized error codes or multi-cause failures. PII is redacted prior to inference, and the LLM produces strictly typed structured decisions (
reason,confidence,recommended_action). Chain-of-thought is never logged or exposed. - Mandate / Policy Router: Evaluates case type, mandate status, and customer history to formulate a candidate
RecoveryDecision. - Non-Overridable Safety Gate: The central policy enforcer. Evaluates candidate actions against mandatory regulatory rules (RBI e-mandate directives, Visa/Mastercard retry caps, monthly intervention limits, fraud indicators). Can permit, override, or outright block any action.
- Recovery Actions: Concrete interventions:
RETRY_NOW,RETRY_LATER,PAYMENT_LINK,AFA_PAYMENT_LINK,VOICE_RECOVERY,REMINDER,ESCALATE, orBLOCK. - Recovery Executor: Dispatches approved actions against payment providers using cryptographic idempotency keys.
- Outcome Evaluator: Validates real provider feedback. Translates provider HTTP/webhook signals into verified outcomes without assuming success.
- Audit Trail + Metrics: Records structured audit events in append-only JSONL files and aggregates mathematical metrics verified by rigorous invariants.
The Safety Gate is the most critical component in Chakra. While machine learning and heuristic models propose candidate actions, the Safety Gate has sole, non-overridable authority to reject or modify actions.
| Rule Name | Trigger Condition | Enforcement Action | Regulatory / Business Rationale |
|---|---|---|---|
| Hard Revocation Check | mandate_state == REVOKED |
BLOCK | Debiting a revoked mandate violates RBI circulars and incurs high bank penalty fees. |
| Fraud & Risk Block |
fraud_flag == True or high-risk signal |
BLOCK | Immediate stop to prevent chargebacks and merchant account suspension. |
| Network Retry Caps | Exceeded network retry limit (e.g. Visa 4 retries / 16 days, Mastercard 10 / 30 days) | BLOCK | Violating card scheme rules results in severe non-compliance fines. |
| Intervention Budget | Customer has received |
BLOCK / ESCALATE | Prevents dunning spam, brand erosion, and customer harassment. |
| Idempotency Guard | Duplicate event received on the same day for the same transaction | BLOCK | Guarantees zero double-debit incidents under race conditions or duplicate webhooks. |
| RBI AFA Enforcement | Transaction amount |
CONVERT TO AFA_PAYMENT_LINK | Reserve Bank of India mandate requires Additional Factor of Authentication (OTP/3DS) for high-value transactions. |
Important
Safety Guarantee: No LLM recommendation or routing policy can ever bypass the Safety Gate. If an LLM recommends RETRY_NOW on an account with a revoked mandate, the Safety Gate intercepts and deterministically sets the status to BLOCKED.
Every RecoveryCase in Chakra traverses an explicit, observable lifecycle:
stateDiagram-v2
[*] --> RECEIVED
RECEIVED --> TRIAGED
TRIAGED --> SAFETY_CHECK
SAFETY_CHECK --> BLOCKED: Rule Violation (Fraud / Mandate Revoked)
SAFETY_CHECK --> ESCALATED: High Churn / Human Review Required
SAFETY_CHECK --> ELIGIBLE: Passed All Safety Checks
ELIGIBLE --> INTERVENTION_ATTEMPTED: Action Dispatched
INTERVENTION_ATTEMPTED --> RECOVERY_PENDING: Payment Link Created / Retry Scheduled / Voice Note Sent
INTERVENTION_ATTEMPTED --> RECOVERED: Provider Confirmed Capture (Immediate Retry)
INTERVENTION_ATTEMPTED --> FAILED: Terminal Failure
RECOVERY_PENDING --> RECOVERED: Webhook Confirms Payment Captured
RECOVERY_PENDING --> FAILED: Link Expired / Max Delay Exceeded
RECOVERED --> [*]
FAILED --> [*]
BLOCKED --> [*]
ESCALATED --> [*]
In amateur recovery systems, generating an SMS payment link or deferring a retry is prematurely counted as "recovered revenue". Chakra strictly rejects this practice.
- Payment Link Created? Status:
RECOVERY_PENDING. Revenue Recovered: βΉ0. - Voice Note Generated? Status:
RECOVERY_PENDING. Revenue Recovered: βΉ0. - Retry Scheduled for +24 Hours? Status:
RECOVERY_PENDING. Revenue Recovered: βΉ0. - Only Provider-Confirmed Success: Revenue is credited to
revenue_recovered_inronly when the provider returnsstatus == "captured"oroutcome == "success".
Chakra exposes 8 discrete intervention mechanisms tailored to recovery scenarios:
| Intervention | Typical Trigger | Mechanism | Observable State |
|---|---|---|---|
RETRY_NOW |
Transient network error / bank gateway timeout under retry caps | Immediate synchronous retry request to payment provider |
RECOVERED or FAILED
|
RETRY_LATER |
Insufficient funds on active mandate | Schedules execution after a designated delay (e.g. 24h/48h aligned with salary cycles) | RECOVERY_PENDING |
PAYMENT_LINK |
Expired card, soft decline, or checkout abandonment | Generates a secure, branded alternative payment link with custom expiry | RECOVERY_PENDING |
AFA_PAYMENT_LINK |
Amount |
Generates an OTP/3DS-mandated payment link satisfying RBI e-mandate guidelines | RECOVERY_PENDING |
VOICE_RECOVERY |
High-value subscription overdue by 7+ days | Generates a contextual Hinglish conversational voice note and dispatches link | RECOVERY_PENDING |
REMINDER |
B2B receivable nearing due date or promise-to-pay window | Issues non-intrusive payment reminder artifact | RECOVERY_PENDING |
ESCALATE |
Multiple pre-debit alerts ignored (churn risk) or agent uncertainty | Routes directly to human operations desk with annotated triage context | ESCALATED |
BLOCK |
Revoked mandate, confirmed fraud flag, or network cap reached | Halts all automated recovery attempts immediately | BLOCKED |
The Chakra Command Center is a purpose-built, high-density operations console designed with a dark financial infrastructure aesthetic (not a generic SaaS template).
-
Page 1: Overview
-
Financial Recovery Funnel: Real-time visual pipeline from Revenue At Risk
$\rightarrow$ Revenue Attempted$\rightarrow$ Revenue Recovered. - Headline Metrics Cards: Revenue At Risk (βΉ), Revenue Attempted (βΉ), Revenue Recovered (βΉ), Recovery Rate (%), Payments Recovered, Blocked, Escalated, and Pending counts.
- Intervention Breakdown Table: Complete real-time audit showing attempted, succeeded, failed, and pending figures per intervention.
- Case Type Breakdown Table: Performance partitioned across Payment Failures, Subscriptions, Checkout Abandonment, Receivables, and Promise-to-Pay.
- Synthetic Benchmark Label: Benchmark figures are explicitly labeled: "Synthetic 120-case benchmark β not production Razorpay data."
-
Financial Recovery Funnel: Real-time visual pipeline from Revenue At Risk
-
Page 2: Live Recovery Feed
- Real-time operational card feed reflecting incoming cases.
- Visual status badges:
-
βRECOVERED (Green) -
β·RECOVERY_PENDING (Yellow) -
π‘BLOCKED (Red) -
βESCALATED (Orange)
-
- One-click navigation to inspect any case in the Decision Explorer.
-
Page 3: Decision Explorer / Case Detail (Primary Inspection Screen)
- Complete 8-stage interactive visual breakdown:
- EVENT: Sanitized raw payload, amount, case ID, timestamp.
- CONTEXT: Customer profile, mandate state, failure history, risk indicators.
- TRIAGE: Classification category, confidence score (%), recommended action.
- AI FALLBACK: Transparent disclosure of Gemini LLM involvement. If not required, clearly displays "Deterministic policy path β AI fallback not required." (Chain-of-thought is never rendered).
- MANDATE ROUTER: Candidate policy applied and proposed action.
-
SAFETY GATE: Visually prominent check list (Mandate Active, Retry Cap, Budget, Fraud, Idempotency, AFA Threshold). Highlights
ALLOWED,AFA REQUIRED, orBLOCKED. - EXECUTOR: Dispatched action, provider target, and idempotency status.
- OUTCOME: Verified provider response and recovered revenue amount.
- Complete 8-stage interactive visual breakdown:
-
Page 4: Safety Center
- Dedicated regulatory control room showing live protection policies.
- Interactive visual exhibit:
$$\text{AI PROPOSED: RETRY_NOW} \longrightarrow \text{SAFETY GATE: MANDATE REVOKED} \longrightarrow \textbf{BLOCKED}$$ - Recent safety decisions audit log with rule triggers and reason codes.
-
Page 5: Audit Trail
- Chronological event stream with structured JSON inspector for all pipeline stages.
- PII-redacted payloads conforming to privacy standards.
-
Page 6: Live Demo / Event Simulator
- Controlled simulation panel to trigger synthetic revenue-at-risk events.
- Configurable parameters: Case Type, Amount (βΉ), Failure Reason, Mandate State (
ACTIVE/REVOKED), Churn Risk, and Fraud Risk. - Calls the real backend pipeline via
POST /api/demo/simulate(zero mock engines in the UI). - Animates the journey live from ingestion to final outcome.
-
Page 7: System Architecture Panel
- Live architectural visualization detailing the full 11-stage pipeline.
The following 4 scenarios demonstrate Chakra's core capabilities in live presentations:
-
Input: Amount:
βΉ2,499| Case Type:PAYMENT_FAILURE| Reason:insufficient_funds| Mandate:ACTIVE - Triage: Diagnosed as transient failure (confidence 98%).
-
Safety Gate: Mandate verified active, retry cap available
$\rightarrow$ ALLOWED. -
Action:
RETRY_NOWdispatched. -
Provider Result:
captured. -
Final State:
RECOVERED| Revenue Recovered: βΉ2,499.
-
Input: Amount:
βΉ8,999| Case Type:SUBSCRIPTION| Overdue:7 days| Mandate:ACTIVE -
Router: Selected
VOICE_RECOVERYfor multi-day overdue subscription. -
Safety Gate: Verified
$\rightarrow$ ALLOWED. - Action: Contextual Hinglish voice recovery note and payment link generated.
-
Final State:
RECOVERY_PENDING| Revenue Recovered: βΉ0 (Correctly uncredited until customer pays).
-
Input: Amount:
βΉ25,000| Case Type:PAYMENT_FAILURE| Mandate:REVOKED - Triage / Router: May propose recovery action.
-
Safety Gate: Intercepts revoked mandate
$\rightarrow$ HARD BLOCK. - Action: Blocked. No provider debit attempted.
-
Final State:
BLOCKED| Reason:MANDATE_REVOKED_NO_RETRY.
-
Input: Amount:
βΉ22,000| Case Type:PAYMENT_FAILURE| Mandate:ACTIVE -
Router: Proposes
RETRY_NOW. -
Safety Gate: Detects amount
$\ge βΉ15,000$ limit$\rightarrow$ OVERRIDE. -
Final Action: Converts to
AFA_PAYMENT_LINK. -
Final State:
RECOVERY_PENDINGwith compliant OTP link.
Chakra includes a rigorous benchmarking suite and invariant verification harness:
| Metric | Benchmark Result |
|---|---|
| Total Cases Processed | 120 |
| Revenue At Risk | βΉ3,560,390.86 |
| Revenue Attempted | βΉ2,299,207.07 |
| Revenue Recovered | βΉ1,950,019.64 |
| Revenue Recovery Rate | 54.77% |
| Interventions Attempted | 67 |
| Interventions Succeeded | 52 |
| Intervention Success Rate | 77.61% |
| Payments Blocked by Safety Gate | 13 (10.83%) |
| Payments Escalated to Ops | 36 (30.00%) |
Every benchmark execution programmatically validates three core invariants:
-
Revenue Hierarchy:
$\text{Revenue Recovered} \le \text{Revenue Attempted} \le \text{Revenue At Risk}$ -
Count Hierarchy:
$\text{Payments Recovered} \le \text{Interventions Succeeded} \le \text{Interventions Attempted} \le \text{Payments Processed}$ -
Partition Sum:
$\text{Payments Blocked} + \text{Payments Escalated} + \text{Payments Eligible} == \text{Payments Processed}$
Chakra is evaluated against an adversarial benchmark of 18 edge cases testing compliance rules:
- Standard insufficient funds retry
- AFA threshold exceedance (> βΉ15,000)
- First mandate transaction AFA requirement
- Fraud flag hard compliance block
- Revoked mandate hard compliance block
- Pre-debit alert churn escalation
- Network retry caps (Visa / Mastercard)
- High-value category limits (> βΉ100,000)
- Expired card alternative links
- Monthly customer intervention budget caps
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
System health check (database, Razorpay mode, Twilio, Gemini status) |
GET |
/api/metrics |
Returns full metrics report including by_intervention and invariant validations |
GET |
/api/audit |
Retrieves newest audit events from the append-only audit trail (?limit=100) |
GET |
/api/policy |
Public, non-secret recovery and regulatory policies for safety visualization |
GET |
/api/cases |
Lists active recovery cases from the database aggregate |
GET |
/api/cases/{id}/trace |
Returns complete, structured decision journey for a case (without CoT) |
POST |
/api/demo/simulate |
Triggers a synthetic recovery case through the real 6-stage backend pipeline |
POST |
/api/payments/orders |
Generates a Razorpay Test Mode or Synthetic checkout order |
POST |
/api/payments/verify |
Server-side signature verification for Razorpay checkout success |
POST |
/api/payments/abandon |
Handles checkout abandonment drop-off and triggers recovery workflow |
POST |
/api/payments/{id}/retry |
Requests a provider-managed retry attempt |
POST |
/webhooks/razorpay |
Ingests real or synthetic Razorpay webhook events with HMAC verification |
- Python 3.11+
- Node.js 18+ (optional, if running frontend via npm)
- Git
git clone https://github.com/RudraMalvankar/Chakra.git
cd Chakra
# Create virtual environment
python -m venv .venv
# Activate virtual environment
# On Windows:
.venv\Scripts\activate
# On Linux/macOS:
source .venv/bin/activate
# Install dependencies
pip install -r requirements.txtCopy .env.example to .env:
cp .env.example .envKey configuration parameters:
USE_MOCK_RAZORPAY=true: Runs Chakra with the built-in local synthetic payment gateway (default).RAZORPAY_KEY_ID&RAZORPAY_KEY_SECRET: (Optional) Connects Chakra to actual Razorpay Test Mode.GEMINI_API_KEY: (Optional) Enables Google Gemini fallback for ambiguous failures.
Terminal 1 β Backend Recovery Engine:
python -m uvicorn backend.app.main:app --host 0.0.0.0 --port 8000 --reloadTerminal 2 β Command Center Frontend:
cd frontend
python -m http.server 3000Open http://localhost:3000 in your browser to access the Chakra Command Center.
If testing mock gateway webhooks locally:
Terminal 1 β Synthetic Gateway:
python -m uvicorn mock-razorpay.main:app --host 0.0.0.0 --port 8001Terminal 2 β Backend Engine:
python -m uvicorn backend.app.main:app --host 0.0.0.0 --port 8000 --reloadTerminal 3 β Frontend Command Center:
cd frontend
python -m http.server 3000Execute the 120-case recovery benchmark:
python backend/scripts/run_demo.pyThis processes 120 mixed cases, evaluates the 18-case safety suite, checks all mathematical invariants, and outputs metrics_report.json and eval_report.json.
Run the complete regression and unit test suite:
python -m pytest -q backend/testsVerify complete Python compilation syntax:
python -m compileall -q backend mock-razorpayChakra/
βββ backend/
β βββ app/
β β βββ api/ # FastAPI route handlers
β β β βββ webhooks.py # Webhook ingestion & signature validation
β β β βββ receivables.py # B2B invoice recovery endpoints
β β β βββ escalations.py # Ops review & manual escalation handling
β β β βββ voice.py # Conversational voice recovery routes
β β βββ config.py # Central Pydantic settings & env management
β β βββ db/ # SQLAlchemy database sessions & migrations
β β βββ lib/ # Utilities, audit logger (JSONL), policy configs
β β βββ models/ # Domain models (RecoveryCase, PaymentState, etc.)
β β βββ schemas/ # Request & response validation schemas
β β βββ services/ # Core business logic services
β β βββ context_builder.py # Normalizes raw events to RecoveryCase
β β βββ triage.py # Deterministic triage engine
β β βββ llm.py # Google Gemini fallback service (PII redacted)
β β βββ mandate_router.py # Policy & mandate routing orchestrator
β β βββ safety_gate.py # Non-overridable compliance & safety firewall
β β βββ recovery_executor.py# Action execution dispatcher
β β βββ outcome_evaluator.py# Provider response verification
β β βββ metrics_aggregator.py# Invariant-checked metrics aggregation
β β βββ razorpay_client.py # Provider adapter (Test mode + synthetic)
β βββ scripts/ # CLI runners (run_demo.py, print_metrics.py)
β βββ tests/ # 160+ automated unit and integration tests
βββ frontend/ # Chakra Command Center
β βββ index.html # Single-page application entrypoint
β βββ app.jsx # React 18 dashboard with dark financial UI
βββ mock-razorpay/ # Standalone synthetic payment gateway
β βββ main.py # Mock API endpoints (payments, orders, links)
β βββ seed.py # Deterministic 120-case benchmark generator
βββ docs/ # Architecture & design documentation
βββ audit_log.jsonl # Append-only structured runtime audit trail
βββ metrics_report.json # Generated summary metrics & invariant verification
βββ eval_report.json # Generated 18-case safety accuracy report
βββ requirements.txt # Backend Python dependencies
- Open Render Dashboard β New + β Web Service β Connect your GitHub repository.
- Configure the build parameters:
- Name:
chakra-backend - Environment:
Python 3 - Region: Choose closest to your database (e.g.
OregonorFrankfurt) - Root Directory:
. - Build Command:
pip install -r requirements.txt - Start Command:
python -m uvicorn backend.app.main:app --host 0.0.0.0 --port $PORT - Health Check Path:
/health
- Name:
- Add Environment Variables in Render:
DATABASE_URL: Your Neon Postgres connection string (e.g.,postgresql://...)GEMINI_API_KEY: Your Google Gemini API keyCORS_ORIGINS:*DRY_RUN:falseUSE_MOCK_RAZORPAY:true(orfalsewhen connecting live Razorpay test keys)RAZORPAY_KEY_ID: (Optional) Your Razorpay test keyRAZORPAY_KEY_SECRET: (Optional) Your Razorpay test secret
- Click Deploy Web Service. Once live, copy your backend URL (e.g.
https://chakra-backend.onrender.com).
(Alternatively, use the included render.yaml Blueprint for 1-click infrastructure deployment).
- Open Vercel β Add New Project β Import your Chakra repository.
- Configure project settings:
- Framework Preset:
Vite - Root Directory: Click Edit and select
frontend - Build Command:
npm run build - Output Directory:
dist
- Framework Preset:
- Add Environment Variable:
VITE_API_BASE_URL: Your Render backend URL (e.g.,https://chakra-backend.onrender.com)
- Click Deploy.
- The included
frontend/vercel.jsonhandles client-side SPA routing rewrites automatically, ensuring sub-routes (/cases,/gateway,/escalations,/voice) work directly on refresh.
- The included
Chakra is fully containerized with production-grade Dockerfiles and a unified Compose configuration.
# Clone and enter directory
git clone https://github.com/RudraMalvankar/Chakra.git
cd Chakra
# (Optional) Copy and configure environment variables
cp .env.example .env
# Build and start all services in the background
docker compose up -d --build- Backend API & Docs: http://localhost:8001 / http://localhost:8001/docs
- Frontend Dashboard: http://localhost:5173
- Health Check: http://localhost:8001/health
The GitHub Actions CI/CD workflow automatically builds and publishes container packages on every push to main or release:
# Pull backend image
docker pull ghcr.io/rudramalvankar/chakra/chakra-backend:latest
# Pull frontend image
docker pull ghcr.io/rudramalvankar/chakra/chakra-frontend:latest- Software License: Apache 2.0.
- Benchmark Disclosure: All benchmarks provided in
metrics_report.jsonand demonstrated in the Command Center are derived from a synthetic 120-case deterministic seed. They demonstrate architectural correctness and recovery logic; they are not production Razorpay transaction records. - Financial Simulation Notice: When operated in default mode, Chakra connects to the internal
mock-razorpaygateway and does not process real monetary transactions.
Made by Rudra Malvankar
Β© 2026 Rudra Malvankar. All rights to the code remain with the author.