Skip to content
Neutron-0Public

About

ABC Bank is an intelligence and experience layer that dynamically adapts a customer's mobile banking interface based on transaction history, cash-flow pulse, life-stage signals, risk indicators, and interaction preferences — designed for Tier 1 to Tier 4, rural, and vernacular-first users across Bharat.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

92 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ABC Bank — Adaptive Banking for Bharat

AI-Powered Hyper-Personalized Banking Experience Layer for HackOut'26 at DA-IICT.

🏆 Top 12 Finalist at HackOut'26 (@ DA-IICT)
Team Name: VZEYA | Team Leader: Harsh Solanki | Team Members: Harsh Solanki (Backend), Panchal Lakshya (Frontend), Ubaid Khan (AI)
Demo / Project Name: ABC Bank (Adaptive Banking for Bharat)

"Instead of asking customers to learn their bank, make the bank learn the customer."

ABC Bank is an intelligence and experience layer that dynamically adapts a customer's mobile banking interface based on transaction history, cash-flow pulse, life-stage signals, risk indicators, and interaction preferences — designed for Tier 1 to Tier 4, rural, and vernacular-first users across Bharat.


🏆 Hackathon Recognition — Top 12 Selected Teams

Team VZEYA (Project: ABC Bank) was selected among the Top 12 Finalist Teams at HackOut'26 (DA-IICT):

📄 Download Official Shortlist PDF

# Team Name Team Leader Name Status
1 Zero Sum Patel Vedant Selected Finalist
2 Wowwsters Kashyap Vadher Selected Finalist
3 Outliers Jeevesh Bodhani Selected Finalist
4 Kinzz Kinjal Rantanpara Selected Finalist
5 Foxbat Viraj Patel Selected Finalist
6 ByteMe Tanmay Kanani Selected Finalist
7 Tech Titans Dhruvil Prajapati Selected Finalist
8 Tech Titans Savaliya Saumil Selected Finalist
9 Tatva Shaurya Doshi Selected Finalist
10 cosmiX Vedant Bhatt Selected Finalist
11 Ctrl Freaks Aum Pethani Selected Finalist
12 VZEYA (Our Team) Harsh Solanki Selected Finalist (Demo: ABC Bank)

Table of Contents


Project Overview

What It Does

ABC Bank is not a standalone banking application. It is an Intelligence and Experience Layer designed to sit on top of existing core banking infrastructure. It transforms raw, disparate banking data from 7 sources (Core Banking, UPI, SMS, CIBIL Bureau, BBPS, NCMC Metro, KYC) into a dynamically personalized mobile experience that adapts in real-time to each customer's financial reality.

The system ingests transaction data, extracts 32 single-pass features, detects behavioral/financial/lifecycle signals, classifies customers into one of 7 Bharat archetypes, scores product recommendations using a weighted multi-factor utility formula, enforces RBI-compliant ethical guardrails (DTI cap at 0.40), logs every decision in a SHA-256 cryptographic audit chain, and dynamically composes the mobile UI through a Server-Driven UI architecture — all in sub-millisecond latency.

The Problem It Solves

Traditional banking apps present the same static interface to every customer regardless of their financial situation. A customer in financial distress sees the same loan offers as a thriving saver. A daily metro commuter gets the same home screen as a rural farmer. ABC Bank solves this by:

  • Dynamically adapting the UI based on financial health (thriving, stable, tight, stress)
  • Suppressing predatory products when a customer is financially vulnerable (DTI > 0.40)
  • Providing vernacular AI assistance in Hindi, Gujarati, Hinglish, and English via on-device MiniCPM-5 SLM processing
  • Contextually surfacing relevant actions based on behavioral patterns (commute times, dining habits, cinema visits)
  • Operating offline-first with graceful degradation when connectivity is limited (2.5s timeout → edge processing)
  • Maintaining cryptographic audit trails for every AI decision via SHA-256 hash chains
  • Enforcing ethical lending by physically preventing credit product recommendations for customers in financial stress

Major Architectural Characteristics

Characteristic Implementation Impact
Server-Driven UI (SDUI) Backend dictates what the frontend renders via ExperienceConfig JSON AI team can modify personalization without touching React Native code
Deterministic AI All financial decisions use mathematical scoring (30% affordability + 30% lifecycle + 25% urgency + 15% archetype − risk penalty), never generative AI Zero hallucination risk in financial decisions
Contract-First Design JSON Schema Draft-07 contracts decouple AI, Backend, and Frontend Independent evolution of all three domains
Ethical AI Guardrails Hard-coded RBI DTI limits (>0.40 = suppress) and DPDP compliance baked into the engine Predatory lending physically impossible
Dual AI Architecture Backend deterministic math for decisions + On-device MiniCPM-5 INT4 SLM for vernacular NLP only Clear separation of concerns; SLM never makes financial decisions
Offline-First 2.5s timeout → edge ONNX processing on-device; DB offline → JSON seed fallback App continues working without connectivity
Cryptographic Auditability SHA-256 hash chain logs every AI decision and suppression for regulatory compliance Tamper-proof audit trail for RBI compliance
Dual Cadence Processing 14-day heavy macro batch + 0.162ms sub-millisecond micro-triggers Real-time responsiveness with periodic deep analysis

Design Principles

  • Privacy-First UX: Spending data operates as internal telemetry to calibrate protective services (auto-sweep FDs, tax savers, Safe-to-Spend buffer) — never displayed as an invasive lifestyle ledger
  • Strict Domain Ownership: Each team member owns their domain; cross-domain edits are forbidden (enforced via CODEOWNERS)
  • No Hallucination Risk: Generative AI (MiniCPM-5 SLM) handles only speech/language — never makes financial recommendations
  • Data Localization: All processing complies with RBI Data Localization Circular (2018) and DPDP Act 2023
  • Zero Banking Data Leakage: The on-device SLM never receives transaction history; it only verbalizes pre-computed trusted facts

Complete System Architecture

High-Level System Architecture

This diagram shows the complete runtime architecture — from end users through the mobile app, backend API, AI pipeline, database, and external data sources. Every component shown exists in the actual codebase.

flowchart TD
  subgraph Users["End Users"]
    U1["Tier 1-4 Urban Customers"]
    U2["Rural and Vernacular-First Users"]
    U3["Metro Commuters"]
  end

  subgraph MobileApp["React Native / Expo App (apps/frontend/)"]
    direction TB
    AppEntry["App.tsx -> ThemeProvider -> AppNavigator"]
    
    subgraph Screens["Feature Screens"]
      HomeScreen["AdaptiveHomeScreen<br/>(Dynamic Hero + Context Cards)"]
      ChatScreen["MitraChatScreen<br/>(Vernacular AI Chat)"]
      PayScreen["PaymentsScreen<br/>(Transfer + 1-Tap Pay)"]
      TxnScreen["TransactionsScreen<br/>(Combined Ledger)"]
      InsightScreen["InsightsScreen<br/>(Spending Analysis)"]
      ProfileScreen["ProfileScreen<br/>(Settings + KYC)"]
    end
    
    subgraph ClientServices["Client Services"]
      ZustandStore["Zustand Store<br/>(useCustomerStore)"]
      BankingAPI["BankingApi<br/>(fetch + 2.5s AbortController)"]
      EdgeEngine["MiniCPM5EdgeEngine<br/>(ONNX On-Device NLP)"]
      OnDeviceIntent["onDeviceIntentService<br/>(Rule-Based Fallback)"]
      i18n["i18n Module<br/>(EN / HI / GU)"]
      BiometricAuth["expo-local-authentication<br/>(Biometric + PIN)"]
    end
    
    AppEntry --> HomeScreen
    HomeScreen --> ZustandStore
    ZustandStore --> BankingAPI
    BankingAPI -.->|Timeout 2.5s| EdgeEngine
    ZustandStore --> OnDeviceIntent
  end

  subgraph BackendAPI["FastAPI Backend :8000 (apps/backend/)"]
    direction TB
    MainPy["main.py<br/>(CORS + Router Mount)"]
    
    subgraph APIRoutes["API Routes (routes.py) — 15+ Endpoints"]
      CustomerRoute["GET /customer/{id}"]
      ExperienceRoute["GET /experience/{id}"]
      PaymentRoute["POST /payments/transfer"]
      AuthRoute["POST /auth/pin/setup/verify"]
      CardRoute["GET/POST /cards/"]
      AssistantRoute["POST /assistant/intent/chat"]
      VoiceRoute["POST /voice/intent"]
      EventRoute["POST /events"]
      ScenarioRoute["POST /scenario/switch"]
    end
    
    subgraph Services["Service Layer"]
      StateService["StateService<br/>(Core Orchestrator)"]
      SafetyPolicy["SafetyPolicyFilter<br/>(Anti-Predatory Lending)"]
      BehaviorEngine["BehavioralEngine<br/>(Contextual Habits)"]
      ExpComposer["ExperienceComposer<br/>(State -> UI Config)"]
    end
    
    subgraph DataAccess["Data Access Layer"]
      DataLoader["DataLoader<br/>(DB -> JSON Fallback)"]
      CustomerRepo["CustomerRepository"]
      TxnRepo["TransactionRepository"]
      EventRepo["EventRepository"]
      ProductRepo["ProductRepository"]
    end
    
    MainPy --> CustomerRoute
    CustomerRoute --> StateService
    StateService --> DataLoader
    StateService --> ExpComposer
    ExpComposer --> SafetyPolicy
  end

  subgraph AIEngine["AI Intelligence Pipeline (ai/)"]
    direction TB
    
    subgraph Ingestion["Data Ingestion"]
      Harmonizer["harmonizer.py<br/>(MD5 Dedup + ISO Parse)"]
    end
    
    subgraph FeatureExt["Feature Extraction"]
      Extractor["extractor.py<br/>(50/30/20 Rule + 32 Metrics)"]
      SpendAnalyzer["spend_analyzer.py<br/>(9-Category Breakdown)"]
      Forecaster["forecaster.py<br/>(30-Day Runway)"]
    end
    
    subgraph SignalDet["Signal Detection"]
      BehavioralSig["behavioral.py<br/>(Commute, Dining, Cinema)"]
      FinancialSig["financial.py<br/>(DTI, Risk, Savings Decline)"]
      LifecycleSig["lifecycle.py<br/>(Medical, Marriage, Job Change)"]
    end
    
    subgraph Personalization["Personalization Engine"]
      StateGenerator["generator.py<br/>(Dual Cadence Controller)"]
      Scorer["scorer.py<br/>(Multi-Factor Utility)"]
      ComplianceFilter["compliance.py<br/>(RBI DTI + DPDP)"]
      CryptoLedger["cryptoledger.py<br/>(SHA-256 Chain)"]
    end
    
    subgraph MLModels["ML Subsystem"]
      Propensity["ONNX Propensity Model"]
      Clustering["KMeans Archetype Clustering"]
      Bandit["UCB Exploration Bandit"]
      Embeddings["Cosine Similarity Embeddings"]
    end
    
    IngestionPipeline --> RawFeatures
    RawFeatures --> DetectedSignals
    DetectedSignals --> EnginePersonalize
    EnginePersonalize --> CheckpointPropensity
  end

  subgraph VoiceAI["On-Device Voice SLM (ai/voice/)"]
    MiniCPM["MiniCPM-5 INT4<br/>(~1.85GB RAM)"]
    IntentClassifier["Intent Classifier<br/>(PAY_METRO, CHECK_EMI, etc.)"]
    IntentHandler["Intent Handlers"]
    DialogueManager["Dialogue State Manager"]
    ZeroLeakPrompts["Zero-Leakage System Prompts"]
    
    MiniCPM --> IntentClassifier
    IntentClassifier --> IntentHandler
    IntentHandler --> DialogueManager
  end

  subgraph DataLayer["Data Layer"]
    PostgreSQL[("PostgreSQL 16<br/>(Docker :5432)<br/>9 Tables")]
    SeedJSON["JSON Seed Data<br/>(1.2k Customers<br/>127k Transactions)"]
    ScenarioJSON["Scenario Overrides<br/>(normal, stress, medical,<br/>fraud, life-change)"]
  end

  subgraph ExternalData["7 External Data Sources"]
    CBS["Core Banking System"]
    UPI["UPI Transaction Logs"]
    AndroidSMS["Android SMS Parser"]
    CIBIL["CIBIL Credit Bureau"]
    BBPS["BBPS Bill Payments"]
    NCMC["NCMC Metro Card"]
    KYCDemo["KYC Demographics"]
  end

  U1 -->|Touch or Voice| HomeScreen
  HomeScreen -->|REST API via JSON| MainPy
  DialogueManager -->|voice-intent.schema.json| MainPy
  ExpComposer -->|experience.schema.json| HomeScreen
  EnginePersonalize -->|customer-state.schema.json| StateService
  DataLoader --> PostgreSQL
  PostgreSQL -.->|DB Offline Fallback| SeedJSON
  CBS --> IngestionPipeline
  StateService -->|Triggers Pipeline| EnginePersonalize

  style Users fill:#e8f5e9
  style MobileApp fill:#e3f2fd
  style BackendAPI fill:#fff3e0
  style AIEngine fill:#f3e5f5
  style VoiceAI fill:#fce4ec
  style DataLayer fill:#e0f2f1
  style ExternalData fill:#f5f5f5
Loading

Server-Driven UI (SDUI) Architecture

This is the core architectural pattern of ABC Bank. The AI determines the customer's reality, the Backend synthesizes it into a UI specification, and the Frontend blindly renders whatever the Backend tells it to show. This means the AI team can completely change the user experience without modifying any React Native code.

flowchart LR
  subgraph AILayer["AI Layer (Ubaid)"]
    direction TB
    DataSources["7 Data Sources<br/>(CBS, UPI, SMS, CIBIL,<br/>BBPS, NCMC, KYC)"]
    Pipeline["Intelligence Pipeline<br/>(Harmonize -> Extract -> <br/>Detect -> Score -> Comply)"]
    CryptoLog["SHA-256 Crypto Ledger<br/>(Decision Audit Trail)"]
    CustomerState["CustomerState JSON<br/>- financial_health: stress<br/>- signals: [commute, emi_due]<br/>- recommendations: [<br/> {product: 'metro_pass',<br/> suppressed: false},<br/> {product: 'personal_loan',<br/> suppressed: true}<br/>]"]
    
    DataSources --> Pipeline
 Pipeline --> CryptoLog
  end

  subgraph BackendLayer["Backend Layer (Harsh)"]
    direction TB
    StateService2["StateService<br/>(Orchestrator)"]
    Composer["ExperienceComposer<br/>(Attention Layer Mapping)"]
    Safety["SafetyPolicyFilter<br/>(DTI above 0.40 -> Suppress)"]
    BehavEngine2["BehavioralEngine<br/>(Time-Aware Context)"]
    ExperienceConfig["ExperienceConfig JSON<br/>- hero_card: 'EMI Due Tomorrow'<br/>- context_cards: [<br/> {layer: DO, title: 'Pay EMI'},<br/> {layer: KNOW, title: 'Spending Up 12%'},<br/> {layer: PLAN, title: 'SIP Investment'}<br/>]<br/>- primary_actions: ['Pay', 'Transfer']<br/>- deprioritized: ['Personal Loan']"]
    
    StateService2 --> Composer
 Composer --> Safety
    BehavEngine2 --> Composer
  end

  subgraph FrontendLayer["Frontend Layer (Lakshya)"]
    direction TB
    AppNavigator["AppNavigator<br/>(Custom Zustand Router)"]
    AdaptiveHome["AdaptiveHomeScreen<br/>(Renders SDUI Config)"]
    HeroCard["Hero Card Component<br/>(Dynamic based on state)"]
    ContextCards["Context Card Stack<br/>(DO -> KNOW -> PLAN -> CONSIDER)"]
    ActionBar["Primary Action Bar<br/>(Dynamic buttons)"]
    
    AppNavigator --> AdaptiveHome
    AdaptiveHome --> HeroCard
    AdaptiveHome --> ContextCards
    AdaptiveHome --> ActionBar
  end

  CustomerState -->|contracts or customer-state.schema.json| StateService2
  ExperienceConfig -->|contracts or experience.schema.json| AppNavigator

  style AILayer fill:#f3e5f5
  style BackendLayer fill:#fff3e0
  style FrontendLayer fill:#e3f2fd
Loading

Complete Data Pipeline Architecture

This diagram traces how raw banking data from 7 distinct sources flows through the entire system — from ingestion through harmonization, feature extraction, signal detection, personalization, compliance, cryptographic logging, experience composition, safety filtering, and finally to the adaptive mobile UI.

flowchart TD
  subgraph Sources["7 Raw Data Sources"]
    CBS2["Core Banking<br/>System (CBS)"]
    UPI2["UPI Transaction<br/>Logs"]
    SMS2["Android SMS<br/>Parser"]
    CIBIL2["CIBIL Credit<br/>Bureau"]
    BBPS2["BBPS Bill<br/>Payments"]
    NCMC2["NCMC Metro<br/>Card Data"]
    KYC2["KYC/Demographics"]
  end

  subgraph Ingestion2["Data Ingestion (ai/intelligence/ingestion/)"]
    MD5["MD5 Deduplication<br/>(Idempotent Transaction IDs)"]
    ISOParse["ISO 8601 Date<br/>Normalization"]
    ConflictRes["Balance Conflict Resolution<br/>(balance_conflicts_resolved)"]
    InMemCache["O(1) In-Memory<br/>Feature Cache"]
  end

  subgraph Features2["Feature Extraction (ai/intelligence/features/)"]
    FiftyThirtyTwenty["50/30/20 Rule Analysis<br/>(Needs/Wants/Savings Split)"]
    NineCategories["9-Category Spend<br/>Breakdown"]
    ThirtyDayForecast["30-Day Cash Flow<br/>Runway Forecast"]
    ThirtyTwoMetrics["32 Single-Pass<br/>Feature Metrics"]
  end

  subgraph Signals2["Signal Detection (ai/intelligence/signals/)"]
    BehavSignals["Behavioral Signals<br/>(Commute Pattern, Dining,<br/>Cinema, Weekend Habits)"]
    FinSignals["Financial Signals<br/>(DTI Ratio, EMI Pressure,<br/>Savings Decline, Risk Score)"]
    LifeSignals["Lifecycle Signals<br/>(Medical Emergency, Marriage,<br/>Job Change, Retirement)"]
  end

  subgraph StateGen2["Customer State (ai/intelligence/customer_state/)"]
    DualCadence["Dual Cadence Controller<br/>(14-day Macro + 0.162ms Micro)"]
    StateBuilder["Customer State Builder<br/>(financial_health Classification)"]
    HealthClass["Financial Health:<br/>thriving / stable / tight / stress"]
  end

  subgraph PersonalizationEng["Personalization (ai/intelligence/personalization/)"]
    MultiFactorScorer["Multi-Factor Utility Scorer<br/>30% Affordability<br/>30% Lifecycle Match<br/>25% Urgency<br/>15% Archetype Fit<br/>- Risk Penalty"]
    ArchetypeMatch["7 Bharat Archetypes<br/>(urban_commuter, rural_farmer,<br/>salaried_professional, student,<br/>small_business_owner,<br/>retired_senior, gig_worker)"]
    RBICompliance["RBI Compliance Check<br/>(DTI above 0.40 -> Suppress All Credit)"]
    DPDPCheck["DPDP Purpose Limitation<br/>(Data Protection Compliance)"]
    CryptoLedger2["SHA-256 Crypto Ledger<br/>(Tamper-Proof Decision Chain)"]
  end

  subgraph ExperienceComp["Experience Composition (apps/backend/)"]
    AttentionLayers["Attention Layer Classification<br/>- DO: Immediate (EMI Due)<br/>- KNOW: Awareness (Spend up12%)<br/>- PLAN: Future (SIP, Insurance)<br/>- CONSIDER: Low Priority"]
    HeroCardGen["Hero Card Generation<br/>(Most Urgent Item)"]
    SafetyPolicyFilter["Safety Policy Filter<br/>(Block Predatory Lending<br/>for Stressed Customers)"]
    ModuleComposition["Dynamic Module<br/>Composition"]
  end

  subgraph UIRender["Adaptive UI Render"]
    AdaptiveUI["AdaptiveHomeScreen<br/>(Morphs Per State)"]
    NormalUI["Normal State:<br/>Standard Dashboard"]
    StressUI["Stress State:<br/>Empathetic Hero Card<br/>+ Hidden Utility Widgets"]
    MedicalUI["Medical State:<br/>Medical Assistance<br/>Prominent"]
  end

  CBS2 --> MD5
  MD5 --> ISOParse
  ISOParse --> ConflictRes
  ConflictRes --> FiftyThirtyTwenty
  FiftyThirtyTwenty --> ThirtyTwoMetrics
  NineCategories --> ThirtyTwoMetrics
  ThirtyDayForecast --> ThirtyTwoMetrics
  ThirtyTwoMetrics --> CommuteSig2
  CommuteSig2 --> DualCadence
  DualCadence --> StateBuilder
  StateBuilder --> HealthClass
  HealthClass --> MultiFactorScorer
  ArchetypeMatch --> MultiFactorScorer
  MultiFactorScorer --> RBICompliance
  RBICompliance --> DPDPCheck
  DPDPCheck --> CryptoLedger2
  CryptoLedger2 -->|customer-state.json| AttentionLayers
  AttentionLayers --> HeroCardGen
  HeroCardGen --> SafetyPolicyFilter
  SafetyPolicyFilter --> ModuleComposition
  ModuleComposition -->|experience-config.json| AdaptiveUI
  HealthClass -->|stress| StressUI
  HealthClass -->|thriving or stable| NormalUI
  HealthClass -->|medical_event| MedicalUI
Loading

Runtime Deployment Architecture

flowchart TD
  subgraph DevMachine["Developer Machine"]
    VSCode["VS Code / IDE"]
    Git["Git Repository"]
  end

  subgraph DockerEnv["Docker Environment"]
    PostgresContainer["postgres:16-alpine<br/> Port 5432<br/> Volume: postgres_data<br/> Healthcheck: pg_isready"]
  end

  subgraph PythonRuntime["Python Runtime"]
    FastAPIServer["FastAPI + Uvicorn<br/>Port 8000<br/>- 15+ REST Endpoints<br/>- CORS Middleware<br/>- Inspector Dashboards"]
    AIPipeline["AI Intelligence Pipeline<br/>- Feature Extraction<br/>- Signal Detection<br/>- Personalization<br/>- Crypto Ledger"]
  end

  subgraph MobileRuntime["Mobile Runtime"]
    ExpoDevServer["Expo Dev Server<br/>(Metro Bundler)"]
    ExpoGoApp["Expo Go App<br/>(Physical Device)"]
    ONNXRuntime["ONNX Runtime<br/>(On-Device ML)"]
    MiniCPMRuntime["MiniCPM-5 INT4 SLM<br/>(~1.85GB RAM on NPU)"]
  end

  subgraph ProductionHint["Production (Referenced)"]
    AWSRDS["AWS RDS PostgreSQL<br/>(Tunnel via localhost:5433)"]
  end

  VSCode --> PostgresContainer
  VSCode --> FastAPIServer
  VSCode --> ExpoDevServer
  FastAPIServer --> PostgresContainer
  FastAPIServer --> AIPipeline
  ExpoDevServer --> ExpoGoApp
  ExpoGoApp --> ONNXRuntime
  ExpoGoApp --> MiniCPMRuntime
  ExpoGoApp -->|REST API| FastAPIServer
  PostgresContainer -.->|Production Tunnel| AWSRDS
Loading

Contract Boundary Architecture

The three JSON Schema contracts enforce strict boundaries between independently-developed components. Each contract is frozen — changes require consensus from all three team members.

flowchart TB
  subgraph AIBoundary["AI Domain (Ubaid)<br/>ai/"]
    AIIngest["Data Ingestion<br/>(7 Sources)"]
    AIFeatures["Feature Extraction<br/>(32 Metrics)"]
    AISignals["Signal Detection"]
    AIPersonalize["Personalization Engine"]
    AICrypto["Crypto Ledger"]
    AIVoice["Voice SLM<br/>(MiniCPM-5)"]
  end

  subgraph Contract1["customer-state.schema.json"]
    CS["CustomerState<br/>- financial_health<br/>- signals[]<br/>- recommendations[]<br/> (each has suppressed flag)"]
  end

  subgraph Contract2["experience.schema.json"]
    EC["ExperienceConfig<br/>- hero_card<br/>- context_cards[]<br/> (DO/KNOW/PLAN/CONSIDER)<br/>- primary_actions[]<br/>- deprioritized_modules[]"]
  end

  subgraph Contract3["voice-intent.schema.json"]
    VI["VoiceIntent<br/>- intent (PAY_METRO, etc.)<br/>- language (en/hi/gu)<br/>- entities[]<br/>- response_text<br/>- confidence"]
  end

  subgraph BackendBoundary["Backend Domain (Harsh)<br/>apps/backend/"]
    BEState["StateService"]
    BEComposer["ExperienceComposer"]
    BESafety["SafetyPolicyFilter"]
    BEBehavior["BehavioralEngine"]
    BEAuth["PIN Auth"]
    BEData["DataLoader + Repositories"]
  end

  subgraph FrontendBoundary["Frontend Domain (Lakshya)<br/>apps/frontend/"]
    FENav["AppNavigator"]
    FEHome["AdaptiveHomeScreen"]
    FEChat["MitraChatScreen"]
    FEPay["PaymentsScreen"]
    FEStore["Zustand Store"]
  end

  AIPersonalize --> CS
  CS --> BEState
  AICrypto --> CS
  
  BEComposer --> EC
  BESafety --> EC
  EC --> FEStore
  
  AIVoice --> VI
  VI --> BEState

  style Contract1 fill:#ffecb3,stroke:#ff8f00,stroke-width:3px
  style Contract2 fill:#c8e6c9,stroke:#2e7d32,stroke-width:3px
  style Contract3 fill:#bbdefb,stroke:#1565c0,stroke-width:3px
Loading

Dual AI Architecture

A critical architectural decision: the system uses two completely separate AI systems with a hard boundary between them. The Backend AI makes all financial decisions using deterministic math. The On-Device SLM handles only natural language — it NEVER makes financial decisions and NEVER sees transaction data.

flowchart LR
  subgraph BackendAI["Backend Deterministic AI<br/>(Decision-Making Authority)"]
    direction TB
    MathScorer["Multi-Factor Utility Scorer<br/>(Pure Mathematics)"]
    DTICalc["DTI Ratio Calculator<br/>(Debt-to-Income)"]
    SpendCalc["50/30/20 Spend Analyzer"]
    CashFlow["30-Day Cash Flow Forecaster"]
    XGBoost["XGBoost Propensity"]
    KMeans["KMeans Archetype Clustering"]
    UCBBandit["UCB Exploration Bandit"]
    
    MathScorer --> DTICalc
    DTICalc --> SpendCalc
    SpendCalc --> CashFlow
  end

  subgraph HardBoundary["HARD BOUNDARY<br/>(No Financial Data Crosses)"]
    Wall["Zero Banking Data<br/>Leakage Policy"]
  end

  subgraph DeviceSLM["On-Device SLM<br/>(Language-Only Authority)"]
    direction TB
    MiniCPM2["MiniCPM-5 INT4<br/>(~1.85GB RAM on NPU)"]
    VernacularNLP["Vernacular NLP<br/>(Hindi/Gujarati/Hinglish/EN)"]
    IntentExtract["Intent Extraction<br/>(PAY_METRO, CHECK_EMI)"]
    ResponseVerb["Response Verbalization<br/>(Pre-Computed Facts Only)"]
    
    MiniCPM2 --> VernacularNLP
    VernacularNLP --> IntentExtract
    IntentExtract --> ResponseVerb
  end

  CashFlow -->|Decisions and Suppressions| Wall
  Wall -->|Approved Trusted Facts Only| MiniCPM2

  style HardBoundary fill:#ffcdd2,stroke:#c62828,stroke-width:4px
  style BackendAI fill:#e8f5e9
  style DeviceSLM fill:#e3f2fd
Loading

Graceful Degradation Architecture

The system is designed to never fail completely. Multiple fallback layers ensure the app remains functional even when backend services or the database are unavailable.

stateDiagram-v2
  [*] --> Normal: App Starts

  state Normal {
    [*] --> LiveAPI: Backend Reachable
    LiveAPI --> DBOnline: PostgreSQL Healthy
    DBOnline --> AIPipeline: AI Pipeline Runs
    AIPipeline --> FullExperience: Complete SDUI Response
  }

  state BackendDegraded {
    [*] --> Timeout: 2.5s AbortController
    Timeout --> EdgeEngine: MiniCPM5EdgeEngine
    EdgeEngine --> OfflineState: Apply Cached/Default State
    OfflineState --> OfflineUI: Render Offline Bundle
  }

  state DatabaseDegraded {
    [*] --> DBOffline: PostgreSQL Unreachable
    DBOffline --> JSONFallback: DataLoader Detects Failure
    JSONFallback --> SeedCustomers: data/seed/customers.json
    JSONFallback --> SeedTransactions: data/seed/transactions.json
    JSONFallback --> ScenarioOverride: data/scenarios/*.json
  }

  state AIDegraded {
    [*] --> PipelineCrash: AI Pipeline Exception
    PipelineCrash --> SafeFallback: _create_safe_fallback_state
    SafeFallback --> GenericProfile: Generic Valid Customer Profile
  }

  Normal --> BackendDegraded: Network Timeout
  Normal --> DatabaseDegraded: DB Connection Failed
  Normal --> AIDegraded: Python Exception
  BackendDegraded --> Normal: Connectivity Restored
  DatabaseDegraded --> Normal: DB Restored
  AIDegraded --> Normal: Next Request Succeeds
Loading

Feature Overview

Feature Map Diagram

flowchart TD
  subgraph FrontendFeatures["Frontend Features"]
    F1["Adaptive Home Screen<br/>(Dynamic Dashboard)"]
    F2["Mitra AI Assistant<br/>(Voice + Chat)"]
    F3["1-Tap Payments<br/>(Biometric Auth)"]
    F4["Card Controls<br/>(Lock/Unlock/Limits)"]
    F5["Multilingual UI<br/>(EN/HI/GU)"]
    F6["Demo Scenario Switcher"]
    F7["SDUI Renderer<br/>(Dumb UI Layer)"]
    F8["Offline State Bundles"]
  end

  subgraph AIFeatures["AI Features"]
    A1["Ethical AI Personalization<br/>(Multi-Factor Scoring)"]
    A2["7 Bharat Archetypes"]
    A3["Financial Health Assessment<br/>(DTI/EMI/Savings)"]
    A4["Multi-Source Data Ingestion<br/>(7 Sources, MD5 Dedup)"]
    A5["Safe-to-Spend Analysis<br/>(50/30/20 + 30-Day Forecast)"]
    A6["Behavioral Context Engine<br/>(Time-Aware Suggestions)"]
    A7["Cryptographic Decision Ledger<br/>(SHA-256 Chain)"]
  end

  subgraph BackendFeatures["Backend Features"]
    B1["Experience Composer<br/>(SDUI Generation)"]
    B2["Safety Policy Filter<br/>(Anti-Predatory Lending)"]
    B3["PIN Authentication<br/>(PBKDF2-HMAC-SHA256)"]
    B4["Loan Disbursement<br/>(Max Rs. 1,50,000)"]
    B5["Inspector Dashboards<br/>(AI Debug Tools)"]
  end

  subgraph Tools["Developer Tools"]
    T1["AI Inspector Dashboard"]
    T2["Voice SLM Simulator"]
    T3["Prisma Studio"]
    T4["Audit Suite (39 Checks)"]
  end

  A1 --> B1
  A3 --> B2
  A4 --> A1
  A6 --> B1
  B1 --> F1
  B2 --> F1
  B3 --> F3
  A2 --> A1
  A7 --> A1
  F2 --> A5
Loading

Feature Inventory (18 Features)

# Feature What It Does Implementation APIs Dependencies
1 Adaptive Home Screen Dashboard morphs based on financial state (normal/stress/medical/fraud) — different hero cards, context cards, and action modules per state apps/frontend/src/features/home/AdaptiveHomeScreen GET /experience/{id} ExperienceComposer, SafetyPolicy
2 Mitra AI Assistant Vernacular voice & chat supporting Hindi, Gujarati, Hinglish, English with structured action chips and navigation routing apps/frontend/src/features/assistant/MitraChatScreen, ai/voice/ POST /assistant/intent, /assistant/chat, GET /assistant/init MiniCPM-5 SLM, IntentClassifier
3 Ethical AI Personalization Multi-factor scoring (30% affordability + 30% lifecycle + 25% urgency + 15% archetype − risk penalty) with mandatory suppression for stressed customers ai/intelligence/personalization/scorer.py, compliance.py, cryptoledger.py — RBI DTI caps, DPDP compliance
4 Server-Driven UI Backend generates complete UI specification; frontend is a dumb renderer apps/backend/app/experience/composer.py GET /experience/{id} ExperienceConfig contract
5 Bharat Archetypes 7 Indian-market customer archetypes (urban_commuter, rural_farmer, salaried_professional, small_business_owner, student, retired_senior, gig_worker) with 15% weight in recommendation scoring ai/intelligence/personalization/scorer.py — KMeans clustering
6 Multi-Source Data Ingestion Ingests and harmonizes 7 banking data sources (CBS, UPI, SMS, CIBIL, BBPS, NCMC, KYC) with MD5 deduplication, ISO date normalization, and conflict resolution ai/intelligence/ingestion/harmonizer.py — In-memory feature cache
7 Financial Health Assessment Classifies customers as thriving/stable/tight/stress based on DTI ratio, EMI pressure, declining savings, and 30-day runway forecast ai/intelligence/signals/financial.py, detector.py — Feature extractor
8 Behavioral Context Engine Detects habits (metro commute, dining, cinema) and provides time-aware suggestions (Mon-Fri 07:45-09:30 → commute prompt) apps/backend/app/services/behavior_engine.py — datetime.now(), transactions
9 1-Tap Payments Instant recurring mandate payments with biometric authentication — tap → biometric → animated checkmark → never leaves screen apps/frontend/src/state/customerStore.ts POST /payments/transfer expo-local-authentication
10 Card Controls Lock/unlock debit/credit cards and set ATM/POS/online limits; locked cards block payment execution apps/backend/app/api/routes.py GET /cards/{id}, POST /cards/controls _card_controls state
11 Loan Disbursement Instant credit up to ₹1,50,000 — credits balance and emits event for state refresh apps/backend/app/services/state_service.py POST /loans/disburse SafetyPolicyFilter
12 PIN Authentication Secure PIN with PBKDF2-HMAC-SHA256 (100k iterations), 16-byte random salt, constant-time hmac.compare_digest, and rate limiting (5 failures → 15-min lockout) apps/backend/app/services/state_service.py POST /auth/pin/setup, /auth/pin/verify secrets, hmac
13 Graceful Degradation Multi-layer fallback: backend timeout (2.5s) → edge ONNX processing; DB offline → JSON seed files; AI crash → safe fallback state apps/frontend/src/services/api.ts, apps/backend/app/db/loader.py — Edge engine, seed data
14 Demo & Scenario System Switch between pre-built scenarios (normal, surplus, financial_stress, medical_event, fraud_alert, life-change) to demonstrate personalization data/scenarios/*.json POST /scenario/switch StateService memory flush
15 Cryptographic Decision Ledger SHA-256 tamper-proof audit chain logging every AI recommendation and suppression decision for regulatory compliance ai/intelligence/personalization/cryptoledger.py — hashlib SHA-256
16 Multilingual Support Full UI and voice support for English, Hindi, and Gujarati with dynamic language switching apps/frontend/src/i18n/ (en, hi, gu) — MiniCPM-5 for voice
17 Safe-to-Spend Analysis 50/30/20 budgeting rule (Needs/Wants/Savings) applied to spending with 9-category breakdown and 30-day cash flow forecast ai/intelligence/features/spend_analyzer.py, extractor.py — Feature extraction
18 Inspector Dashboards Live browser tools for debugging: AI Inspector (personalization math, crypto chain, safe-to-spend dials) and Voice Inspector (SLM simulator) ai/inspector.html, ai/voice_inspector.html GET /inspector, /voice-inspector —

Repository Structure

dau/
├── apps/
│  ├── backend/            # FastAPI API server (Owner: Harsh)
│  │  ├── app/
│  │  │  ├── main.py         # FastAPI init, CORS middleware, router mount
│  │  │  ├── api/
│  │  │  │  └── routes.py      # All 15+ REST endpoints
│  │  │  ├── db/
│  │  │  │  ├── session.py     # SQLAlchemy engine (auto WSL IP detection)
│  │  │  │  ├── models.py      # ORM models (Customer, Account, Transaction, etc.)
│  │  │  │  ├── loader.py      # DataLoader (PostgreSQL → JSON fallback)
│  │  │  │  ├── alembic/      # Migration versions and env.py
│  │  │  │  └── repositories/
│  │  │  │    ├── customer_repo.py
│  │  │  │    ├── transaction_repo.py
│  │  │  │    └── event_and_product_repo.py
│  │  │  ├── experience/
│  │  │  │  └── composer.py     # ExperienceComposer (State → SDUI Config)
│  │  │  ├── models/         # Pydantic schemas
│  │  │  │  ├── customer_state.py  # CustomerStateModel, Balance, Recommendation
│  │  │  │  ├── experience.py    # ExperienceConfigModel, HeroCard, ContextCard
│  │  │  │  ├── assistant.py    # AssistantIntentRequest/Response
│  │  │  │  ├── events.py      # BankingEventModel
│  │  │  │  └── voice.py      # VoiceIntentModel (legacy)
│  │  │  └── services/
│  │  │    ├── state_service.py  # Core orchestrator (state, auth, payments, loans)
│  │  │    ├── safety_policy.py  # SafetyPolicyFilter (anti-predatory lending)
│  │  │    └── behavior_engine.py # BehavioralEngine (time-aware context)
│  │  └── requirements.txt      # FastAPI, SQLAlchemy, Alembic, Pydantic, etc.
│  └── frontend/            # React Native / Expo app (Owner: Lakshya)
│    ├── App.tsx           # Entry: ThemeProvider → AppNavigator → useEffect(fetch)
│    ├── src/
│    │  ├── components/       # Reusable UI primitives
│    │  │  ├── common/       # Shared components (buttons, cards, etc.)
│    │  │  ├── context/      # Context-aware card components
│    │  │  ├── payments/      # Payment-specific components
│    │  │  └── transactions/    # Transaction list components
│    │  ├── features/        # Screen-level feature modules
│    │  │  ├── assistant/     # MitraChatScreen (AI voice/chat)
│    │  │  ├── demo/       # PrototypeLabModal, ArchitectureFlowModal
│    │  │  ├── home/       # AdaptiveHomeScreen (SDUI renderer)
│    │  │  ├── insights/     # InsightsScreen (spending analytics)
│    │  │  ├── journeys/     # Modal flows (KYC, Insurance, Medical, etc.)
│    │  │  ├── more/       # MoreViewScreen (catalog)
│    │  │  ├── onboarding/    # OnboardingModal
│    │  │  ├── payments/     # PaymentsScreen
│    │  │  ├── profile/      # ProfileScreen
│    │  │  └── transactions/   # TransactionsScreen
│    │  ├── i18n/         # Localization: en.ts, hi.ts, gu.ts
│    │  ├── motion/        # Custom Animated API transitions & gestures
│    │  ├── navigation/      # AppNavigator.tsx (custom Zustand-driven router)
│    │  ├── services/       # BankingApi.ts + MiniCPM5EdgeEngine.ts
│    │  ├── state/        # customerStore.ts (monolithic Zustand store)
│    │  ├── theme/        # ThemeContext.tsx + tokens + colors + fonts
│    │  └── types/        # TypeScript interfaces (index.ts)
│    ├── assets/          # Icons, fonts, minicpm5_slm_v1.onnx
│    ├── app.json          # Expo configuration
│    └── package.json        # Dependencies
├── ai/                # AI/ML Intelligence Engine (Owner: Ubaid)
│  ├── intelligence/         # Backend AI pipeline
│  │  ├── ingestion/
│  │  │  ├── harmonizer.py     # 7-source harmonizer (MD5 dedup, ISO dates)
│  │  │  └── models.py      # Data source models
│  │  ├── features/
│  │  │  ├── extractor.py     # 50/30/20 rule, 32 single-pass metrics
│  │  │  ├── spend_analyzer.py   # 9-category spending breakdown
│  │  │  └── forecaster.py     # 30-day cash flow runway forecast
│  │  ├── signals/
│  │  │  ├── detector.py      # Signal classification orchestrator
│  │  │  ├── behavioral.py     # Commute, dining, cinema detection
│  │  │  ├── financial.py     # DTI, risk, declining savings
│  │  │  └── lifecycle.py     # Medical, marriage, job change detection
│  │  ├── customer_state/
│  │  │  ├── generator.py     # Dual cadence (14-day batch + 0.162ms micro)
│  │  │  ├── cadence.py      # Cadence control logic
│  │  │  └── schemas.py      # State schemas
│  │  ├── personalization/
│  │  │  ├── scorer.py       # Multi-factor utility (0.30+0.30+0.25+0.15−risk)
│  │  │  ├── compliance.py     # RBI DTI caps + DPDP limitations
│  │  │  └── cryptoledger.py    # SHA-256 tamper-proof decision chain
│  │  ├── recommendations/
│  │  │  ├── rules.py       # Recommendation business rules
│  │  │  └── scoring.py      # Offer ranking + ethical suppression
│  │  ├── explanations/       # Counterfactual explanations for transparency
│  │  └── ml/            # Machine Learning subsystem
│  │    ├── propensity/      # ONNX propensity model (ml_propensity_prob)
│  │    ├── embeddings/      # Cosine similarity embeddings
│  │    ├── clustering/      # KMeans archetype soft-clustering
│  │    └── bandit/        # UCB exploration/exploitation bandit
│  ├── voice/            # On-device SLM voice pipeline
│  │  ├── model/minicpm5_runner.py # MiniCPM-5 INT4 runner (~1.85GB, NPU)
│  │  ├── inference/        # End-to-end voice processing
│  │  ├── intents/
│  │  │  ├── classifier.py     # Intent classification
│  │  │  └── handlers.py      # Handlers (PAY_METRO, CHECK_EMI, etc.)
│  │  ├── prompts/         # Zero-leakage system prompts
│  │  └── dialogue/         # Dialogue state management
│  ├── tests/            # 45 tests, 0.39s total
│  ├── run.py            # Intelligence entrypoint
│  ├── run_voice.py         # Voice entrypoint
│  ├── inspector.html        # AI decision debugging dashboard
│  ├── voice_inspector.html     # SLM simulator dashboard
│  └── requirements.txt       # NumPy, SciPy, scikit-learn, ONNX Runtime
├── contracts/             # JSON Schema contracts (shared, frozen)
│  ├── customer-state.schema.json  # AI → Backend (financial_health, signals, recs)
│  ├── experience.schema.json    # Backend → Frontend (hero, cards, actions)
│  └── voice-intent.schema.json   # Voice → Backend (intent, lang, entities)
├── data/
│  ├── seed/             # customers.json (1.2k), transactions.json (127k+)
│  └── scenarios/          # normal.json, financial-stress.json, life-change.json
├── prisma/schema.prisma       # Introspection-only (9 models, not for migrations)
├── scripts/
│  ├── audit_and_verify_all.py    # 39-check validation suite (~540 lines)
│  ├── generate_seed_data.py     # Mock data generator (1.2k profiles, 127k txns)
│  ├── seed_database.py       # Bulk DB seeder (batches of 10,000)
│  ├── run-demo.ps1 / run-demo.sh  # Demo launcher scripts
│  ├── export_onnx_meta.py      # ONNX model metadata export
│  └── test_ondevice_intent.js    # On-device intent test (Node.js)
├── docs/               # Comprehensive documentation (13 files)
├── docker-compose.yml        # PostgreSQL 16 (Alpine)
├── alembic.ini            # Migration config → apps/backend/app/db/alembic
├── package.json           # Prisma tooling (db:studio, db:introspect)
├── .env.example           # Environment template
├── .github/CODEOWNERS        # Domain ownership enforcement
└── .gitignore            # Exclusion patterns

Monorepo Dependency Diagram

flowchart TD
  subgraph SharedContracts["Shared Contracts (Frozen)"]
    CSSchema["customer-state.schema.json"]
    EXSchema["experience.schema.json"]
    VISchema["voice-intent.schema.json"]
  end

  subgraph SharedData["Shared Data"]
    SeedData["data/seed/<br/>(customers.json<br/>transactions.json)"]
    Scenarios["data/scenarios/<br/>(normal, stress, medical,<br/>fraud, life-change)"]
  end

  subgraph Backend2["apps/backend/ (Harsh)"]
    BERoutes["routes.py"]
    BEServices["services/"]
    BEExperience["experience/"]
    BEDB["db/ + repositories/"]
  end

  subgraph Frontend2["apps/frontend/ (Lakshya)"]
    FEScreens["features/"]
    FEStore["state/customerStore.ts"]
    FEServices2["services/api.ts"]
    FEEdge["services/MiniCPM5EdgeEngine.ts"]
  end

  subgraph AIModule["ai/ (Ubaid)"]
    AIIntelligence["intelligence/"]
    AIVoice2["voice/"]
    AITests["tests/"]
    AIML["ml/"]
  end

  subgraph Scripts2["scripts/"]
    Audit["audit_and_verify_all.py"]
    Seeder["seed_database.py"]
    Generator["generate_seed_data.py"]
  end

  %% Dependencies
  AIIntelligence -->|Python import| BEServices
  AIVoice2 -->|Python import| BERoutes
  CSSchema -->|Validates| BEServices
  EXSchema -->|Validates| FEStore
  VISchema -->|Validates| BERoutes
  SeedData -->|Fallback data| BEDB
  Scenarios -->|Demo overrides| BEServices
  FEServices2 -->|HTTP REST| BERoutes
  FEEdge -->|Offline fallback| FEStore
  Seeder -->|Populates| BEDB
  Audit -->|Validates| AIIntelligence

  style SharedContracts fill:#ffecb3,stroke:#f57f17
  style SharedData fill:#e0f7fa,stroke:#00838f
Loading

Team Ownership

Member Role Domain Ownership
Harsh Solanki Team Lead, Backend apps/backend/, system architecture, integration
Panchal Lakshya Frontend apps/frontend/, adaptive UI, animations, voice UI
Ubaid Khan AI/ML ai/, feature extraction, signals, recommendations, voice SLM

Shared ownership: contracts/, data/, docs/, scripts/

Note: Strict Rule: Team members must NOT edit other domains' folders. Changes to contracts/ require consensus from all three members. Enforced via .github/CODEOWNERS.


Core Contracts

Contract Flow Diagram

flowchart LR
  subgraph Producer1["AI Engine"]
    AIOut["Customer State<br/>Generator"]
  end

  subgraph Contract_CS["customer-state.schema.json<br/>(JSON Schema Draft-07)"]
    CSFields["- financial_health: thriving/stable/tight/stress<br/>- signals: [{type, confidence, source}]<br/>- recommendations: [{product_id, score,<br/> category, suppressed: bool,<br/> explanation}]"]
  end

  subgraph Producer2["Voice SLM"]
    VoiceOut["MiniCPM-5 Intent<br/>Classifier"]
  end

  subgraph Contract_VI["voice-intent.schema.json<br/>(JSON Schema Draft-07)"]
    VIFields["- intent: PAY_METRO/CHECK_EMI/...<br/>- language: en/hi/gu<br/>- entities: [{type, value}]<br/>- response_text: string<br/>- confidence: 0.0-1.0"]
  end

  subgraph Consumer1["Backend"]
    BEConsume["StateService<br/>+ ExperienceComposer"]
  end

  subgraph Contract_EX["experience.schema.json<br/>(JSON Schema Draft-07)"]
    EXFields["- hero_card: {title, subtitle, type, actions}<br/>- context_cards: [{layer: DO/KNOW/PLAN/CONSIDER,<br/> title, body, icon, actions}]<br/>- primary_actions: [{label, route}]<br/>- deprioritized_modules: [string]"]
  end

  subgraph Consumer2["Frontend"]
    FEConsume["Zustand Store -> <br/>AdaptiveHomeScreen"]
  end

  AIOut -->|Produces| CSFields
  CSFields -->|Consumed by| BEConsume
  VoiceOut -->|Produces| VIFields
  VIFields -->|Consumed by| BEConsume
  BEConsume -->|Produces| EXFields
  EXFields -->|Consumed by| FEConsume

  style Contract_CS fill:#ffecb3,stroke:#ff8f00,stroke-width:3px
  style Contract_VI fill:#bbdefb,stroke:#1565c0,stroke-width:3px
  style Contract_EX fill:#c8e6c9,stroke:#2e7d32,stroke-width:3px
Loading

Contract Schema Details

Contract File Producer → Consumer Key Fields
CustomerState customer-state.schema.json AI → Backend financial_health (thriving/stable/tight/stress), signals[], recommendations[] (each with suppressed flag for ethical filtering)
ExperienceConfig experience.schema.json Backend → Frontend hero_card, context_cards[] (organized by DO/KNOW/PLAN/CONSIDER attention layers), primary_actions[], deprioritized_modules[]
VoiceIntent voice-intent.schema.json Voice → Backend intent (PAY_METRO, CHECK_EMI, LOCK_CARD, PAY_BILL), language (en/hi/gu), entities[], response_text, confidence

Technology Stack

Backend

Component Technology Version Purpose
API Framework FastAPI ≥0.110.0 Async REST API with auto-generated OpenAPI docs
ASGI Server Uvicorn ≥0.28.0 High-performance Python web server
ORM SQLAlchemy ≥2.0.0 Database abstraction with declarative models
Migrations Alembic ≥1.13.0 Database schema version control
Validation Pydantic ≥2.0.0 Request/response schema validation
Schema Validation jsonschema ≥4.0.0 Contract schema validation (Draft-07)
HTTP Client httpx ≥0.27.0 Async HTTP requests
DB Driver psycopg (binary) ≥3.1.0 PostgreSQL adapter
Testing pytest ≥8.0.0 Test framework

Frontend

Component Technology Version Purpose
Framework React Native 0.86.3 Cross-platform mobile
Platform Expo ^57.0.22 Managed workflow + build tooling
UI React 19.2.3 Component rendering
State Zustand ^5.0.15 Lightweight global state management
Icons lucide-react-native — SVG icon library
ML Runtime onnxruntime-react-native — On-device ML inference
Biometrics expo-local-authentication — Fingerprint/FaceID authentication
Secure Storage expo-secure-store — Encrypted key-value storage

AI Engine

Component Technology Version Purpose
Validation Pydantic ≥2.0.0 Data model validation
Numerics NumPy ≥1.26.0 Array operations, feature computation
Statistics SciPy ≥1.12.0 Statistical analysis
ML scikit-learn ≥1.4.0 KMeans clustering, propensity
ML Runtime ONNX Runtime ≥1.20.0 Model inference (<10ms latency)
Serialization joblib ≥1.3.0 Model persistence
On-Device SLM MiniCPM-5 INT4 ~1.85GB RAM Vernacular NLP on Snapdragon/Apple NPUs

Infrastructure

Component Technology Configuration
Database PostgreSQL 16 (Alpine) Docker, port 5432, volume postgres_data
Containerization Docker Compose Single db service with pg_isready healthcheck
Schema Viewer Prisma Studio Introspection only (prisma db pull)

Backend Architecture — Deep Dive

Backend Layer Architecture Diagram

flowchart TD
  subgraph EntryPoint["Entry Point"]
    MainPy2["main.py<br/>- FastAPI() init<br/>- CORSMiddleware (allow_origins=[*])<br/>- Router mount (/api/v1)<br/>- Static file serving<br/> (/inspector, /voice-inspector)"]
  end

  subgraph APILayer["API Layer (routes.py)"]
    CoreRoutes["Core Routes<br/>- GET /customer/{id}<br/>- GET /experience/{id}"]
    AuthRoutes["Auth Routes<br/>- POST /auth/pin/setup<br/>- POST /auth/pin/verify"]
    PayRoutes["Payment Routes<br/>- POST /payments/transfer<br/>- POST /loans/disburse"]
    CardRoutes["Card Routes<br/>- GET /cards/{id}<br/>- POST /cards/controls"]
    AssistantRoutes["Assistant Routes<br/>- GET /assistant/init<br/>- POST /assistant/chat<br/>- POST /assistant/intent"]
    EventRoutes["Event Routes<br/>- POST /events<br/>- POST /scenario/switch"]
  end

  subgraph ServiceLayer["Service Layer"]
    StateService2["StateService<br/>(Core Orchestrator)<br/>- get_state() -> cache/DB/AI/fallback<br/>- switch_scenario() -> flush + reload<br/>- ingest_event() -> balance + signals<br/>- execute_payment() -> lock + funds + ledger<br/>- disburse_loan() -> max Rs. 1,50,000<br/>- set/verify_customer_pin()<br/>- submit_kyc(), submit_medical_claim()<br/>- pause_mandate(), request_emi_grace()<br/>- split_emi(), sweep_deficit_for_emi()"]
    SafetyPolicy2["SafetyPolicyFilter<br/>- evaluate_financial_stress()<br/> (DTI above 0.40 or EMI pressure)<br/>- filter_recommendations()<br/> (suppress loan/payday/credit)<br/>- apply_module_policies()<br/> (restrict loan module,<br/> prioritize cashflow advisory)"]
    BehaviorEngine2["BehavioralEngine<br/>- analyze_habits()<br/> (recurring txn -> daily/weekly)<br/>- evaluate_current_relevance()<br/> (datetime.now() -> contextual hints<br/> Mon-Fri 07:45-09:30 = commute)"]
  end

  subgraph ExperienceLayer["Experience Layer"]
    ExpComposer2["ExperienceComposer<br/>- compose(state, recommendations)<br/> -> ExperienceConfigModel<br/>- _determine_layer(priority)<br/> -> DO/KNOW/PLAN/CONSIDER<br/>- Build hero_card<br/>- Build context_cards[]<br/>- Compute primary_actions[]<br/>- Mark deprioritized_modules[]"]
  end

  subgraph DataLayer2["Data Access Layer"]
    DataLoader2["DataLoader<br/>- Try PostgreSQL via repos<br/>- Catch SQLAlchemy exceptions<br/>- Fallback to JSON files<br/> (data/seed/*.json,<br/> data/scenarios/*.json)"]
    Repos["Repositories<br/>- CustomerRepository<br/> (get_by_id, get_summary)<br/>- TransactionRepository<br/> (get_by_customer, get_by_account)<br/>- EventRepository<br/>- ProductRepository"]
    Session["session.py<br/>- SQLAlchemy Engine<br/>- Connection pooling<br/>- Auto WSL IPv4 detection<br/> (PowerShell Get-NetNeighbor)<br/>- Fallback to localhost"]
  end

  subgraph PydanticModels["Pydantic Schemas"]
    CustState["CustomerStateModel<br/>(customer_id, financial_health,<br/>balances, signals, recommendations)"]
    ExpConfig["ExperienceConfigModel<br/>(hero_card, context_cards,<br/>primary_actions, deprioritized)"]
    AssistModel["AssistantIntentRequest/Response"]
    EventModel["BankingEventModel"]
  end

  subgraph ExternalAI["External AI Pipeline"]
    AIExtractor["ai.intelligence.features.extractor"]
    AIGenerator["ai.intelligence.customer_state.generator"]
    AIClassifier["ai.voice.intents.classifier"]
  end

  MainPy2 --> CoreRoutes
  CoreRoutes --> StateService2
  StateService2 --> ExpComposer2
  ExpComposer2 --> SafetyPolicy2
  StateService2 --> DataLoader2
  DataLoader2 --> Repos
  Repos --> Session
  Session --> PostgreSQL2[("PostgreSQL 16")]
  DataLoader2 -.->|Fallback| JSONFiles["JSON Seed Files"]
  StateService2 -->|Python import| AIGenerator
Loading

Request Lifecycle — Complete Sequence Diagram

This shows the exact execution path when a client requests GET /experience/{customer_id} — the core endpoint driving the adaptive UI:

sequenceDiagram
  autonumber
  participant Client as Mobile App
  participant API as FastAPI Router
  participant State as StateService
  participant Data as DataLoader / DB
  participant AI as AI Pipeline
  participant SDUI as ExperienceComposer

  Client->>API: GET /api/v1/experience/{id}
  API->>State: get_state(customer_id)
  
  alt Memory Cache Hit
    State-->>API: Return Cached CustomerState
  else Memory Cache Miss
    State->>Data: load_customer_data()
    Data-->>State: Customer Data (PostgreSQL or JSON Seed Fallback)
    State->>AI: generate_state(features, signals)
    AI-->>State: Enriched CustomerState
    State->>State: Cache in Memory (O(1) TTL)
  end
  
  State->>SDUI: compose(state, recommendations)
  SDUI->>SDUI: Apply Safety Policy Filter (DTI Cap 0.40)
  SDUI->>SDUI: Classify Attention Layers (DO, KNOW, PLAN, CONSIDER)
  SDUI-->>State: Final ExperienceConfigModel
  State-->>API: ExperienceConfig JSON
  API-->>Client: 200 OK JSON Response
Loading

All API Endpoints

Base URL: http://localhost:8000 | API Prefix: /api/v1

Category Method Endpoint Purpose Auth Key Validation
Root GET /health Health check None —
Root GET /inspector AI decision dashboard (HTML) None —
Root GET /voice-inspector SLM simulator dashboard (HTML) None —
Core GET /api/v1/customer/{customer_id} Full customer state (health, signals, recs) None 404 if not found
Core GET /api/v1/experience/{customer_id} SDUI experience config (hero, cards, actions) None 404 if not found
Auth POST /api/v1/auth/pin/setup Cryptographic PIN creation None PIN format
Auth POST /api/v1/auth/pin/verify PIN verification with rate limiting None 403 if locked, 5 attempts max
Cards GET /api/v1/cards/{customer_id} Card states (is_locked, limits) None 404 if not found
Cards POST /api/v1/cards/controls Update card lock/limits None Customer exists
Txns GET /api/v1/transactions/{customer_id} Combined runtime + historic transactions None 404 if not found
Pay POST /api/v1/payments/transfer Money transfer Card lock check 403 if locked, 400 if insufficient
Loans POST /api/v1/loans/disburse Instant credit (max ₹1,50,000) None Amount bounds
AI GET /api/v1/assistant/init Initialize Mitra chat (greeting by language) None language param (en/hi/gu)
AI POST /api/v1/assistant/chat Conversational endpoint None Message body
AI POST /api/v1/assistant/intent Structured intent execution (CHECK_BALANCE, etc.) None Intent + language
Voice POST /api/v1/voice/intent Legacy voice classification None Voice data
Events POST /api/v1/events Generic banking event ingestion None BankingEventModel
Demo POST /api/v1/scenario/switch Switch demo scenario None scenario + customer_id

Core Services Detail

StateService (apps/backend/app/services/state_service.py) — The central orchestrator:

  • get_state(): Memory cache → DataLoader → AI pipeline → safe fallback (never fails)
  • switch_scenario(): Flush memory cache, switch target scenario context
  • ingest_event(): Update balance mathematically, track metadata, embed recommendation overrides
  • execute_payment(): Verify card unlocked → check funds → credit mock ledger → emit event
  • disburse_loan(): Up to ₹1,50,000 instant credit → credit balance → emit event
  • set_customer_pin() / verify_customer_pin(): PBKDF2-HMAC-SHA256 (100k iterations), constant-time comparison, rate limiting
  • submit_kyc(): PAN regex ^[A-Z]{5}[0-9]{4}[A-Z]$, Aadhaar regex ^\d{12}$
  • submit_medical_claim(), pause_mandate(), request_emi_grace(), split_emi(), sweep_deficit_for_emi(): Simulated banking operations

SafetyPolicyFilter (apps/backend/app/services/safety_policy.py) — Ethical guardrail:

  • evaluate_financial_stress(): DTI > 0.40 OR critical EMI pressure → stressed
  • filter_recommendations(): Iterates recommendations; any matching {loan, payday, credit, personal_loan} → suppressed=true, priority=0
  • apply_module_policies(): Restricts loan module visibility, prioritizes cashflow advisory modules

BehavioralEngine (apps/backend/app/services/behavior_engine.py) — Time-aware context:

  • analyze_habits(): Maps recurring transactions to daily/weekly behavioral schemas
  • evaluate_current_relevance(): datetime.now() → Mon-Fri 07:45-09:30 = commute prompt, Sunday evening = dining suggestion

ExperienceComposer (apps/backend/app/experience/composer.py) — SDUI generator:

  • compose(): CustomerState + AI recommendations → ExperienceConfigModel
  • _determine_layer(): Priority integer → DO (immediate) | KNOW (awareness) | PLAN (future) | CONSIDER (low-priority)

State Resolution Flow

flowchart TD
  Start["get_state: customer_id"] --> CacheCheck{"Memory Cache Hit?"}
  CacheCheck -->|Yes| ReturnCached["Return Cached State: O(1) Lookup"]
  CacheCheck -->|No| LoadData["DataLoader: load_customer_data"]
  
  LoadData --> DBCheck{"PostgreSQL Reachable?"}
  DBCheck -->|Yes| QueryDB["Query via Repositories"]
  DBCheck -->|No| JSONFallback["Fallback: Read JSON Seed Files"]
  
  QueryDB --> RunAI["Run AI Intelligence Pipeline"]
  JSONFallback --> RunAI
  
  RunAI --> AICheck{"Pipeline Success?"}
  AICheck -->|Yes| BuildState["Build CustomerStateModel and Apply Behavioral Engine"]
  AICheck -->|No| SafeFallback["Create Safe Fallback Profile"]
  
  BuildState --> CacheStore["Store in Memory Cache"]
  SafeFallback --> CacheStore
  CacheStore --> ReturnState["Return CustomerStateModel"]
  ReturnCached --> ReturnState
Loading

Experience Composition Flow

flowchart TD
  Input["CustomerStateModel and AI Recommendations"] --> LayerClassify["Classify into Attention Layers"]
  
  LayerClassify --> DO["DO Layer: Priority 8+ (Overdue EMI, Card Lock, Fraud)"]
  LayerClassify --> KNOW["KNOW Layer: Priority 5-7 (Spend Spike, Balance Alert)"]
  LayerClassify --> PLAN["PLAN Layer: Priority 3-4 (SIP Investment, Insurance)"]
  LayerClassify --> CONSIDER["CONSIDER Layer: Priority 1-2 (Card Upgrade, Minor Offers)"]
  
  DO --> HeroCard["Generate Hero Card: Most Urgent Item"]
  KNOW --> ContextCards["Build Context Cards Array"]
  PLAN --> ContextCards
  CONSIDER --> ContextCards
  
  HeroCard --> DraftConfig["Draft ExperienceConfig"]
  ContextCards --> DraftConfig
  
  DraftConfig --> SafetyCheck{"SafetyPolicyFilter: Stressed?"}
  SafetyCheck -->|DTI above 0.40| Suppress["Suppress Credit Products and Hide Loans"]
  SafetyCheck -->|Healthy| PassThrough["Pass Through: All Recommendations Visible"]
  
  Suppress --> FinalConfig["Final ExperienceConfigModel"]
  PassThrough --> FinalConfig
  
  FinalConfig --> OutputNode["JSON Response to Frontend"]
Loading

Safety Policy Filter Flow

flowchart TD
  Input2["Draft Recommendations from AI Engine"] --> StressEval{"Evaluate Financial Stress"}
  
  StressEval -->|DTI above 0.40| STRESSED["STRESSED"]
  StressEval -->|Critical EMI Pressure| STRESSED
  StressEval -->|Declining Savings Trend| STRESSED
  StressEval -->|None of the Above| HEALTHY["HEALTHY"]
  
  STRESSED --> FilterLoop["Filter Recommendations Loop"]
  
  FilterLoop --> CheckCategory{"Category Match?"}
  CheckCategory -->|Borrowing Products| SuppressRec["SET suppressed = true - SET priority = 0 - Suppressed due to financial stress"]
  CheckCategory -->|Safety and Savings Products| KeepRec["KEEP recommendation - May increase priority"]
  
  SuppressRec --> ModulePolicies["Apply Module Policies"]
  KeepRec --> ModulePolicies
  
  HEALTHY --> ModulePolicies
  
  ModulePolicies --> RestrictLoan["Restrict Loan Module Display"]
  ModulePolicies --> PrioritizeCashflow["Prioritize Cashflow Advisory Modules"]
  
  RestrictLoan --> SafeConfig["Safe Configuration Output"]
  PrioritizeCashflow --> SafeConfig
Loading

Payment Transfer — Complete Sequence Diagram

sequenceDiagram
  participant User as User
  participant Store as Zustand Store
  participant Bio as Biometrics
  participant API as BankingApi
  participant Routes as routes.py
  participant State as StateService
  participant Cards as _card_controls
  participant Balance as Balance Check
  participant Ledger as Mock Ledger
  participant Event as Event Emitter

  User->>Store: Tap Pay Metro Rs. 40
  Store->>Bio: requestPaymentAuth()
  Bio->>Bio: Device Biometrics / PIN
  alt Auth Failed
    Bio-->>Store: Authentication Failed
    Store-->>User: Show Error
  else Auth Success
    Bio-->>Store: Authenticated
    Store->>API: POST /payments/transfer
    API->>Routes: Route to handler
    Routes->>State: execute_payment(req)
    
    State->>Cards: Check is_locked
    alt Card Locked
      Cards-->>State: is_locked = true
      State-->>Routes: PermissionError
      Routes-->>API: 403 Forbidden
      API-->>Store: Error Response
      Store-->>User: Card is locked
    else Card Active
      Cards-->>State: is_locked = false
      State->>Balance: Check available >= amount
      alt Insufficient Funds
        Balance-->>State: Insufficient
        State-->>Routes: ValueError
        Routes-->>API: 400 Bad Request
        API-->>Store: Error Response
        Store-->>User: Insufficient balance
      else Funds Available
        Balance-->>State: Sufficient
        State->>Ledger: Generate TXN_UPI_... ID
        State->>Ledger: Prepend to _in_memory_transactions
        State->>State: Subtract from balance
        State->>Event: ingest_event(payment_event)
        Event-->>State: State refreshed
        State-->>Routes: Success + Updated Balance
        Routes-->>API: 200 OK
        API-->>Store: Update balance
        Store-->>User: Animated Checkmark
      end
    end
  end
Loading

Error Handling & Graceful Degradation

Error Condition Detection Response Code
Customer not found KeyError in StateService 404 Not Found HTTPException(404)
Invalid input ValueError / Pydantic validation 400 Bad Request HTTPException(400)
Card locked PermissionError in execute_payment 403 Forbidden HTTPException(403)
PIN locked out failed_attempts >= 5 429 Rate Limited (15min) HTTPException(429)
DB offline SQLAlchemy.exc caught by DataLoader Fallback to JSON seed files 200 (degraded)
AI pipeline crash Exception caught by StateService _create_safe_fallback_state() 200 (generic)
Insufficient funds Balance check in execute_payment 400 Bad Request HTTPException(400)

Frontend Architecture — Deep Dive

Frontend Architecture Diagram

flowchart TD
  AppTsx["App.tsx Entry"] --> ThemeProvider["ThemeProvider"]
  ThemeProvider --> Navigator["AppNavigator Router"]
  
  Navigator --> HomeScreen["AdaptiveHomeScreen (SDUI Engine)"]
  Navigator --> ChatScreen["MitraChatScreen (AI Assistant)"]
  Navigator --> PayScreen["PaymentsScreen (1-Tap and Mandates)"]
  Navigator --> TxnScreen["TransactionsScreen (Activity Logs)"]
  Navigator --> ModalOverlay["Journey Modals (KYC, Insurance, Medical)"]
  
  HomeScreen --> Store["useCustomerStore (Zustand Core)"]
  ChatScreen --> Store
  PayScreen --> Store
  ModalOverlay --> Store
  
  Store --> Api["BankingApi Client"]
  Api -.->|Offline Fallback| EdgeEngine["MiniCPM5EdgeEngine (On-Device NLP)"]
  
  HomeScreen --> ContextCards["Adaptive Context Cards (DO, KNOW, PLAN)"]
  ContextCards --> ThemeTokens["Design Tokens (Colors and Typography)"]
Loading

Screen Navigation State Diagram

flowchart TD
  Launch["App Launch"] --> Home["AdaptiveHomeScreen (Main Dashboard)"]
  
  Home <--> TabPay["PaymentsScreen Tab"]
  Home <--> TabTxn["TransactionsScreen Tab"]
  Home <--> TabInsights["InsightsScreen Tab"]
  Home <--> TabProfile["ProfileScreen Tab"]
  Home <--> TabMore["More / Settings Tab"]
  
  Home --> KYC["KYC Journey Modal"]
  Home --> Medical["Medical Emergency Modal"]
  Home --> Insurance["Insurance Claim Modal"]
  TabMore --> DemoLab["Demo Lab Scenario Switcher"]
  
  KYC -.->|Dismiss| Home
  Medical -.->|Dismiss| Home
  Insurance -.->|Dismiss| Home
  DemoLab -.->|Dismiss| TabMore
Loading

Data Fetching & Offline Fallback Sequence

flowchart TD
  AppInit["App / Pull-to-Refresh: fetchStateAndContext()"] --> APIReq["BankingApi: GET /api/v1/experience/{id}"]
  
  APIReq --> TimeoutGuard{"Request Status (2.5s Timeout Guard)"}
  
  TimeoutGuard -->|Online 200 OK| LiveSuccess["Live Backend: Return ExperienceConfig JSON"]
  TimeoutGuard -->|Timeout > 2.5s| EdgeEngine["Edge Fallback: MiniCPM-5 On-Device NLP and ONNX"]
  TimeoutGuard -->|Network Error| CacheBundle["Cache Fallback: Load Offline Scenario Bundle"]
  
  LiveSuccess --> UpdateStore["useCustomerStore: Update Reactive State"]
  EdgeEngine --> UpdateStore
  CacheBundle --> UpdateStore
  
  UpdateStore --> RenderHome["AdaptiveHomeScreen: Re-render Dynamic Dashboard"]
Loading

Payment Authentication Sequence

flowchart TD
  UserTap["User: Tap Payment Mandate (e.g. Metro Rs. 40)"] --> TriggerAuth["Store: requestPaymentAuth()"]
  TriggerAuth --> DeviceAuth{"Device Biometrics Available?"}
  
  DeviceAuth -->|Yes| BioScan["expo-local-authentication: Biometric Scan"]
  DeviceAuth -->|No| PINInput["MPIN Fallback: POST /auth/pin/verify"]
  
  BioScan --> BioResult{"Scan Passed?"}
  BioResult -->|Yes| ExecPay["POST /payments/transfer"]
  BioResult -->|No| ErrToast["Show Error Toast: Authentication Failed"]
  
  PINInput --> PINResult{"PIN Valid?"}
  PINResult -->|Yes| ExecPay
  PINResult -->|No| ErrToast
  
  ExecPay --> SuccessResp["200 OK: Balance Updated and Mandate Paid"]
  SuccessResp --> UIFeedback["AdaptiveHomeScreen: Animated Checkmark"]
Loading

Adaptive Home Screen Flow

flowchart TD
  ExConfig["ExperienceConfig from Backend"] --> ScenarioDetect{"Active Scenario State"}
  
  ScenarioDetect -->|Normal or Surplus| NormalHero["Hero: Welcome and Balance"]
  NormalHero --> NormalCards["Context Cards: Insights and Tips"]
  NormalCards --> NormalActions["Actions: Pay, Transfer, Scan"]
  
  ScenarioDetect -->|Financial Stress| StressHero["Hero: Wellness Support"]
  StressHero --> StressCards["Context Cards: Cashflow Advisory"]
  StressCards --> StressActions["Actions: Budgeting and Relief Options"]
  
  ScenarioDetect -->|Medical Event| MedHero["Hero: Emergency Assistance"]
  MedHero --> MedCards["Context Cards: Insurance Claims and Instant Loan"]
  
  ScenarioDetect -->|Fraud Alert| FraudHero["Hero: Security Alert"]
  FraudHero --> FraudCards["Context Cards: Review Suspicious Activity"]
Loading

State Management Architecture

flowchart TD
  UserAction["User Interaction: Tap, Pull, Navigate"] --> StoreDispatch["Store Action Dispatcher"]
  
  StoreDispatch --> Router{"Operation Type"}
  Router -->|Network Fetch| ApiCall["BankingApi HTTP Client"]
  Router -.->|Offline Fallback| EdgeEngine["MiniCPM5EdgeEngine Local NLP"]
  Router -->|Authentication| BioService["expo-local-authentication"]
  
  ApiCall --> StoreCore["useCustomerStore: Zustand Central Store"]
  EdgeEngine --> StoreCore
  BioService --> StoreCore
  
  StoreCore --> ReactiveUI["Reactive UI: AdaptiveHomeScreen, MitraChatScreen, PaymentsScreen"]
Loading

AI & Intelligence Engine — Deep Dive

Complete Intelligence Pipeline Diagram

flowchart TD
  DataSources["7 Raw Data Sources (CBS, UPI, SMS, CIBIL, BBPS, NCMC, KYC)"] --> Harmonization["Data Harmonization (harmonizer.py: MD5 Dedup, ISO Dates, Conflict Resolution)"]
  Harmonization --> FeatureExtraction["Feature Extraction (50/30/20 Rule, 9 Spend Categories, Cash Flow Forecast)"]
  FeatureExtraction --> SignalDetection["Signal Detection (Commute Habits, EMI Pressure, Life Events, DTI Ratio)"]
  SignalDetection --> StateGeneration["Customer State Generation (Financial Health Classifier: Thriving, Stable, Tight, Stress)"]
  StateGeneration --> RecommendationEngine["Recommendation Engine (Multi-Factor Utility Scorer + 7 Bharat Archetypes)"]
  RecommendationEngine --> ComplianceLayer["Compliance Layer (RBI DTI 0.40 Cap, DPDP Purpose, SHA-256 Crypto Ledger)"]
  ComplianceLayer --> OutputState["customer-state.json to Backend ExperienceComposer"]
Loading

Voice Processing Pipeline — Complete Sequence

flowchart TD
  UserSpeech["User Spoken Utterance: Mera khata balance kitna hai?"] --> STT["Speech-to-Text Conversion (Web Speech API / Native)"]
  STT --> SLM["On-Device MiniCPM-5 INT4 SLM (~1.85GB RAM)"]
  
  SLM --> PolicyCheck["Zero-Leakage Policy: No Raw Banking History in Prompt"]
  PolicyCheck --> Intent["Classify Intent: CHECK_BALANCE (Confidence 0.94)"]
  
  Intent --> BackendFetch["POST /assistant/intent to FastAPI Backend"]
  BackendFetch --> FactStore["Database / Trusted Fact Store: Fetch Balance (Rs. 45,230)"]
  
  FactStore --> ResponseVerbalizer["On-Device SLM: Verbalize Fact in Hindi"]
  ResponseVerbalizer --> AudioOut["Audio Output: Aapka khata balance Rs. 45,230 hai"]
Loading

Zero-Leakage Voice Security Architecture

flowchart LR
  subgraph Visible["Yes Data SLM CAN Access"]
    Intent["User's spoken intent<br/>(natural language text)"]
    TrustedFacts2["Pre-computed trusted facts<br/>- Current balance<br/>- Next EMI due date<br/>- Card lock status<br/>- Bill amounts"]
    Templates["Response templates<br/>(Localized strings)"]
  end

  subgraph Blocked["Data SLM CANNOT Access"]
    TxnHistory["Transaction history"]
    SpendingData["Spending patterns"]
    CreditScore["CIBIL credit score"]
    PersonalData["PAN / Aadhaar"]
    Recommendations2["AI recommendations"]
    FinancialHealth2["Financial health classification"]
    DTIRatio["DTI ratio"]
  end

  subgraph SLMProcess["MiniCPM-5 SLM Process"]
    Parse["1. Parse user utterance"]
    Classify["2. Classify intent"]
    Verbalize["3. Verbalize trusted fact"]
  end

  Intent -->|Allowed Spoken Input| Parse
  TrustedFacts2 -->|Allowed Pre-computed Facts| Verbalize
  TxnHistory -.->|BLOCKED by Zero-Leakage Policy| Parse
  PersonalData -.->|BLOCKED by Zero-Leakage Policy| Parse

  style Blocked fill:#ffcdd2,stroke:#c62828
  style Visible fill:#c8e6c9,stroke:#2e7d32
Loading

Database Architecture — Deep Dive

Entity Relationship Diagram

erDiagram
  customers ||--o{ accounts : "has (CASCADE)"
  customers ||--o{ recurring_payments : "has (CASCADE)"
  customers ||--o{ customer_events : "has (CASCADE)"
  customers ||--o{ customer_products : "has (CASCADE)"
  customers ||--o{ consent_preferences : "has (CASCADE)"
  accounts ||--o{ transactions : "contains (CASCADE)"
  products ||--o{ customer_products : "offered as (CASCADE)"

  customers {
    varchar64 customer_id PK "Primary Key"
    varchar first_name "Required"
    varchar last_name "Required"
    varchar email "Unique"
    varchar phone "Required"
    date date_of_birth "Required"
    varchar pan_number "Regex: A-Z5 0-9-4 A-Z"
    varchar aadhaar_number "Regex: 12 digits"
    varchar address_line1 "Required"
    varchar address_line2 "Optional"
    varchar city "Required"
    varchar state "Required"
    varchar pincode "Required"
    varchar kyc_status "pending/verified/rejected"
    varchar language_preference "en/hi/gu"
    varchar occupation "Required"
    decimal annual_income "Required"
    timestamp created_at "Auto"
    timestamp updated_at "Auto"
  }

  accounts {
    varchar account_id PK "Primary Key"
    varchar customer_id FK "Index: customer_id"
    varchar account_type "savings/current/fd"
    varchar account_number "Unique"
    varchar ifsc_code "Required"
    decimal balance "Required"
    varchar currency "INR default"
    varchar status "active/frozen/closed"
    timestamp opened_at "Required"
    timestamp updated_at "Auto"
  }

  transactions {
    varchar transaction_id PK "Primary Key"
    varchar account_id FK "Required"
    varchar customer_id "Index: customer_id + category"
    varchar type "credit/debit"
    decimal amount "Required"
    varchar currency "INR default"
    varchar category "food/transport/shopping/etc"
    varchar description "Required"
    varchar merchant_name "Optional"
    varchar reference_number "Unique"
    varchar status "completed/pending/failed"
    timestamp transaction_date "Index: customer_id + date"
    timestamp created_at "Auto"
  }

  recurring_payments {
    varchar payment_id PK "Primary Key"
    varchar customer_id FK "Index: customer_id"
    varchar account_id FK "Required"
    varchar payee_name "Required"
    decimal amount "Required"
    varchar frequency "daily/weekly/monthly"
    varchar category "Required"
    date next_due_date "Required"
    varchar status "active/paused/completed"
    boolean auto_pay "Default: false"
    timestamp created_at "Auto"
  }

  customer_events {
    varchar event_id PK "Primary Key"
    varchar customer_id FK "Index: customer_id + type"
    varchar event_type "Required"
    text event_data "JSON payload"
    varchar severity "info/warning/critical"
    varchar source "system/user/ai"
    timestamp created_at "Auto"
  }

  products {
    varchar product_id PK "Primary Key"
    varchar name "Required"
    varchar category "loan/insurance/investment"
    text description "Required"
    decimal interest_rate "Required"
    decimal min_amount "Required"
    decimal max_amount "Required"
    int tenure_months "Required"
    text eligibility_criteria "JSON"
    text features "JSON"
    varchar status "active/discontinued"
    timestamp created_at "Auto"
  }

  customer_products {
    varchar id PK "Primary Key"
    varchar customer_id FK "Index + Unique with product_id"
    varchar product_id FK "Required"
    varchar status "applied/approved/active/closed"
    timestamp applied_at "Required"
    timestamp approved_at "Optional"
    decimal disbursed_amount "Optional"
    decimal interest_rate "Optional"
    int tenure_months "Optional"
    decimal emi_amount "Optional"
    date next_emi_date "Optional"
  }

  consent_preferences {
    varchar consent_id PK "Primary Key"
    varchar customer_id FK "Index: customer_id"
    varchar consent_type "data_sharing/marketing/analytics"
    varchar status "granted/revoked"
    timestamp granted_at "Required"
    timestamp expires_at "Optional"
    text purpose "Required"
  }

  alembic_version {
    varchar32 version_num PK "Migration Version"
  }
Loading

Data Access Layer Architecture

flowchart TD
  subgraph APILayerDB["API Layer"]
    Route["routes.py endpoint handler"]
  end

  subgraph ServiceLayerDB["Service Layer"]
    StateServiceDB["StateService"]
  end

  subgraph DataAccessDB["Data Access Layer"]
    DataLoaderDB["DataLoader<br/>(Primary Access Point)"]
    
    subgraph Repos["Repositories"]
      CustRepoDB["CustomerRepository<br/>- get_by_id()<br/>- get_customer_summary()"]
      TxnRepoDB["TransactionRepository<br/>- get_by_customer()<br/>- get_by_account()"]
      EvtRepoDB["EventRepository<br/>- get_events()"]
      ProdRepoDB["ProductRepository<br/>- get_products()"]
    end
  end

  subgraph ORMLayer["ORM Layer"]
    SQLAlchemy["SQLAlchemy 2.0<br/>(Declarative Models)"]
    SessionDB["session.py<br/>- Engine + Connection Pool<br/>- Auto WSL IPv4 detection<br/> (PowerShell Get-NetNeighbor)<br/>- Fallback: localhost"]
  end

  subgraph StorageDB["Storage"]
    PostgreSQLDB[("PostgreSQL 16<br/>(Docker :5432)<br/>9 Tables")]
    JSONSeedDB["JSON Seed Files<br/>(data/seed/)<br/>- customers.json (1.2k)<br/>- transactions.json (127k+)"]
    ScenarioFilesDB["Scenario Overrides<br/>(data/scenarios/)<br/>- normal.json<br/>- financial-stress.json<br/>- life-change.json"]
  end

  Route --> StateServiceDB
  StateServiceDB --> DataLoaderDB
  DataLoaderDB --> CustRepoDB
  CustRepoDB --> SQLAlchemy
  SQLAlchemy --> SessionDB
  SessionDB --> PostgreSQLDB
  
  DataLoaderDB -.->|PostgreSQL Offline Fallback| JSONSeedDB
  DataLoaderDB -.->|Scenario Override| ScenarioFilesDB
Loading

Migration & Introspection Flow

flowchart LR
  subgraph Development["Development"]
    Dev["Developer writes<br/>migration"]
  end

  subgraph AlembicMgr["Alembic Migration Manager"]
    AlembicEnv["alembic/env.py"]
    AlembicVer["alembic/versions/<br/>(Migration Files)"]
    AlembicIni["alembic.ini<br/>(Configuration)"]
  end

  subgraph Database3["PostgreSQL"]
    Schema["Live Database Schema<br/>(9 Tables)"]
    AlembicTable["alembic_version table<br/>(Tracks current version)"]
  end

  subgraph PrismaTool["Prisma (Read-Only)"]
    PrismaIntrospect["prisma db pull<br/>(Introspects live DB)"]
    PrismaSchema["prisma/schema.prisma<br/>(Generated schema file)"]
    PrismaStudio["Prisma Studio<br/>(Visual DB Browser)"]
  end

  Dev -->|alembic revision| AlembicVer
  AlembicVer -->|alembic upgrade head| Schema
  Schema --> AlembicTable
  Schema -->|npm run db:introspect| PrismaIntrospect
  PrismaIntrospect --> PrismaSchema
  PrismaSchema -->|npm run db:studio| PrismaStudio

  style PrismaTool fill:#e3f2fd
  style AlembicMgr fill:#fff3e0
Loading

Seed Data Pipeline

flowchart TD
  Generator["scripts/generate_seed_data.py<br/>(~540 lines)"]
  Generator -->|Generates| CustJSON["data/seed/customers.json<br/>(1,200 Mock Profiles)"]
  Generator -->|Generates| TxnJSON["data/seed/transactions.json<br/>(127,000+ Transactions)"]
  
  Seeder["scripts/seed_database.py"]
  CustJSON --> Seeder
  TxnJSON --> Seeder
  
  Seeder -->|SQLAlchemy bulk_insert_mappings in 10k batches| DB2[("PostgreSQL 16")]
  
  Seeder -->|Step 1| Wipe["Wipe existing data<br/>(Clean slate)"]
  Seeder -->|Step 2| Reset["Reset schema<br/>(Recreate tables)"]
  Seeder -->|Step 3| Insert["Bulk insert<br/>(10k per batch)"]
  
  ScenarioFiles["data/scenarios/<br/>- normal.json<br/>- financial-stress.json<br/>- life-change.json"]
  ScenarioFiles -->|Runtime Override| StateService3["StateService<br/>(switch_scenario)"]
Loading

Authentication & Security — Deep Dive

End-to-End Authentication & MPIN Flow

ABC Bank implements a banking-grade customer authentication flow combining mobile OTP verification, 4-digit MPIN credentials (or device biometrics), and statutory DPDP Act 2023 compliance agreements.

sequenceDiagram
  autonumber
  actor User as Customer / User
  participant UI as AuthScreen (React Native)
  participant Store as customerStore (Zustand)
  participant AuthAPI as Auth Service / Backend
  participant SMS as SMS OTP Gateway (Mock/Live)

  Note over User, UI: Stage 1: Phone Entry and KYC Identifier
  User->>UI: Inputs 10-digit mobile number (+91)
  UI->>SMS: Request SMS OTP challenge
  SMS-->>UI: OTP dispatched (e.g. 123456 / Dev auto-hint)

  Note over User, UI: Stage 2: OTP Verification
  User->>UI: Enters 6-digit numeric OTP
  UI->>UI: Validate OTP against challenge token

  Note over User, UI: Stage 3: MPIN Setup / Quick Login
  alt First-time Customer
    UI->>UI: Prompt 4-digit MPIN creation + confirmation
    UI->>AuthAPI: POST /auth/pin/setup (PBKDF2-HMAC-SHA256)
    AuthAPI-->>UI: PIN Hash and Salt persistent registration
  else Returning Customer
    UI->>UI: Prompt 4-digit MPIN or Biometric (Fingerprint/Face)
    UI->>AuthAPI: POST /auth/pin/verify (hmac.compare_digest)
    AuthAPI-->>UI: 200 OK (fail_count reset)
  end

  Note over User, UI: Stage 4: DPDP Act 2023 and RBI Statutory Consent
  alt New Account / Updated Compliance Scope
    UI->>User: Display DPDP Statutory Disclosures Modal
    Note over UI: Disclose Data Fiduciary, Purpose, Account Aggregator AA,<br/>Right to Revoke and Grievance DPO Contact
    User->>UI: Accepts statutory terms and grants consent
    UI->>Store: recordDPDPConsent(timestamp, version=2023.1)
  end

  Note over User, UI: Stage 5: Session Initialization
  UI->>Store: setAuthenticated(true, customerProfile)
  Store-->>UI: Hydrate active scenario and banking dashboard
  UI-->>User: Transition to Main Application Shell
Loading

Dual Authentication Architecture (Mobile OTP / MPIN & NetBanking JWT)

ABC Bank supports two complementary authentication paths designed to accommodate both modern Bharat mobile banking and standard internet banking / developer evaluation:

  1. Bharat Mobile Banking (OTP + MPIN + Biometric):

    • Evaluator-friendly 1-tap OTP simulation (auto-hints verified code 482910 or 000000).
    • Hardware-bound 6-digit MPIN validation with cryptographic PIN verify (/auth/pin/verify).
    • 1-tap evaluator persona presets (Salaried, Surplus, Tight Buffer, Medical Emergency, Fraud Alert).
  2. NetBanking / Session Token Architecture (JWT HS256):

    • Directly authenticates via POST /api/v1/auth/login accepting Email, Phone number, or Customer ID.
    • Authoritative HS256 JWT tokens generated with standard RFC 7519 claims (sub, iat, exp).
    • Client API SDK automatically attaches Authorization: Bearer <token> to all downstream banking requests.
    • New user registration via POST /api/v1/auth/register dynamically provisions customer records into the relational database and seed store.

DPDP Act 2023 & RBI Statutory Consent Architecture

In compliance with the Digital Personal Data Protection (DPDP) Act, 2023 and RBI Master Direction on IT Governance, Risk and Controls, ABC Bank enforces strict transparency, consent gating, and revocation capabilities before any financial or behavioral data is processed.

Statutory Principles Enforced

Dimension DPDP 2023 Requirement ABC Bank Implementation
Data Fiduciary Identity Clear disclosure of processing entity Displayed as ABC Bank Ltd.
Notice & Purpose Specification Purpose must be clearly stated in plain language Explicitly itemizes Account Aggregator retrieval, contextual SDUI personalization, and fraud mitigation.
Vernacular Accessibility Consent notices must be accessible in Schedule 8 languages UI supports English, Hindi, and Gujarati consent summaries.
Right to Withdraw Consent Data principal can withdraw consent as easily as giving it Toggle available under ProfileScreen -> Statutory Compliance & DPDP 2023 to immediately revoke processing rights.
Data Minimization & Retention Retain data only as long as necessary for specified purpose Session caches and AI telemetry strictly expire; no raw transaction payloads stored in AI agent logs.
Grievance Redressal Mandatory designation of Data Protection Officer (DPO) Statutory DPO contact (dpo@abcbank.in, Grievance Officer, Mumbai) accessible directly from the consent sheet.
flowchart TD
  AppLaunch([App Launch]) --> CheckAuth{Authenticated?}
  CheckAuth -->|No| AuthGate[AuthScreen: Mobile + OTP + MPIN]
  AuthGate --> ConsentCheck{DPDP Consent Recorded?}
  ConsentCheck -->|No| ConsentModal[DPDP Statutory Consent Modal]
  ConsentModal --> UserAction{User Decision}
  UserAction -->|Reject or Exit| TerminateSession[Session Blocked / Guest Only]
  UserAction -->|Accept| RecordConsent[Store SHA-256 Consent Proof and Timestamp]
  RecordConsent --> UnlockVault[Unlock Full Banking SDUI and Accounts]
  ConsentCheck -->|Yes| UnlockVault
  UnlockVault --> InAppProfile[ProfileScreen: DPDP Management]
  InAppProfile --> RevokeAction{Revoke Consent?}
  RevokeAction -->|Yes| StripTelemetry[Anonymize Local Cache and Block Personalization]
Loading

PIN Authentication — Complete Lifecycle

stateDiagram-v2
  [*] --> NoPIN: Customer Created

  state NoPIN {
    [*] --> AwaitSetup: No PIN Configured
  }

  NoPIN --> PINActive: POST /auth/pin/setup<br/>(PBKDF2-HMAC-SHA256, 100k iterations)

  state PINActive {
    [*] --> Ready: PIN Hash + Salt Stored
    Ready --> Verifying: POST /auth/pin/verify
    
    Verifying --> Success: hmac.compare_digest == True
    Verifying --> Failed: hmac.compare_digest == False
    
    Success --> Ready: Reset fail_count = 0
    Failed --> IncrementFails: fail_count++
    
    IncrementFails --> Ready: fail_count under 5
    IncrementFails --> Lockout: fail_count >= 5
  }

  state Lockout {
    [*] --> Frozen: locked_until = now + 15min
    Frozen --> Cooldown: 15 minutes elapsed
  }

  Lockout --> PINActive: Cooldown complete

  note right of PINActive
    Storage: In-memory dict
    _customer_pins = {
      customer_id: {
        hash: bytes,
        salt: hex(16),
        failed_attempts: int,
        locked_until: datetime or None
      }
    }
  end note
Loading

PIN Verification with Rate Limiting — Complete Sequence

sequenceDiagram
  participant Client as Client
  participant Router as routes.py
  participant Auth as StateService
  participant Store as _customer_pins Dict
  participant Crypto as PBKDF2-HMAC-SHA256

  Client->>Router: POST /auth/pin/verify - {customer_id, pin}
  Router->>Auth: verify_customer_pin(id, pin)
  
  Auth->>Store: Lookup customer_id
  alt No PIN Set
    Store-->>Auth: KeyError
    Auth-->>Router: 404 Not Found
    Router-->>Client: {error: PIN not configured}
  else PIN Exists
    Store-->>Auth: {hash, salt, fails, locked_until}
    
    Auth->>Auth: Check locked_until
    alt Currently Locked
      Note over Auth: locked_until > datetime.now()
      Auth-->>Router: 429 Rate Limited
      Router-->>Client: {error: Account locked, - retry_after: 15 minutes}
    else Not Locked
      Auth->>Crypto: PBKDF2(pin, salt, iterations=100000)
      Crypto-->>Auth: Computed hash
      
      Auth->>Auth: hmac.compare_digest(stored, computed)
      Note over Auth: Constant-time comparison<br/>(prevents timing attacks)
      
      alt Match
        Auth->>Store: Reset failed_attempts = 0
        Auth-->>Router: 200 Success
        Router-->>Client: {verified: true}
      else No Match
        Auth->>Store: failed_attempts++
        
        alt failed_attempts >= 5
          Auth->>Store: locked_until = now + 15min
          Auth-->>Router: 429 Rate Limited
          Router-->>Client: {error: Too many attempts, - locked_for: 15 minutes}
        else failed_attempts under 5
          Auth-->>Router: 401 Unauthorized
          Router-->>Client: {error: Invalid PIN, - attempts_remaining: N}
        end
      end
    end
  end
Loading

Card Security State Machine

stateDiagram-v2
  [*] --> Unlocked: Default state

  state Unlocked {
    [*] --> Active
    Active: All payments allowed
    Active: ATM Yes POS Yes Online Yes
  }

  state Locked {
    [*] --> Blocked
    Blocked: Payment blocked
    Blocked: ATM No POS No Card No
  }

  Unlocked --> Locked: POST /cards/controls (lock card)
  Locked --> Unlocked: POST /cards/controls (unlock card)

  Locked --> PaymentDenied: POST /payments/transfer (ATM/POS/Card)
  PaymentDenied --> Locked: PermissionError 403

  state PaymentDenied {
    [*] --> Denied
    Denied: Card is locked error
  }

  note right of Locked
    Card controls stored in
    _card_controls dict in-memory
    per customer_id with:
    - is_locked: bool
    - atmLimit: int
    - posLimit: int
    - onlineLimit: int
  end note
Loading

Multi-Layer Authorization Architecture

flowchart TD
  Request["Incoming API Request"] --> Layer1{"Layer 1:<br/>Customer ID<br/>Exists?"}
  
  Layer1 -->|No| Reject404["404 Not Found"]
  Layer1 -->|Yes| Layer2{"Layer 2:<br/>PIN Locked Out?<br/>(Rate Limiting)"}
  
  Layer2 -->|Locked - 15min cooldown| Reject429["429 Rate Limited"]
  Layer2 -->|Not Locked| Layer3{"Layer 3:<br/>Card Locked?<br/>(For Payments)"}
  
  Layer3 -->|Locked| Reject403["403 Forbidden<br/>'Card is locked'"]
  Layer3 -->|Active| Layer4{"Layer 4:<br/>Sufficient<br/>Funds?"}
  
  Layer4 -->|Insufficient| Reject400["400 Bad Request<br/>'Insufficient balance'"]
  Layer4 -->|Sufficient| Layer5{"Layer 5:<br/>Safety Policy<br/>(For Recommendations)"}
  
  Layer5 -->|DTI above 0.40| Suppress["Suppress Credit Products<br/>(suppressed = true)"]
  Layer5 -->|Healthy| Allow["Allow All Products"]
  
  Suppress --> Layer6["Layer 6:<br/>Crypto Ledger<br/>(Log Decision)"]
  Allow --> Layer6
  
  Layer6 --> Success["Yes Action Executed"]
Loading

Ethical AI Security Architecture

flowchart TD
  AIRec["AI Recommendation<br/>Generated"] --> DTICheck{"DTI Ratio<br/>Check"}
  
  DTICheck -->|DTI above 0.40| BLOCK["BLOCK"]
  DTICheck -->|DTI <= 0.40| StressCheck{"Financial Health<br/>Classification"}
  
  StressCheck -->|stress| BLOCK
  StressCheck -->|tight| CAUTION["CAUTION<br/>(Flag but allow)"]
  StressCheck -->|stable or thriving| ALLOW["ALLOW"]
  
  BLOCK --> SuppressAll["Suppress ALL:<br/>- Personal loans<br/>- Payday advances<br/>- Credit limit increases<br/>- Credit card offers"]
  BLOCK --> ReplaceWith["Replace with:<br/>- Cashflow advisory<br/>- Emergency fund tips<br/>- Budget optimization<br/>- Auto-sweep FD suggestions"]
  
  SuppressAll --> CryptoLog["SHA-256 Crypto Ledger<br/>Log suppression with:<br/>- customer_id<br/>- product_id<br/>- reason: 'DTI 0.45 exceeds 0.40'<br/>- timestamp<br/>- hash_chain_link"]
  ReplaceWith --> CryptoLog
  
  CAUTION --> CryptoLog
  ALLOW --> CryptoLog
  
  CryptoLog --> Explanation["Counterfactual Explanation<br/>'This loan was not shown because<br/>your debt-to-income ratio (0.45)<br/>exceeds the RBI guideline of 0.40'"]
  
  Explanation --> FinalOutput["Final Recommendation<br/>List (Filtered)"]
Loading

Known Security Limitations

Limitation Current State Risk Level Production Fix Needed
CORS Policy allow_origins=["*"] High Restrict to specific domains
API Authentication No JWT/OAuth tokens; uses customer_id path params High Implement JWT bearer tokens
PIN Storage In-memory dict (lost on restart) Medium Persist to encrypted database
HTTPS Not enforced at app level High Add TLS termination
CSRF Protection None Medium Add CSRF tokens for state-changing ops
Rate Limiting Only on PIN verify (5 attempts) Medium Add global rate limiting
General Endpoint Auth No authentication on most endpoints High Add auth middleware

Data Flow Architecture — Deep Dive

End-to-End Personalization — Complete Sequence

sequenceDiagram
  participant DS as 7 Data Sources
  participant Harm as Harmonizer
  participant Feat as Feature Extractor
  participant Sig as Signal Detector
  participant State2 as State Generator
  participant Score as Recommendation Scorer
  participant Comply as Compliance Filter
  participant Crypto2 as Crypto Ledger
  participant Compose as Experience Composer
  participant Safe as Safety Policy Filter
  participant UI2 as Mobile App

  DS->>Harm: Raw banking data (CBS, UPI, SMS, - CIBIL, BBPS, NCMC, KYC)
  Harm->>Harm: MD5 deduplication
  Harm->>Harm: ISO 8601 date normalization
  Harm->>Harm: Balance conflict resolution
  Harm->>Feat: Clean, deduplicated data
  
  Feat->>Feat: 50/30/20 rule analysis
  Feat->>Feat: 9-category spend breakdown
  Feat->>Feat: 30-day cash flow forecast
  Feat->>Feat: 32 single-pass metrics
  Feat->>Sig: Feature vector
  
  Sig->>Sig: Behavioral: commute, dining, cinema
  Sig->>Sig: Financial: DTI, EMI, savings decline
  Sig->>Sig: Lifecycle: medical, marriage, job
  Sig->>State2: Signal array
  
  State2->>State2: Dual cadence check
  Note over State2: Macro (14-day) or<br/>Micro (0.162ms trigger)?
  State2->>State2: Classify financial_health
  State2->>Score: CustomerState
  
  Score->>Score: Calculate utility per product
  Note over Score: U = 0.30*A + 0.30*L<br/>+ 0.25*Ur + 0.15*Ar - R
  Score->>Score: Rank 1-5 per recommendation
  Score->>Comply: Ranked recommendations
  
  Comply->>Comply: RBI DTI cap check (above 0.40?)
  Comply->>Comply: DPDP purpose limitation
  alt DTI above 0.40
    Comply->>Comply: Suppress all credit products
  end
  Comply->>Crypto2: Decision + suppression data
  Crypto2->>Crypto2: SHA-256 hash chain append
  Crypto2->>Compose: customer-state.json
  
  Compose->>Compose: Map to attention layers
  Note over Compose: DO -> KNOW -> PLAN -> CONSIDER
  Compose->>Compose: Generate hero_card
  Compose->>Compose: Build context_cards[]
  Compose->>Safe: Draft ExperienceConfig
  
  Safe->>Safe: Re-verify stress indicators
  Safe->>Safe: Apply module policies
  Safe->>UI2: experience-config.json
  
  UI2->>UI2: Zustand store update
  UI2->>UI2: Adaptive re-render
Loading

Attention Layer Priority System

flowchart TD
  subgraph DOLayer["DO Layer (Priority >= 8)<br/>Immediate Action Required"]
    DO1["Overdue EMI Payment"]
    DO2["Card Locked - Unlock Required"]
    DO3["Fraud Alert - Review Now"]
    DO4["Medical Emergency Support"]
    DO5["KYC Expiring Today"]
  end

  subgraph KNOWLayer["KNOW Layer (Priority 5-7)<br/>Awareness Items"]
    KNOW1["Spending Up 12% This Month"]
    KNOW2["Balance Below Rs. 5,000"]
    KNOW3["Bill Due in 3 Days"]
    KNOW4["Salary Credit Expected"]
    KNOW5["FD Maturity This Week"]
  end

  subgraph PLANLayer["PLAN Layer (Priority 3-4)<br/>Future Planning"]
    PLAN1["SIP Investment Opportunity"]
    PLAN2["Insurance Renewal Due"]
    PLAN3["Tax-Saving FD Window"]
    PLAN4["Education Loan Planning"]
  end

  subgraph CONSIDERLayer["CONSIDER Layer (Priority 1-2)<br/>Low Priority Suggestions"]
    CONSIDER1["Credit Card Upgrade Available"]
    CONSIDER2["Savings Account Comparison"]
    CONSIDER3["Loyalty Reward Points"]
  end

  DO1 -->|Highest Priority Hero Card Source| HeroCard2["Hero Card<br/>(Most Urgent DO Item)"]
  KNOW1 -->|Context Cards| ContextStack["Context Card Stack"]
  PLAN1 -->|Context Cards| ContextStack
  CONSIDER1 -->|Deprioritized Cards| ContextStack
  
  HeroCard2 --> FinalUI["Final Adaptive UI"]
  ContextStack --> FinalUI

  style DOLayer fill:#ffcdd2,stroke:#c62828
  style KNOWLayer fill:#fff9c4,stroke:#f57f17
  style PLANLayer fill:#c8e6c9,stroke:#2e7d32
  style CONSIDERLayer fill:#e0e0e0,stroke:#616161
Loading

Testing Architecture

Test Architecture Diagram

flowchart TD
  subgraph AITests["AI Test Suite (ai/tests/)<br/>45 Tests, ~0.39s"]
    T1["test_massive_load.py<br/>10k transactions under 100ms"]
    T2["test_multi_source_ingestion.py<br/>SMS vs CBS conflict arbitration"]
    T3["test_personalization.py<br/>Ethical loan suppression<br/>Top-1-to-5 ranking"]
    T4["test_cadence.py<br/>Dual cadence timing"]
    T5["test_cryptoledger.py<br/>SHA-256 chain integrity"]
    T6["test_voice_slm.py<br/>Voice pipeline testing"]
  end

  subgraph AuditSuite["Audit Suite (scripts/)<br/>39 Checks, ~540 Lines"]
    A1["ONNX inference latency<br/>(under 10ms requirement)"]
    A2["Subword tokenizer<br/>vector integrity"]
    A3["XGBoost propensity<br/>extraction accuracy"]
    A4["KMeans archetype<br/>soft-clustering validity"]
    A5["DTI loan suppression<br/>(under 0.40 threshold)"]
    A6["50/30/20 spend<br/>breakdown accuracy"]
    A7["SHA-256 crypto ledger<br/>integrity verification"]
    A8["Multi-turn vernacular<br/>chatbot routing"]
  end

  subgraph Gaps["Note: Test Gaps"]
    G1["No backend API tests"]
    G2["No frontend component tests"]
    G3["No E2E integration tests"]
    G4["No CI/CD pipeline"]
  end

  T1 -->|pytest test suite| Results["111 Tests Passing<br/>(45 AI + 66 Backend)"]
  A1 -->|39-check audit run| Results

  style Gaps fill:#fff3e0,stroke:#e65100
Loading

Commands

# Run AI tests (45 tests, ~0.39s)
pytest ai/tests/ -v

# Run full audit suite (39 checks)
python scripts/audit_and_verify_all.py

# Test on-device intent classification
node scripts/test_ondevice_intent.js

Configuration Reference

Variable Required Description Example Used By Sensitive
DATABASE_URL Yes PostgreSQL connection string postgresql://postgres:postgres@localhost:5432/abc_bank Backend Yes
EXPO_PUBLIC_API_URL Yes Backend API URL for mobile app http://152.67.9.53/api/v1 (Cloud) / http://localhost:8000/api/v1 (Local) Frontend No
AI_VERBOSITY No AI logging verbosity level 1 AI Engine No
DEFAULT_LANGUAGE No Default language (en/hi/gu) en Backend No
MINICPM5_MODEL_PATH No Path to MiniCPM-5 ONNX model ./assets/minicpm5_slm_v1.onnx Voice AI No
PRISMA_DB_URL No Prisma tunnel DB string (for Studio) postgresql://...@localhost:5433/abc_bank Prisma Yes

→ Full template: .env.example


Quick Start

Prerequisites

  • Python 3.11+ · Node.js 18+ · Docker & Docker Compose · Expo CLI

Setup

# 1. Clone & configure
git clone <repository-url> && cd dau
cp .env.example .env # Edit with your config

# 2. Start database
docker-compose up -d

# 3. Backend
pip install -r apps/backend/requirements.txt
pip install -r ai/requirements.txt
cd apps/backend && alembic upgrade head && cd ../..
python scripts/seed_database.py # Optional: seed demo data
uvicorn apps.backend.app.main:app --host 0.0.0.0 --port 8000 --reload

# 4. Frontend (new terminal)
cd apps/frontend && npm install && npx expo start

# 5. Validation
pytest ai/tests/ -v            # 45 tests
python scripts/audit_and_verify_all.py   # 39 checks

Endpoints: API Docs → http://localhost:8000/docs · Health → /health · AI Inspector → /inspector · Voice Inspector → /voice-inspector

→ Full setup guide: docs/development/setup.md


Build & Deployment

Current Deployment Architecture

flowchart TD
  subgraph DevEnv["Development Environment"]
    Dev2["Developer"]
    Code["Source Code<br/>(Git Repository)"]
  end

  subgraph LocalInfra["Local Infrastructure"]
    DockerDB["Docker Compose<br/>- postgres:16-alpine<br/>- Port 5432<br/>- Volume: postgres_data"]
    FastAPILocal["FastAPI + Uvicorn<br/>- Port 8000<br/>- --reload mode"]
    ExpoLocal["Expo Dev Server<br/>- Metro Bundler<br/>- QR Code -> Expo Go"]
  end

  subgraph CloudInfra["Live Cloud Deployment (152.67.9.53)"]
    NginxCloud["Nginx Reverse Proxy<br/>- Port 80 (Public)<br/>- SSL Ready / Header Pass"]
    FastAPICloud["FastAPI + Uvicorn (abc-bank.service)<br/>- Port 8000 (Internal)<br/>- PBKDF2 and JWT Auth"]
    PostgresCloud[("PostgreSQL 14<br/>- Port 5432<br/>- Database: abc_bank")]
  end

  Dev2 --> Code
  Code --> DockerDB
  Code --> FastAPILocal
  Code --> ExpoLocal
  FastAPILocal --> DockerDB
  ExpoLocal -->|API Requests via EXPO_PUBLIC_API_URL| NginxCloud
  NginxCloud -->|proxy_pass 127.0.0.1:8000| FastAPICloud
  FastAPICloud --> PostgresCloud
Loading

Database Migration Flow

flowchart LR
  Dev3["Developer"] -->|alembic revision --autogenerate| Migration["New Migration File<br/>(alembic/versions/)"]
  Migration -->|alembic upgrade head| LiveDB[("PostgreSQL<br/>(Live Schema)")]
  LiveDB -->|npm run db:introspect| PrismaFile["prisma/schema.prisma<br/>(Updated)"]
  PrismaFile -->|npm run db:studio| Studio["Prisma Studio<br/>(Visual Browser)"]
Loading

Scripts & Tooling

Script Purpose Usage Output
scripts/audit_and_verify_all.py 39-check validation across all AI pillars (~540 lines) python scripts/audit_and_verify_all.py Pass/fail per check
scripts/generate_seed_data.py Generate 1.2k mock customer profiles + 127k transactions python scripts/generate_seed_data.py JSON files in data/seed/
scripts/seed_database.py Bulk insert seed data into PostgreSQL (batches of 10,000) python scripts/seed_database.py Populated database
scripts/run-demo.ps1 Start backend + frontend for Windows demo .\scripts\run-demo.ps1 Running servers
scripts/run-demo.sh Start backend + frontend for Unix/macOS demo ./scripts/run-demo.sh Running servers
scripts/export_onnx_meta.py Export ONNX model metadata python scripts/export_onnx_meta.py Model metadata
scripts/test_ondevice_intent.js Test on-device intent classification node scripts/test_ondevice_intent.js Intent results

NPM Scripts (root package.json)

Script Purpose
npm run db:studio Open Prisma Studio for visual DB inspection
npm run db:introspect Pull live DB schema into prisma/schema.prisma
npm run db:validate Validate Prisma schema consistency

Implementation Status

Component Status Owner Details
JSON Schema Contracts Complete Shared Frozen schemas for state, experience, and voice
Seed Data & Scenarios Complete Shared 5 comprehensive adaptive scenarios
Multi-Source Data Harmonizer Production-Ready Ubaid 7 dirty feeds (CBS, UPI, SMS, CIBIL, BBPS, NCMC, KYC)
Vectorized Feature Extractor Production-Ready Ubaid 32 single-pass metrics, cash-flow forecast, 50/30/20
Multi-Factor Personalization Production-Ready Ubaid Affordability/Lifecycle/Urgency/Archetype scoring
Dual-Cadence Processing Production-Ready Ubaid 14-day batch + 0.162ms micro-triggers
Cryptographic Audit Ledger Production-Ready Ubaid Immutable SHA-256 decision chain
Ethical AI Guardrail Production-Ready Ubaid DTI > 0.40 loan suppression
Voice Intent & MiniCPM-5 SLM Production-Ready Ubaid Hindi, Gujarati, English edge SLM
AI Test Suite Verified Ubaid 45/45 tests passing (0.39s)
Backend API (FastAPI) Implemented Harsh 15+ routes, CORS, health, scenarios
Experience Composer Implemented Harsh SafetyPolicyFilter + dynamic composition
Frontend App (Expo SDK 57) Complete Lakshya Dynamic attention stack, adaptive cards
Offline State Bundles Complete Lakshya Instant offline resilience for all scenarios

Key Principles

  • Data Privacy & Localization: Encrypted, local processing complying with RBI Data Localization Circular (2018) and DPDP Act 2023
  • Strict Architecture Decoupling: MiniCPM-5 Voice SLM handles conversational speech queries only; personal recommendations are 100% deterministic and mathematical
  • Privacy-First UX: Granular spending data operates strictly as internal telemetry to calibrate protective services, never displayed as an invasive lifestyle ledger
  • Ethical AI Shield: When financial stress or high DTI is detected, loan offers are strictly eliminated and replaced by cash-flow stabilization support
  • No Hallucination Risk: Generative AI never makes financial decisions — only deterministic math-based scoring

Documentation Index

Category Document Description
Architecture Architecture Overview High-level system architecture (7 diagrams)
Architecture Backend Architecture FastAPI services, routes, request lifecycle (7 diagrams)
Architecture Frontend Architecture React Native/Expo, state management, navigation (7 diagrams)
Architecture AI Engine Architecture Intelligence pipeline, voice SLM, ML models (8 diagrams)
Architecture Data Flow End-to-end data flows, contracts, attention layers (6 diagrams)
Architecture Authentication PIN, biometrics, card security, limitations (5 diagrams)
Reference API Endpoints All 15+ endpoints with request/response details (5 diagrams)
Reference Database Schema 9 tables, ER diagram, migrations, seed data (4 diagrams)
Reference Security Overview Auth, ethical AI, compliance, limitations (4 diagrams)
Reference Feature Inventory 18 features with implementation details (6 diagrams)
Operations Development Setup Prerequisites, quick start, env vars, scripts (3 diagrams)
Operations Testing Test suites, audit checks, coverage gaps (2 diagrams)
Operations Deployment Infrastructure, Docker, migrations (3 diagrams)
Legacy Personalization Guide Hyper-personalization math formulas
Legacy Banking Taxonomy 55+ Indian banking services
Legacy AI System Guide AI agent architecture
Legacy Contracts Interface contracts with payloads
Legacy Data Model Conceptual entities
Legacy Demo Flow Hackathon demo script

Traceability Matrix

Concept Implementation Documentation
Authentication apps/backend/app/services/state_service.py Authentication
Experience Composition apps/backend/app/experience/composer.py Backend Architecture
AI Personalization ai/intelligence/personalization/ AI Engine
Data Ingestion ai/intelligence/ingestion/harmonizer.py Data Flow
Safety Policy apps/backend/app/services/safety_policy.py Security
Crypto Ledger ai/intelligence/personalization/cryptoledger.py Security
State Management apps/frontend/src/state/customerStore.ts Frontend Architecture
Voice Pipeline ai/voice/ AI Engine
Database Access apps/backend/app/db/ Database Schema
API Routes apps/backend/app/api/routes.py API Endpoints

Built for HackOut'26 at DA-IICT by Harsh Solanki, Panchal Lakshya, and Ubaid Khan.

About

ABC Bank is an intelligence and experience layer that dynamically adapts a customer's mobile banking interface based on transaction history, cash-flow pulse, life-stage signals, risk indicators, and interaction preferences — designed for Tier 1 to Tier 4, rural, and vernacular-first users across Bharat.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages