Enhanced AegisWallet Architecture Skill v3.0 - Brazilian Fintech Voice-First Assistant
About This Skill
This skill provides enhanced architecture guidance for voice-first Brazilian fintech applications, now specialized in real-world problem resolution with comprehensive documentation integration, MCP tools, and practical implementation examples. Use when designing voice interfaces, implementing PIX/Boletos, optimizing financial systems, or making technology stack decisions for Brazilian market applications.
What's New in v3.0
- 🔧 Practical Problem Resolution: Enhanced with actual code examples and working scripts
- 📚 Documentation Integration: Full sync with
docs/architecture/ reference materials
- 🇧🇷 Brazilian Compliance: Deep LGPD, PIX, and Open Banking implementation patterns
- ⚡ Performance Optimization: Sub-200ms voice response patterns and benchmarks
- 🎯 Enhanced Validation: Comprehensive scripts for architecture compliance
- 🚀 Emergency Recovery: Diagnostic and recovery scripts for production issues
When to Use This Skill
Use this skill when:
- Voice Interface Issues: "Voice commands are slow/unresponsive" → Use performance optimization patterns
- Brazilian Compliance: "Need to implement LGPD/PIX" → Use comprehensive implementation guides
- Architecture Decisions: "How should I structure X?" → Consult integrated documentation
- Performance Problems: "System is slow/lagging" → Use diagnostic scripts and patterns
- Security Implementation: "Need financial-grade security" → Use security patterns
- Real-time Sync Issues: "Data not updating properly" → Use real-time patterns
- Development Workflow: "How to implement X feature?" → Use templates and examples
Enhanced Troubleshooting Capabilities
Voice Performance Issues
Quando: "A autenticação está demorando 2+ segundos para responder comandos de voz"
Resposta: Use `scripts/performance_audit.py --directory .` e verifique:
- VITE_ENABLE_VOICE_REASONING está desabilitado
- Configurações de microfone e silêncio
- Sobrecarga de processamento de voz
- Otimizações de cache para comandos comuns
Architecture Consulting
Quando: "Preciso implementar PIX com Hono RPC"
Resposta: Consulte `docs/architecture/hono-rpc-patterns.md` para padrões detalhados:
- Endpoint structure: `/api/v1/pix/transfer`
- Validation: zValidator + authMiddleware
- Rate limiting para segurança PIX
- Autenticação dupla (senha + biometria)
- Tratamento de erro padronizado
System Recovery
Quando: "Sistema não está respondendo ou deu erro"
Resposta: Use `scripts/emergency-recovery.sh` para diagnóstico completo:
- Verificar API status (curl http://localhost:3000/health)
- Verificar Hono server status
- Verificar Supabase service status
- Executar recovery automatizado
📚 Enhanced Documentation Integration
This skill now provides complete integration with existing AegisWallet documentation:
Primary Documentation Sources
docs/architecture.md: Complete architecture overview and system design
docs/architecture/tech-stack.md: Detailed technology specifications and patterns
docs/architecture/hono-rpc-patterns.md: API design patterns with validation and security
docs/architecture/voice-interface-patterns.md: Voice-first interaction patterns
docs/architecture/frontend-spec.md: Frontend architecture and component patterns
docs/architecture/ai-chat-architecture.md: AI-powered conversational interfaces
docs/LGPD_COMPLIANCE_TESTING_PENDING.md: Brazilian compliance implementation status
docs/VERCEL_DEPLOYMENT_GUIDE.md: Deployment and production patterns
Quick Reference Documentation
# Architecture fundamentals
docs/architecture.md # System overview and design principles
# Technology stack specifics
docs/architecture/tech-stack.md # Bun + Hono + React 19 + Supabase patterns
docs/architecture/hono-rpc-patterns.md # API endpoint design and security
# Voice interface implementation
docs/architecture/voice-interface-patterns.md # Voice-first UI patterns
docs/architecture/ai-chat-architecture.md # AI conversation patterns
# Frontend development
docs/architecture/frontend-spec.md # React 19 + TanStack patterns
docs/architecture/frontend-architecture.md # Component architecture
# Compliance and deployment
docs/LGPD_COMPLIANCE_TESTING_PENDING.md # LGPD implementation checklist
docs/VERCEL_DEPLOYMENT_GUIDE.md # Production deployment guide
Enhanced MCP Integration
- Context7: Access latest framework documentation and best practices
- Tavily: Research Brazilian fintech regulations and market trends
- Serena: Semantic code analysis and architecture validation
- Apex Researcher: Multi-source validation for Brazilian compliance (≥95% accuracy)
🛠️ Enhanced Validation & Diagnostic Tools
Architecture Compliance Validation
# Complete architecture validation
python scripts/validate_architecture.py --directory . --output json
# Performance audit with voice-specific metrics
python scripts/performance_audit.py --directory . --benchmark voice
# Brazilian compliance validation
python scripts/brazilian_compliance_validator.py --check pix,lgpd,openbanking
# Emergency system recovery
./scripts/emergency-recovery.sh --full-scan
Performance Monitoring Scripts
# Voice response time analysis
python scripts/voice_performance_analyzer.py --target-ms 200
# Memory leak detection for voice components
python scripts/memory_leak_detector.py --focus voice-hooks
# Database query optimization
python scripts/database_performance_optimizer.py --analyze-financial-queries
Brazilian Compliance Testing
# LGPD compliance validation
python scripts/lgpd_compliance_test.py --comprehensive
# PIX transaction flow testing
python scripts/pix_transaction_validator.py --test-full-flow
# Open Banking integration testing
python scripts/openbanking_compliance_test.py --validate-spec-3.1
🎯 Enhanced NLU System
- Brazilian Portuguese Specialization: 6 major regional variations with 50+ slang terms
- Hit/Miss Tracking: Real-time analytics with learning feedback loops
- Error Recovery: Multi-strategy recovery with 80%+ success rate
- Context Processing: Multi-turn conversation context with user preferences
- Performance Monitoring: Sub-200ms processing with real-time health monitoring
🚀 Voice Performance Optimizations
- Processing Time: Reduced from 3-5s to ≤2s for voice commands
- Memory Management: Fixed memory leaks from intervals/timeouts
- Voice Activity Detection: Real-time speech detection with <20ms latency
- Timeout Optimization: All major timeouts reduced by 60-80%
- Performance Testing: Comprehensive test suite for validation
📊 Analytics & Learning
- Regional Analytics: Accuracy tracking by Brazilian region
- Pattern Evolution: Learning from user corrections and adaptations
- System Health: Comprehensive monitoring with automated alerting
- Performance Reports: Detailed insights and optimization suggestions
Essential Voice Commands
This skill provides guidance for implementing these 6 essential Brazilian voice commands:
- "Como está meu saldo?" - Balance inquiry with regional variations
- "Quanto posso gastar esse mês?" - Spending capacity check
- "Tem algum boleto programado?" - Bill inquiry (varies by region)
- "Tem algum recebimento programado?" - Income inquiry
- "Como ficará meu saldo no final do mês?" - Balance projection
- "Faz uma transferência para..." - Money transfer command
Performance Standards
Updated Targets (Post-Optimization)
- Voice Processing: ≤200ms (reduced from 500ms)
- Total Response: ≤500ms (reduced from 1000ms)
- Accuracy: 90%+ for Brazilian financial commands
- Error Recovery: 80%+ success rate
- System Uptime: 99.9%
- Regional Accuracy: 85-95% depending on region
Regional Performance Goals
- São Paulo (SP): 95% accuracy - Financial capital variations
- Rio de Janeiro (RJ): 92% accuracy - Carioca expressions
- Nordeste (NE): 88% accuracy - Regional slang and patterns
- Sul: 90% accuracy - Southern expressions and terminology
- Norte: 85% accuracy - Northern regional variations
- Centro-Oeste (CO): 87% accuracy - Central-west patterns
Core Architecture Expertise
Technology Stack Mastery
Runtime & Framework
- Bun: Package management and runtime (3-5x faster than npm)
- Hono: Edge-first API framework for sub-150ms response times
- React 19: Voice interface with concurrent features and hooks
- TypeScript 5.9.3: End-to-end type safety and strict mode
Database & Infrastructure
- Supabase: PostgreSQL + Auth + Realtime + Storage + RLS
- tRPC v11: Type-safe API procedures with automatic client generation
- TanStack Query v5: Real-time financial data synchronization
- TanStack Router v5: File-based routing with full TypeScript support
Frontend & UI
- Tailwind CSS 4.x: Utility-first styling with Brazilian localization
- shadcn/ui: WCAG 2.1 AA+ compliant accessible components
- Motion (Framer Motion): Voice interaction animations
- React Hook Form + Zod: Type-safe form validation
Brazilian Financial System Integration
PIX Implementation
// PIX transaction architecture
interface PIXTransaction {
id: string;
userId: string;
amount: Money;
pixKey: PIXKey;
description: string;
status: 'pending' | 'processing' | 'completed' | 'failed';
transactionId: string;
endToEndId: string;
createdAt: DateTime;
}
// PIX key management
interface PIXKey {
id: string;
userId: string;
keyType: 'email' | 'cpf' | 'cnpj' | 'phone' | 'random';
keyValue: string;
label?: string;
isFavorite: boolean;
isActive: boolean;
}
Boleto Processing
// Boleto payment workflow
interface BoletoPayment {
id: string;
barcode: string;
amount: Money;
dueDate: DateTime;
status: 'pending' | 'paid' | 'expired';
metadata: BoletoMetadata;
}
Enhanced Brazilian Portuguese Patterns with Regional Variations
// Complete regional pattern system for Brazilian Portuguese
interface BrazilianPortuguesePatterns {
// São Paulo (SP) - Financial capital variations
saoPaulo: {
greetings: ["oi", "eai", "beleza", "meu bem"];
financial: ["grana", "coiso", "boleta", "cê tá ligado?", "tipo assim"];
payments: ["faz um pix pra mim", "me manda o pix", "transfere na conta"];
questions: ["quanto tá?", "me fala o valor", "qualé o preço?"];
expressions: ["rolê", "parça", "mano", "vamos nessa"];
};
// Rio de Janeiro (RJ) - Carioca variations
rioDeJaneiro: {
greetings: ["eai", "beleza", "firmesa?", "demais"];
financial: ["grana", "dinhe", "ferinha", "caraca!"];
payments: ["me ajuda com o pix", "faz a transferência", "me passa o pix"];
questions: ["qualé o valor?", "quanto é?", "me fala quanto custa"];
expressions: ["maneiro", "sinistro", "você é brabo", "massa"];
};
// Nordeste (NE) - Regional variations
nordeste: {
greetings: ["oi", "eai", "bão?", "oxente"];
financial: ["bão", "grana", "coisa", "visse?", "meu filho"];
payments: ["me faz um pix", "manda o pix", "transfere pra cá"];
questions: ["quanto tá meu filho?", "qualé o valor visse?", "me diga quanto"];
expressions: ["oxente", "arre", "massa", "bão demais", "meu patrao"];
};
// Sul - Southern variations
sul: {
greetings: ["oi", "eai", "bah", "tchê"];
financial: ["grana", "dinhero", "coisa", "bah!"];
payments: ["me manda o pix tchê", "faz a transferência", "pix pra mim"];
questions: ["quanto é tchê?", "qualé o valor bah?", "me fala o preço"];
expressions: ["bah", "tchê", "guri", "legal", "show"];
};
}
// Voice command patterns for Brazilian financial operations
const BRAZILIAN_VOICE_COMMANDS = {
// Balance inquiries with regional variations
balanceQueries: [
"Como está meu saldo?", // Standard
"Quanto tenho na conta?", // Standard
"Me fala quanto tenho de grana", // SP/RJ
"Qualé o saldo da conta meu bem?", // SP
"Oxente, quanto tô tendo?", // NE
"Bah, me diz o saldo tchê", // Sul
"Me mostra quanto tenho", // General
],
// Spending capacity inquiries
spendingCapacity: [
"Quanto posso gastar esse mês?", // Standard
"Qualé meu limite?", // SP/RJ
"Me fala quanto sobra pra gastar", // General
"Oxente, dá pra gastar quanto?", // NE
"Bah, qualé o limite tchê?", // Sul
],
// Bill inquiries
billQueries: [
"Tem algum boleto programado?", // Standard
"Tem boleta pra pagar?", // SP
"Qualé os boletos?", // RJ
"Oxente, tem conta pra pagar?", // NE
"Tem alguma boleta vencendo?", // Sul
"Me fala das contas do mês", // General
],
// Income inquiries
incomeQueries: [
"Tem algum recebimento programado?", // Standard
"Vai entrar dinheiro esse mês?", // General
"Qualé os recebimentos?", // SP/RJ
"Oxente, vai entrar grana?", // NE
"Bah, vem dinheiro pra conta tchê?", // Sul
],
// Balance projections
balanceProjections: [
"Como ficará meu saldo no final do mês?", // Standard
"Quanto vou ter no fim do mês?", // General
"Me fala como fica o saldo", // SP
"Oxente, quanto vai sobrar?", // NE
"Bah, qualé o saldo final tchê?", // Sul
],
// Transfer commands
transferCommands: [
"Faz uma transferência para [nome]", // Standard
"Manda grana pra [nome]", // SP/RJ
"Pix pra [nome]", // All regions
"Transfere [valor] pra [nome]", // General
"Faz um pix pra [nome] meu bem", // SP
"Oxente, manda dinheiro pra [nome]", // NE
"Bah, me ajuda com pix pra [nome] tchê", // Sul
],
};
// Context-aware processing for Brazilian financial commands
interface BrazilianFinancialContext {
// User preferences and habits
userPreferences: {
region: keyof BrazilianPortuguesePatterns;
formalityLevel: number; // 0 (informal) to 1 (formal)
commonPhrases: string[];
slangUsage: number; // 0-1 frequency
};
// Financial context
financialContext: {
accountTypes: string[];
paymentMethods: string[];
billCategories: string[];
incomeSources: string[];
typicalAmounts: number[];
};
// Conversation context
conversationContext: {
previousCommands: string[];
currentIntent?: string;
entitiesExtracted: Record<string, any>;
confidenceLevel: number;
};
}
// Brazilian entity extraction patterns
interface BrazilianEntityPatterns {
// Money amounts with Brazilian variations
moneyPatterns: [
/\d+ reais?/i,
/\d+,\d{2}/i,
/R\$\s*\d+/i,
/\d+ real/i,
/\d+ pilas?/i, // Slang
/\d+ merreques?/i, // Slang
/\d+ granas?/i, // Slang
];
// PIX key patterns
pixKeyPatterns: {
cpf: /\d{3}\.\d{3}\.\d{3}-\d{2}/,
cnpj: /\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}/,
phone: /\(\d{2}\)\s*\d{4,5}-\d{4}/,
email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/,
random: /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,
};
// Date patterns with Brazilian variations
datePatterns: [
/\d{1,2}\/\d{1,2}\/\d{4}/, // DD/MM/YYYY
/\d{1,2} de [a-z]+ de \d{4}/i, // "15 de janeiro de 2024"
/dia \d{1,2}/i, // "dia 15"
/mês que vem/i, // "mês que vem"
/semana que vem/i, // "semana que vem"
/hoje/i, // "hoje"
/amanhã/i, // "amanhã"
];
// Brazilian bill types
billTypes: [
/boleto/i,
/conta/i,
/fatura/i,
/aluguel/i,
/condomínio/i,
/escola/i,
/plano de saúde/i,
/internet/i,
/luz/i,
/água/i,
/telefone/i,
];
}
Voice-First Architecture
Voice Command Processing
// Essential voice commands system
interface VoiceCommand {
command: string;
intent: 'balance_query' | 'payment_query' | 'transfer_query' | 'schedule_check';
confidence: number;
response: string;
processingTime: number;
}
// Six essential voice commands
const ESSENTIAL_COMMANDS = [
"Como está meu saldo?", // Balance query
"Quanto posso gastar esse mês?", // Spending capacity
"Tem algum boleto programado?", // Scheduled bills
"Tem algum recebimento programado?", // Scheduled income
"Como ficará meu saldo no final do mês?", // Projection
"Faz uma transferência para..." // Money transfer
];
AI Autonomy Levels
interface AutonomyLevel {
level: number; // 50-95% autonomy progression
capabilities: string[];
confirmationRequired: boolean;
trustScore: number;
}
const AUTONOMY_LEVELS = {
LEARNING: { level: 25, requiresConfirmation: true, description: "Observing user patterns" },
ASSISTANT: { level: 50, requiresConfirmation: true, description: "Suggesting actions" },
AUTONOMOUS: { level: 75, requiresConfirmation: false, description: "Executing routine actions" },
TRUSTED: { level: 95, requiresConfirmation: false, description: "Full autonomous management" }
};
Real-Time Architecture
Event-Driven Design
// Domain events for financial operations
interface FinancialEvent {
id: string;
aggregateId: string;
aggregateType: 'Transaction' | 'Account' | 'Budget';
eventType: string;
data: any;
metadata: {
userId: string;
timestamp: string;
source: 'voice' | 'ui' | 'api' | 'webhook';
};
}
// Real-time event handling
class FinancialEventDispatcher {
async dispatch(event: FinancialEvent): Promise<void> {
// Store event in event store
await this.eventStore.save(event);
// Update real-time subscriptions
await this.realtimeService.publish(event);
// Execute synchronous handlers
await this.executeHandlers(event);
// Trigger AI autonomy evaluation
await this.aiEngine.evaluate(event);
}
}
Security & LGPD Compliance
Data Protection Architecture
// LGPD compliance implementation
interface LGPDCompliance {
dataMinimization: boolean; // Collect only necessary data
purposeLimitation: boolean; // Use data for declared purposes only
retentionPolicy: string; // Data retention periods
userRights: {
access: boolean; // Right to access data
deletion: boolean; // Right to be forgotten
portability: boolean; // Right to data portability
consent: boolean; // Explicit consent management
};
}
// Security layers
interface SecurityArchitecture {
encryption: {
atRest: 'AES-256'; // Supabase managed
inTransit: 'TLS 1.3'; // Enforced
};
authentication: {
primary: 'biometric'; // Face ID, Touch ID
secondary: 'password'; // Traditional backup
session: 'JWT'; // Secure tokens
};
authorization: {
rowLevelSecurity: true; // Tenant isolation
auditTrails: true; // Complete operation logging
};
}
Performance Optimization
Voice Response Optimization
// Performance targets for voice interactions
const VOICE_PERFORMANCE_TARGETS = {
speechToText: 200, // milliseconds
intentProcessing: 150, // milliseconds
actionExecution: 100, // milliseconds
textToSpeech: 50, // milliseconds
totalResponse: 500 // milliseconds maximum
};
// Caching strategy for financial data
interface CacheStrategy {
userProfiles: { ttl: 300000, max: 100 }; // 5 minutes
accountBalances: { ttl: 30000, max: 50 }; // 30 seconds
transactionHistory: { ttl: 60000, max: 200 }; // 1 minute
exchangeRates: { ttl: 86400000, max: 10 }; // 24 hours
};
Database Architecture
Schema Design Patterns
-- Core user entity with LGPD compliance
CREATE TABLE users (
id UUID PRIMARY KEY REFERENCES auth.users(id),
email TEXT UNIQUE NOT NULL,
autonomy_level INTEGER DEFAULT 50 CHECK (autonomy_level >= 50 AND autonomy_level <= 95),
voice_command_enabled BOOLEAN DEFAULT true,
data_processing_consent TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Financial transactions with audit trail
CREATE TABLE transactions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
amount DECIMAL(15,2) NOT NULL,
description TEXT NOT NULL,
category TEXT,
transaction_date TIMESTAMP WITH TIME ZONE NOT NULL,
status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'completed', 'failed')),
metadata JSONB DEFAULT '{}',
voice_command_id UUID REFERENCES voice_commands(id),
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Voice commands for AI learning
CREATE TABLE voice_commands (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
command TEXT NOT NULL,
intent TEXT NOT NULL,
confidence DECIMAL(3,2),
response TEXT,
processing_time_ms INTEGER,
was_successful BOOLEAN,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
Development Workflow Patterns
Essential Commands
# Development workflow
bun dev # Start full-stack development
bun dev:client # Frontend only (Vite + React)
bun dev:server # Backend only (Hono + tRPC)
# Quality assurance
bun lint # OXLint + Biome validation
bun type-check # TypeScript strict mode
bun test:coverage # Unit tests with coverage
bun quality # Full CI pipeline
# Database operations
bunx supabase db push # Apply migrations
bunx supabase gen types # Generate TypeScript types
bunx supabase db diff # Schema validation
Import Patterns
// Supabase client integration
import { supabase } from "@/integrations/supabase/client";
// tRPC procedures
import { router, protectedProcedure } from "@/server/trpc";
// React Query for server state
import { useQuery, useMutation } from "@tanstack/react-query";
// TanStack Router
import { createFileRoute } from "@tanstack/react-router";
// Voice processing
import { useVoiceRecognition } from "@/hooks/useVoiceRecognition";
Implementation Patterns
Component Architecture
// Voice-first component template
interface VoiceComponentProps {
readonly onVoiceCommand?: (command: VoiceCommand) => void;
readonly accessibilityLabel?: string;
readonly children?: React.ReactNode;
}
export const VoiceFinancialComponent: React.FC<VoiceComponentProps> = ({
onVoiceCommand,
accessibilityLabel,
children
}) => {
const { isListening, transcript } = useVoiceRecognition();
const { announceToScreenReader } = useAccessibility();
return (
<div
role="application"
aria-label={accessibilityLabel}
className={cn(
"voice-component",
isListening && "voice-listening"
)}
>
{children}
{isListening && (
<VoiceIndicator transcript={transcript} />
)}
</div>
);
};
Enhanced NLU System Architecture
// Complete NLU system with Brazilian Portuguese specialization
interface EnhancedNLUSystem {
// Core processing engine with sub-200ms target
processCommand: (audio: AudioBuffer) => Promise<NLUResult>;
// Brazilian Portuguese patterns with regional variations
brazilianPatterns: {
regions: RegionalPattern[];
slangTerms: SlangTerm[];
financialTerminology: FinancialTerm[];
};
// Learning analytics with hit/miss tracking
analytics: {
trackHitMiss: (command: string, success: boolean) => void;
getAccuracyMetrics: () => AccuracyMetrics;
generateLearningReport: () => LearningReport;
};
// Error recovery with multiple strategies
errorRecovery: {
classifyError: (error: NLUError) => ErrorType;
applyRecoveryStrategy: (error: NLUError) => Promise<NLUResult>;
learnFromCorrection: (original: string, corrected: string) => void;
};
// Performance monitoring and optimization
performance: {
trackProcessingTime: (duration: number) => void;
getSystemHealth: () => HealthMetrics;
generatePerformanceReport: () => PerformanceReport;
};
}
// Voice Activity Detection for real-time speech processing
interface VoiceActivityDetection {
// Real-time speech detection with <20ms latency
detectSpeech: (audioChunk: AudioBuffer) => boolean;
// Automatic speech end detection
detectSpeechEnd: (silenceDuration: number) => boolean;
// Energy-based voice activity detection
calculateEnergyLevel: (audio: AudioBuffer) => number;
}
// Performance optimization patterns
const VOICE_PERFORMANCE_TARGETS = {
speechToText: 200, // milliseconds (reduced from 500ms)
intentProcessing: 150, // milliseconds
actionExecution: 100, // milliseconds
textToSpeech: 50, // milliseconds
totalResponse: 500, // milliseconds maximum (reduced from 2000ms)
// Voice recognition settings
autoStopTimeout: 3000, // 3 seconds (reduced from 10s)
processingDelay: 100, // 100ms (reduced from 500ms)
minAudioDuration: 300, // 0.3 seconds minimum
maxAudioDuration: 10000, // 10 seconds maximum
silenceDuration: 1500, // 1.5 seconds (reduced from 2s)
};
// Brazilian Portuguese regional patterns
interface BrazilianRegionalPatterns {
// São Paulo variations
saoPaulo: {
slang: ["meu bem", "grana", "boleta", "rolê", "parça"];
patterns: ["quanto tá", "me fala", "tipo assim"];
};
// Rio de Janeiro variations
rioDeJaneiro: {
slang: ["maneiro", "caraca", "você é brabo", "demais"];
patterns: ["me ajuda", "qualé", "sinistro"];
};
// Nordeste variations
nordeste: {
slang: ["oxente", "bão", "arre", "massa", "visse"];
patterns: ["me diga", "como cê tá", "vamos nessa"];
};
// Sul variations
sul: {
slang: ["bah", "tchê", "guri", "legal", "show"];
patterns: ["me mostra", "quanto é", "vamos fazer"];
};
}
// Enhanced voice command hook with optimizations
interface OptimizedVoiceRecognition {
// Performance monitoring
processingTime: number;
successRate: number;
errorRate: number;
// Voice Activity Detection
voiceActivityDetection: VoiceActivityDetection;
// Brazilian Portuguese processing
regionalProcessor: BrazilianRegionalProcessor;
// Learning and analytics
analytics: NLUAnalytics;
// Error recovery
errorRecovery: ErrorRecoverySystem;
// Performance optimization methods
optimizeProcessing: () => void;
clearCache: () => void;
getPerformanceMetrics: () => PerformanceMetrics;
}
// Memory leak prevention patterns
const MEMORY_MANAGEMENT = {
// Cleanup intervals and timeouts
clearAllTimers: () => {
clearInterval(refreshInterval.current);
clearTimeout(timeoutRef.current);
clearTimeout(clearResponseRef.current);
},
// Abort controller for async operations
abortController: new AbortController(),
// Proper cleanup on unmount
cleanup: () => {
voiceActivityDetection?.cleanup();
abortController.abort();
clearAllTimers();
},
};
API Design Patterns
// tRPC procedure with comprehensive validation
export const createTransactionRouter = router({
create: protectedProcedure
.input(z.object({
amount: z.number().positive().max(1000000),
description: z.string().min(1).max(500),
category: z.enum(['food', 'transport', 'housing', 'entertainment', 'other']),
date: z.string().datetime().optional(),
voiceCommand: z.string().optional(),
}))
.mutation(async ({ ctx, input }) => {
// Business logic validation
if (input.amount > ctx.user.dailyLimit) {
throw new TRPCError({
code: 'FORBIDDEN',
message: 'Amount exceeds daily spending limit'
});
}
// Create transaction with audit trail
const transaction = await createTransaction({
userId: ctx.user.id,
...input,
source: 'voice_command',
metadata: {
ip: ctx.ip,
userAgent: ctx.userAgent,
}
});
// Real-time update
await ctx.realtime.publish(`user:${ctx.user.id}:transactions`, {
type: 'transaction_created',
data: transaction
});
return transaction;
}),
});
// Enhanced voice command processing API
export const voiceCommandRouter = router({
process: protectedProcedure
.input(z.object({
audioData: z.string(), // base64 encoded audio
region: z.enum(['SP', 'RJ', 'NE', 'SUL', 'NORTE', 'CO']).optional(),
context: z.object({
previousCommands: z.array(z.string()).optional(),
userPreferences: z.object({
language: z.string().optional(),
slangLevel: z.number().optional(), // 0-1 formality level
}).optional(),
}).optional(),
}))
.mutation(async ({ ctx, input }) => {
// Process with enhanced NLU system
const startTime = Date.now();
try {
const result = await enhancedNLUEngine.processCommand({
audioData: input.audioData,
userId: ctx.user.id,
region: input.region || 'SP',
context: input.context,
});
const processingTime = Date.now() - startTime;
// Track performance metrics
await voiceAnalytics.trackProcessing({
userId: ctx.user.id,
processingTime,
success: result.success,
confidence: result.confidence,
intent: result.intent,
});
return {
...result,
processingTime,
performanceTarget: processingTime <= VOICE_PERFORMANCE_TARGETS.totalResponse,
};
} catch (error) {
// Error recovery attempt
const recoveryResult = await errorRecovery.attemptRecovery({
error,
userId: ctx.user.id,
originalInput: input,
});
return recoveryResult;
}
}),
// Brazilian Portuguese pattern learning
learnPattern: protectedProcedure
.input(z.object({
originalCommand: z.string(),
correctedCommand: z.string(),
region: z.string(),
context: z.string().optional(),
}))
.mutation(async ({ ctx, input }) => {
await brazilianPatterns.learnFromCorrection({
userId: ctx.user.id,
original: input.originalCommand,
corrected: input.correctedCommand,
region: input.region,
context: input.context,
});
return { success: true };
}),
// Performance analytics endpoint
getAnalytics: protectedProcedure
.input(z.object({
timeframe: z.enum(['hour', 'day', 'week', 'month']),
metrics: z.array(z.enum([
'accuracy', 'latency', 'success_rate', 'error_rate', 'regional_performance'
])),
}))
.query(async ({ ctx, input }) => {
return voiceAnalytics.getDetailedMetrics({
userId: ctx.user.id,
timeframe: input.timeframe,
metrics: input.metrics,
});
}),
});
// Voice command optimization patterns
const VOICE_OPTIMIZATION_PATTERNS = {
// Caching strategies for frequently used commands
caching: {
commonCommands: new Map([
['saldo', { cachedResponse: true, ttl: 30000 }], // 30s cache
['transferência', { cachedResponse: false, ttl: 0 }],
['boletos', { cachedResponse: true, ttl: 60000 }], // 1m cache
]),
// Regional pattern caching
regionalPatterns: new Map([
['SP', { patterns: saoPauloPatterns, lastUpdated: Date.now() }],
['RJ', { patterns: rioPatterns, lastUpdated: Date.now() }],
['NE', { patterns: nordestePatterns, lastUpdated: Date.now() }],
]),
},
// Performance monitoring
monitoring: {
// Real-time metrics collection
collectMetrics: (command: string, processingTime: number, success: boolean) => {
performanceTracker.record({
command,
processingTime,
success,
timestamp: Date.now(),
userId: getCurrentUserId(),
});
},
// Health check system
healthCheck: async () => {
const health = await systemHealth.check({
voiceRecognition: { targetLatency: 200, currentLatency: getCurrentLatency() },
nluProcessing: { targetLatency: 150, currentLatency: getNLULatency() },
databaseOperations: { targetLatency: 100, currentLatency: getDBLatency() },
});
return health;
},
},
// Error recovery strategies
errorRecovery: {
strategies: [
'pattern_matching', // Try to match known patterns
'context_inference', // Use conversation context
'regional_adaptation', // Adapt for regional variations
'user_history', // Learn from user's past corrections
'clarification_request', // Ask user for help
],
applyStrategy: async (error: NLUError) => {
for (const strategy of errorRecovery.strategies) {
try {
const result = await applyRecoveryStrategy(strategy, error);
if (result.success) return result;
} catch (e) {
// Try next strategy
}
}
// Final fallback - ask for clarification
return requestClarification(error);
},
},
};
Validation & Quality Gates
Architecture Compliance Checklist
Enhanced Code Quality Standards
- Test Coverage: 90%+ for critical business logic including NLU systems
- TypeScript: Strict mode enabled, zero implicit any
- Error Handling: Comprehensive error boundaries and user feedback
- Security: Input validation, SQL injection prevention, XSS protection
- Performance: Lighthouse score ≥90, Core Web Vitals compliance
- Voice Performance: Sub-200ms processing for 95% of voice commands
- Memory Management: Zero memory leaks from intervals/timeouts
- Regional Accuracy: 90%+ accuracy for Brazilian Portuguese variations
- System Health: 99.9% uptime with automated monitoring
Enhanced Performance Standards
// Updated performance targets based on latest optimizations
const ENHANCED_PERFORMANCE_TARGETS = {
// Voice processing (reduced from previous targets)
speechToText: 200, // milliseconds (reduced from 500ms)
intentProcessing: 150, // milliseconds (reduced from 300ms)
actionExecution: 100, // milliseconds (reduced from 200ms)
textToSpeech: 50, // milliseconds (reduced from 100ms)
totalResponse: 500, // milliseconds maximum (reduced from 1000ms)
// Voice recognition optimizations
autoStopTimeout: 3000, // 3 seconds (reduced from 10s)
processingDelay: 100, // 100ms (reduced from 500ms)
minAudioDuration: 300, // 0.3 seconds minimum
maxAudioDuration: 10000, // 10 seconds maximum (reduced from 30s)
silenceDuration: 1500, // 1.5 seconds (reduced from 2s)
// NLU system performance
nluProcessing: 150, // milliseconds target
accuracyThreshold: 0.90, // 90% accuracy target
errorRecoveryRate: 0.80, // 80% error recovery rate
cacheHitRate: 0.60, // 60% cache hit rate
// Regional performance targets
regionalAccuracy: {
SP: 0.95, // São Paulo: 95%
RJ: 0.92, // Rio de Janeiro: 92%
NE: 0.88, // Nordeste: 88%
SUL: 0.90, // Sul: 90%
NORTE: 0.85, // Norte: 85%
CO: 0.87, // Centro-Oeste: 87%
},
// System health targets
systemUptime: 0.999, // 99.9% uptime
memoryUsage: 0.75, // 75% maximum memory usage
cpuUsage: 0.70, // 70% maximum CPU usage
databaseLatency: 100, // 100ms maximum database latency
};
Enhanced Quality Gates Checklist
Enhanced Testing Requirements
// Comprehensive testing patterns for voice systems
const ENHANCED_TESTING_REQUIREMENTS = {
// Unit tests
unitTests: {
nluEngine: 95, // 95% coverage for NLU engine
brazilianPatterns: 100, // 100% coverage for regional patterns
errorRecovery: 90, // 90% coverage for error recovery
performanceTracking: 85, // 85% coverage for performance systems
},
// Integration tests
integrationTests: {
voiceProcessing: 90, // 90% coverage for end-to-end voice processing
regionalVariations: 85, // 85% coverage for regional pattern testing
realTimeUpdates: 80, // 80% coverage for real-time systems
errorRecovery: 85, // 85% coverage for error recovery scenarios
},
// Performance tests
performanceTests: {
voiceLatency: 'sub_500ms', // All voice operations under 500ms
memoryUsage: 'no_leaks', // Zero memory leaks
concurrency: '100_users', // Support for 100 concurrent users
regionalAccuracy: '90_percent_plus', // 90%+ accuracy across regions
},
// Accessibility tests
accessibilityTests: {
screenReader: 'wcag_aa_plus', // WCAG 2.1 AA+ compliance
voiceNavigation: 'full_support', // Full voice navigation support
keyboardNavigation: 'complete', // Complete keyboard navigation
colorContrast: '4_5_ratio', // 4.5:1 minimum contrast ratio
},
// Security tests
securityTests: {
sqlInjection: 'prevention', // SQL injection prevention
xssPrevention: 'full', // XSS prevention
dataEncryption: 'aes256', // AES-256 encryption
lgpdCompliance: 'full', // Full LGPD com
…(truncated)
1---
2name: aegis-architect
3description: Enhanced architecture guidance for voice-first Brazilian fintech applications. Use when designing voice interfaces, implementing PIX/Boletos, optimizing financial systems, or making technology stack decisions for Brazilian market applications. Integrates with docs/ content, MCP tools for Brazilian market research, enhanced validation scripts, and comprehensive Brazilian compliance patterns.
4license: MIT
5metadata:
6 source: https://skillmd.com/skills/aibot88/aegis-architect
7 version: "3.0.0"
8 author: "AegisWallet Development Team"
9 category: "architecture"
10 last-updated: "2025-11-27"
11 domain: "brazilian-fintech"
12 expertise: ["voice-first", "brazilian-financial", "lgpd-compliance", "performance-optimization", "hono-rpc"]
13 links:
14 references: [
15 {
16 "title": "AegisWallet Architecture Documentation",
17 "url": "docs/architecture.md"
18 },
19 {
20 "title": "Technology Stack Specification",
21 "url": "docs/architecture/tech-stack.md"
22 },
23 {
24 "Performance Patterns",
25 "url": "docs/architecture/hono-rpc-patterns.md"
26 },
27 {
28 "Voice Interface Patterns",
29 "url": "docs/architecture/voice-interface-patterns.md"
30 },
31 {
32 "AI Chat Architecture",
33 "url": "docs/architecture/ai-chat-architecture.md"
34 }
35 ]
36---
37
38# Enhanced AegisWallet Architecture Skill v3.0 - Brazilian Fintech Voice-First Assistant
39
40## About This Skill
41
42This skill provides **enhanced architecture guidance** for voice-first Brazilian fintech applications, now **specialized in real-world problem resolution** with comprehensive documentation integration, MCP tools, and **practical implementation examples**. Use when designing voice interfaces, implementing PIX/Boletos, optimizing financial systems, or making technology stack decisions for Brazilian market applications.
43
44### What's New in v3.0
45
46- **🔧 Practical Problem Resolution**: Enhanced with actual code examples and working scripts
47- **📚 Documentation Integration**: Full sync with `docs/architecture/` reference materials
48- **🇧🇷 Brazilian Compliance**: Deep LGPD, PIX, and Open Banking implementation patterns
49- **⚡ Performance Optimization**: Sub-200ms voice response patterns and benchmarks
50- **🎯 Enhanced Validation**: Comprehensive scripts for architecture compliance
51- **🚀 Emergency Recovery**: Diagnostic and recovery scripts for production issues
52
53## When to Use This Skill
54
55**Use this skill when:**
56- **Voice Interface Issues**: "Voice commands are slow/unresponsive" → Use performance optimization patterns
57- **Brazilian Compliance**: "Need to implement LGPD/PIX" → Use comprehensive implementation guides
58- **Architecture Decisions**: "How should I structure X?" → Consult integrated documentation
59- **Performance Problems**: "System is slow/lagging" → Use diagnostic scripts and patterns
60- **Security Implementation**: "Need financial-grade security" → Use security patterns
61- **Real-time Sync Issues**: "Data not updating properly" → Use real-time patterns
62- **Development Workflow**: "How to implement X feature?" → Use templates and examples
63
64### Enhanced Troubleshooting Capabilities
65
66#### Voice Performance Issues
67```
68Quando: "A autenticação está demorando 2+ segundos para responder comandos de voz"
69
70Resposta: Use `scripts/performance_audit.py --directory .` e verifique:
71- VITE_ENABLE_VOICE_REASONING está desabilitado
72- Configurações de microfone e silêncio
73- Sobrecarga de processamento de voz
74- Otimizações de cache para comandos comuns
75```
76
77#### Architecture Consulting
78```
79Quando: "Preciso implementar PIX com Hono RPC"
80
81Resposta: Consulte `docs/architecture/hono-rpc-patterns.md` para padrões detalhados:
82- Endpoint structure: `/api/v1/pix/transfer`
83- Validation: zValidator + authMiddleware
84- Rate limiting para segurança PIX
85- Autenticação dupla (senha + biometria)
86- Tratamento de erro padronizado
87```
88
89#### System Recovery
90```
91Quando: "Sistema não está respondendo ou deu erro"
92
93Resposta: Use `scripts/emergency-recovery.sh` para diagnóstico completo:
94- Verificar API status (curl http://localhost:3000/health)
95- Verificar Hono server status
96- Verificar Supabase service status
97- Executar recovery automatizado
98```
99
100## 📚 Enhanced Documentation Integration
101
102This skill now provides **complete integration** with existing AegisWallet documentation:
103
104### Primary Documentation Sources
105- **`docs/architecture.md`**: Complete architecture overview and system design
106- **`docs/architecture/tech-stack.md`**: Detailed technology specifications and patterns
107- **`docs/architecture/hono-rpc-patterns.md`**: API design patterns with validation and security
108- **`docs/architecture/voice-interface-patterns.md`**: Voice-first interaction patterns
109- **`docs/architecture/frontend-spec.md`**: Frontend architecture and component patterns
110- **`docs/architecture/ai-chat-architecture.md`**: AI-powered conversational interfaces
111- **`docs/LGPD_COMPLIANCE_TESTING_PENDING.md`**: Brazilian compliance implementation status
112- **`docs/VERCEL_DEPLOYMENT_GUIDE.md`**: Deployment and production patterns
113
114### Quick Reference Documentation
115```bash
116# Architecture fundamentals
117docs/architecture.md # System overview and design principles
118
119# Technology stack specifics
120docs/architecture/tech-stack.md # Bun + Hono + React 19 + Supabase patterns
121docs/architecture/hono-rpc-patterns.md # API endpoint design and security
122
123# Voice interface implementation
124docs/architecture/voice-interface-patterns.md # Voice-first UI patterns
125docs/architecture/ai-chat-architecture.md # AI conversation patterns
126
127# Frontend development
128docs/architecture/frontend-spec.md # React 19 + TanStack patterns
129docs/architecture/frontend-architecture.md # Component architecture
130
131# Compliance and deployment
132docs/LGPD_COMPLIANCE_TESTING_PENDING.md # LGPD implementation checklist
133docs/VERCEL_DEPLOYMENT_GUIDE.md # Production deployment guide
134```
135
136### Enhanced MCP Integration
137- **Context7**: Access latest framework documentation and best practices
138- **Tavily**: Research Brazilian fintech regulations and market trends
139- **Serena**: Semantic code analysis and architecture validation
140- **Apex Researcher**: Multi-source validation for Brazilian compliance (≥95% accuracy)
141
142## 🛠️ Enhanced Validation & Diagnostic Tools
143
144### Architecture Compliance Validation
145```bash
146# Complete architecture validation
147python scripts/validate_architecture.py --directory . --output json
148
149# Performance audit with voice-specific metrics
150python scripts/performance_audit.py --directory . --benchmark voice
151
152# Brazilian compliance validation
153python scripts/brazilian_compliance_validator.py --check pix,lgpd,openbanking
154
155# Emergency system recovery
156./scripts/emergency-recovery.sh --full-scan
157```
158
159### Performance Monitoring Scripts
160```bash
161# Voice response time analysis
162python scripts/voice_performance_analyzer.py --target-ms 200
163
164# Memory leak detection for voice components
165python scripts/memory_leak_detector.py --focus voice-hooks
166
167# Database query optimization
168python scripts/database_performance_optimizer.py --analyze-financial-queries
169```
170
171### Brazilian Compliance Testing
172```bash
173# LGPD compliance validation
174python scripts/lgpd_compliance_test.py --comprehensive
175
176# PIX transaction flow testing
177python scripts/pix_transaction_validator.py --test-full-flow
178
179# Open Banking integration testing
180python scripts/openbanking_compliance_test.py --validate-spec-3.1
181```
182
183### 🎯 Enhanced NLU System
184- **Brazilian Portuguese Specialization**: 6 major regional variations with 50+ slang terms
185- **Hit/Miss Tracking**: Real-time analytics with learning feedback loops
186- **Error Recovery**: Multi-strategy recovery with 80%+ success rate
187- **Context Processing**: Multi-turn conversation context with user preferences
188- **Performance Monitoring**: Sub-200ms processing with real-time health monitoring
189
190### 🚀 Voice Performance Optimizations
191- **Processing Time**: Reduced from 3-5s to ≤2s for voice commands
192- **Memory Management**: Fixed memory leaks from intervals/timeouts
193- **Voice Activity Detection**: Real-time speech detection with <20ms latency
194- **Timeout Optimization**: All major timeouts reduced by 60-80%
195- **Performance Testing**: Comprehensive test suite for validation
196
197### 📊 Analytics & Learning
198- **Regional Analytics**: Accuracy tracking by Brazilian region
199- **Pattern Evolution**: Learning from user corrections and adaptations
200- **System Health**: Comprehensive monitoring with automated alerting
201- **Performance Reports**: Detailed insights and optimization suggestions
202
203## Essential Voice Commands
204
205This skill provides guidance for implementing these 6 essential Brazilian voice commands:
206
2071. **"Como está meu saldo?"** - Balance inquiry with regional variations
2082. **"Quanto posso gastar esse mês?"** - Spending capacity check
2093. **"Tem algum boleto programado?"** - Bill inquiry (varies by region)
2104. **"Tem algum recebimento programado?"** - Income inquiry
2115. **"Como ficará meu saldo no final do mês?"** - Balance projection
2126. **"Faz uma transferência para..."** - Money transfer command
213
214## Performance Standards
215
216### Updated Targets (Post-Optimization)
217- **Voice Processing**: ≤200ms (reduced from 500ms)
218- **Total Response**: ≤500ms (reduced from 1000ms)
219- **Accuracy**: 90%+ for Brazilian financial commands
220- **Error Recovery**: 80%+ success rate
221- **System Uptime**: 99.9%
222- **Regional Accuracy**: 85-95% depending on region
223
224### Regional Performance Goals
225- **São Paulo (SP)**: 95% accuracy - Financial capital variations
226- **Rio de Janeiro (RJ)**: 92% accuracy - Carioca expressions
227- **Nordeste (NE)**: 88% accuracy - Regional slang and patterns
228- **Sul**: 90% accuracy - Southern expressions and terminology
229- **Norte**: 85% accuracy - Northern regional variations
230- **Centro-Oeste (CO)**: 87% accuracy - Central-west patterns
231
232## Core Architecture Expertise
233
234### Technology Stack Mastery
235
236#### Runtime & Framework
237- **Bun**: Package management and runtime (3-5x faster than npm)
238- **Hono**: Edge-first API framework for sub-150ms response times
239- **React 19**: Voice interface with concurrent features and hooks
240- **TypeScript 5.9.3**: End-to-end type safety and strict mode
241
242#### Database & Infrastructure
243- **Supabase**: PostgreSQL + Auth + Realtime + Storage + RLS
244- **tRPC v11**: Type-safe API procedures with automatic client generation
245- **TanStack Query v5**: Real-time financial data synchronization
246- **TanStack Router v5**: File-based routing with full TypeScript support
247
248#### Frontend & UI
249- **Tailwind CSS 4.x**: Utility-first styling with Brazilian localization
250- **shadcn/ui**: WCAG 2.1 AA+ compliant accessible components
251- **Motion (Framer Motion)**: Voice interaction animations
252- **React Hook Form + Zod**: Type-safe form validation
253
254### Brazilian Financial System Integration
255
256#### PIX Implementation
257```typescript
258// PIX transaction architecture
259interface PIXTransaction {
260 id: string;
261 userId: string;
262 amount: Money;
263 pixKey: PIXKey;
264 description: string;
265 status: 'pending' | 'processing' | 'completed' | 'failed';
266 transactionId: string;
267 endToEndId: string;
268 createdAt: DateTime;
269}
270
271// PIX key management
272interface PIXKey {
273 id: string;
274 userId: string;
275 keyType: 'email' | 'cpf' | 'cnpj' | 'phone' | 'random';
276 keyValue: string;
277 label?: string;
278 isFavorite: boolean;
279 isActive: boolean;
280}
281```
282
283#### Boleto Processing
284```typescript
285// Boleto payment workflow
286interface BoletoPayment {
287 id: string;
288 barcode: string;
289 amount: Money;
290 dueDate: DateTime;
291 status: 'pending' | 'paid' | 'expired';
292 metadata: BoletoMetadata;
293}
294```
295
296#### Enhanced Brazilian Portuguese Patterns with Regional Variations
297```typescript
298// Complete regional pattern system for Brazilian Portuguese
299interface BrazilianPortuguesePatterns {
300 // São Paulo (SP) - Financial capital variations
301 saoPaulo: {
302 greetings: ["oi", "eai", "beleza", "meu bem"];
303 financial: ["grana", "coiso", "boleta", "cê tá ligado?", "tipo assim"];
304 payments: ["faz um pix pra mim", "me manda o pix", "transfere na conta"];
305 questions: ["quanto tá?", "me fala o valor", "qualé o preço?"];
306 expressions: ["rolê", "parça", "mano", "vamos nessa"];
307 };
308
309 // Rio de Janeiro (RJ) - Carioca variations
310 rioDeJaneiro: {
311 greetings: ["eai", "beleza", "firmesa?", "demais"];
312 financial: ["grana", "dinhe", "ferinha", "caraca!"];
313 payments: ["me ajuda com o pix", "faz a transferência", "me passa o pix"];
314 questions: ["qualé o valor?", "quanto é?", "me fala quanto custa"];
315 expressions: ["maneiro", "sinistro", "você é brabo", "massa"];
316 };
317
318 // Nordeste (NE) - Regional variations
319 nordeste: {
320 greetings: ["oi", "eai", "bão?", "oxente"];
321 financial: ["bão", "grana", "coisa", "visse?", "meu filho"];
322 payments: ["me faz um pix", "manda o pix", "transfere pra cá"];
323 questions: ["quanto tá meu filho?", "qualé o valor visse?", "me diga quanto"];
324 expressions: ["oxente", "arre", "massa", "bão demais", "meu patrao"];
325 };
326
327 // Sul - Southern variations
328 sul: {
329 greetings: ["oi", "eai", "bah", "tchê"];
330 financial: ["grana", "dinhero", "coisa", "bah!"];
331 payments: ["me manda o pix tchê", "faz a transferência", "pix pra mim"];
332 questions: ["quanto é tchê?", "qualé o valor bah?", "me fala o preço"];
333 expressions: ["bah", "tchê", "guri", "legal", "show"];
334 };
335}
336
337// Voice command patterns for Brazilian financial operations
338const BRAZILIAN_VOICE_COMMANDS = {
339 // Balance inquiries with regional variations
340 balanceQueries: [
341 "Como está meu saldo?", // Standard
342 "Quanto tenho na conta?", // Standard
343 "Me fala quanto tenho de grana", // SP/RJ
344 "Qualé o saldo da conta meu bem?", // SP
345 "Oxente, quanto tô tendo?", // NE
346 "Bah, me diz o saldo tchê", // Sul
347 "Me mostra quanto tenho", // General
348 ],
349
350 // Spending capacity inquiries
351 spendingCapacity: [
352 "Quanto posso gastar esse mês?", // Standard
353 "Qualé meu limite?", // SP/RJ
354 "Me fala quanto sobra pra gastar", // General
355 "Oxente, dá pra gastar quanto?", // NE
356 "Bah, qualé o limite tchê?", // Sul
357 ],
358
359 // Bill inquiries
360 billQueries: [
361 "Tem algum boleto programado?", // Standard
362 "Tem boleta pra pagar?", // SP
363 "Qualé os boletos?", // RJ
364 "Oxente, tem conta pra pagar?", // NE
365 "Tem alguma boleta vencendo?", // Sul
366 "Me fala das contas do mês", // General
367 ],
368
369 // Income inquiries
370 incomeQueries: [
371 "Tem algum recebimento programado?", // Standard
372 "Vai entrar dinheiro esse mês?", // General
373 "Qualé os recebimentos?", // SP/RJ
374 "Oxente, vai entrar grana?", // NE
375 "Bah, vem dinheiro pra conta tchê?", // Sul
376 ],
377
378 // Balance projections
379 balanceProjections: [
380 "Como ficará meu saldo no final do mês?", // Standard
381 "Quanto vou ter no fim do mês?", // General
382 "Me fala como fica o saldo", // SP
383 "Oxente, quanto vai sobrar?", // NE
384 "Bah, qualé o saldo final tchê?", // Sul
385 ],
386
387 // Transfer commands
388 transferCommands: [
389 "Faz uma transferência para [nome]", // Standard
390 "Manda grana pra [nome]", // SP/RJ
391 "Pix pra [nome]", // All regions
392 "Transfere [valor] pra [nome]", // General
393 "Faz um pix pra [nome] meu bem", // SP
394 "Oxente, manda dinheiro pra [nome]", // NE
395 "Bah, me ajuda com pix pra [nome] tchê", // Sul
396 ],
397};
398
399// Context-aware processing for Brazilian financial commands
400interface BrazilianFinancialContext {
401 // User preferences and habits
402 userPreferences: {
403 region: keyof BrazilianPortuguesePatterns;
404 formalityLevel: number; // 0 (informal) to 1 (formal)
405 commonPhrases: string[];
406 slangUsage: number; // 0-1 frequency
407 };
408
409 // Financial context
410 financialContext: {
411 accountTypes: string[];
412 paymentMethods: string[];
413 billCategories: string[];
414 incomeSources: string[];
415 typicalAmounts: number[];
416 };
417
418 // Conversation context
419 conversationContext: {
420 previousCommands: string[];
421 currentIntent?: string;
422 entitiesExtracted: Record<string, any>;
423 confidenceLevel: number;
424 };
425}
426
427// Brazilian entity extraction patterns
428interface BrazilianEntityPatterns {
429 // Money amounts with Brazilian variations
430 moneyPatterns: [
431 /\d+ reais?/i,
432 /\d+,\d{2}/i,
433 /R\$\s*\d+/i,
434 /\d+ real/i,
435 /\d+ pilas?/i, // Slang
436 /\d+ merreques?/i, // Slang
437 /\d+ granas?/i, // Slang
438 ];
439
440 // PIX key patterns
441 pixKeyPatterns: {
442 cpf: /\d{3}\.\d{3}\.\d{3}-\d{2}/,
443 cnpj: /\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}/,
444 phone: /\(\d{2}\)\s*\d{4,5}-\d{4}/,
445 email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/,
446 random: /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,
447 };
448
449 // Date patterns with Brazilian variations
450 datePatterns: [
451 /\d{1,2}\/\d{1,2}\/\d{4}/, // DD/MM/YYYY
452 /\d{1,2} de [a-z]+ de \d{4}/i, // "15 de janeiro de 2024"
453 /dia \d{1,2}/i, // "dia 15"
454 /mês que vem/i, // "mês que vem"
455 /semana que vem/i, // "semana que vem"
456 /hoje/i, // "hoje"
457 /amanhã/i, // "amanhã"
458 ];
459
460 // Brazilian bill types
461 billTypes: [
462 /boleto/i,
463 /conta/i,
464 /fatura/i,
465 /aluguel/i,
466 /condomínio/i,
467 /escola/i,
468 /plano de saúde/i,
469 /internet/i,
470 /luz/i,
471 /água/i,
472 /telefone/i,
473 ];
474}
475```
476
477### Voice-First Architecture
478
479#### Voice Command Processing
480```typescript
481// Essential voice commands system
482interface VoiceCommand {
483 command: string;
484 intent: 'balance_query' | 'payment_query' | 'transfer_query' | 'schedule_check';
485 confidence: number;
486 response: string;
487 processingTime: number;
488}
489
490// Six essential voice commands
491const ESSENTIAL_COMMANDS = [
492 "Como está meu saldo?", // Balance query
493 "Quanto posso gastar esse mês?", // Spending capacity
494 "Tem algum boleto programado?", // Scheduled bills
495 "Tem algum recebimento programado?", // Scheduled income
496 "Como ficará meu saldo no final do mês?", // Projection
497 "Faz uma transferência para..." // Money transfer
498];
499```
500
501#### AI Autonomy Levels
502```typescript
503interface AutonomyLevel {
504 level: number; // 50-95% autonomy progression
505 capabilities: string[];
506 confirmationRequired: boolean;
507 trustScore: number;
508}
509
510const AUTONOMY_LEVELS = {
511 LEARNING: { level: 25, requiresConfirmation: true, description: "Observing user patterns" },
512 ASSISTANT: { level: 50, requiresConfirmation: true, description: "Suggesting actions" },
513 AUTONOMOUS: { level: 75, requiresConfirmation: false, description: "Executing routine actions" },
514 TRUSTED: { level: 95, requiresConfirmation: false, description: "Full autonomous management" }
515};
516```
517
518### Real-Time Architecture
519
520#### Event-Driven Design
521```typescript
522// Domain events for financial operations
523interface FinancialEvent {
524 id: string;
525 aggregateId: string;
526 aggregateType: 'Transaction' | 'Account' | 'Budget';
527 eventType: string;
528 data: any;
529 metadata: {
530 userId: string;
531 timestamp: string;
532 source: 'voice' | 'ui' | 'api' | 'webhook';
533 };
534}
535
536// Real-time event handling
537class FinancialEventDispatcher {
538 async dispatch(event: FinancialEvent): Promise<void> {
539 // Store event in event store
540 await this.eventStore.save(event);
541
542 // Update real-time subscriptions
543 await this.realtimeService.publish(event);
544
545 // Execute synchronous handlers
546 await this.executeHandlers(event);
547
548 // Trigger AI autonomy evaluation
549 await this.aiEngine.evaluate(event);
550 }
551}
552```
553
554### Security & LGPD Compliance
555
556#### Data Protection Architecture
557```typescript
558// LGPD compliance implementation
559interface LGPDCompliance {
560 dataMinimization: boolean; // Collect only necessary data
561 purposeLimitation: boolean; // Use data for declared purposes only
562 retentionPolicy: string; // Data retention periods
563 userRights: {
564 access: boolean; // Right to access data
565 deletion: boolean; // Right to be forgotten
566 portability: boolean; // Right to data portability
567 consent: boolean; // Explicit consent management
568 };
569}
570
571// Security layers
572interface SecurityArchitecture {
573 encryption: {
574 atRest: 'AES-256'; // Supabase managed
575 inTransit: 'TLS 1.3'; // Enforced
576 };
577 authentication: {
578 primary: 'biometric'; // Face ID, Touch ID
579 secondary: 'password'; // Traditional backup
580 session: 'JWT'; // Secure tokens
581 };
582 authorization: {
583 rowLevelSecurity: true; // Tenant isolation
584 auditTrails: true; // Complete operation logging
585 };
586}
587```
588
589### Performance Optimization
590
591#### Voice Response Optimization
592```typescript
593// Performance targets for voice interactions
594const VOICE_PERFORMANCE_TARGETS = {
595 speechToText: 200, // milliseconds
596 intentProcessing: 150, // milliseconds
597 actionExecution: 100, // milliseconds
598 textToSpeech: 50, // milliseconds
599 totalResponse: 500 // milliseconds maximum
600};
601
602// Caching strategy for financial data
603interface CacheStrategy {
604 userProfiles: { ttl: 300000, max: 100 }; // 5 minutes
605 accountBalances: { ttl: 30000, max: 50 }; // 30 seconds
606 transactionHistory: { ttl: 60000, max: 200 }; // 1 minute
607 exchangeRates: { ttl: 86400000, max: 10 }; // 24 hours
608};
609```
610
611### Database Architecture
612
613#### Schema Design Patterns
614```sql
615-- Core user entity with LGPD compliance
616CREATE TABLE users (
617 id UUID PRIMARY KEY REFERENCES auth.users(id),
618 email TEXT UNIQUE NOT NULL,
619 autonomy_level INTEGER DEFAULT 50 CHECK (autonomy_level >= 50 AND autonomy_level <= 95),
620 voice_command_enabled BOOLEAN DEFAULT true,
621 data_processing_consent TIMESTAMP WITH TIME ZONE,
622 created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
623 updated_at TIMESTAMP WITH TIME ZONE DEFAULT now()
624);
625
626-- Financial transactions with audit trail
627CREATE TABLE transactions (
628 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
629 user_id UUID REFERENCES users(id) ON DELETE CASCADE,
630 amount DECIMAL(15,2) NOT NULL,
631 description TEXT NOT NULL,
632 category TEXT,
633 transaction_date TIMESTAMP WITH TIME ZONE NOT NULL,
634 status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'completed', 'failed')),
635 metadata JSONB DEFAULT '{}',
636 voice_command_id UUID REFERENCES voice_commands(id),
637 created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
638);
639
640-- Voice commands for AI learning
641CREATE TABLE voice_commands (
642 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
643 user_id UUID REFERENCES users(id) ON DELETE CASCADE,
644 command TEXT NOT NULL,
645 intent TEXT NOT NULL,
646 confidence DECIMAL(3,2),
647 response TEXT,
648 processing_time_ms INTEGER,
649 was_successful BOOLEAN,
650 created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
651);
652```
653
654### Development Workflow Patterns
655
656#### Essential Commands
657```bash
658# Development workflow
659bun dev # Start full-stack development
660bun dev:client # Frontend only (Vite + React)
661bun dev:server # Backend only (Hono + tRPC)
662
663# Quality assurance
664bun lint # OXLint + Biome validation
665bun type-check # TypeScript strict mode
666bun test:coverage # Unit tests with coverage
667bun quality # Full CI pipeline
668
669# Database operations
670bunx supabase db push # Apply migrations
671bunx supabase gen types # Generate TypeScript types
672bunx supabase db diff # Schema validation
673```
674
675#### Import Patterns
676```typescript
677// Supabase client integration
678import { supabase } from "@/integrations/supabase/client";
679
680// tRPC procedures
681import { router, protectedProcedure } from "@/server/trpc";
682
683// React Query for server state
684import { useQuery, useMutation } from "@tanstack/react-query";
685
686// TanStack Router
687import { createFileRoute } from "@tanstack/react-router";
688
689// Voice processing
690import { useVoiceRecognition } from "@/hooks/useVoiceRecognition";
691```
692
693## Implementation Patterns
694
695### Component Architecture
696```typescript
697// Voice-first component template
698interface VoiceComponentProps {
699 readonly onVoiceCommand?: (command: VoiceCommand) => void;
700 readonly accessibilityLabel?: string;
701 readonly children?: React.ReactNode;
702}
703
704export const VoiceFinancialComponent: React.FC<VoiceComponentProps> = ({
705 onVoiceCommand,
706 accessibilityLabel,
707 children
708}) => {
709 const { isListening, transcript } = useVoiceRecognition();
710 const { announceToScreenReader } = useAccessibility();
711
712 return (
713 <div
714 role="application"
715 aria-label={accessibilityLabel}
716 className={cn(
717 "voice-component",
718 isListening && "voice-listening"
719 )}
720 >
721 {children}
722 {isListening && (
723 <VoiceIndicator transcript={transcript} />
724 )}
725 </div>
726 );
727};
728```
729
730### Enhanced NLU System Architecture
731```typescript
732// Complete NLU system with Brazilian Portuguese specialization
733interface EnhancedNLUSystem {
734 // Core processing engine with sub-200ms target
735 processCommand: (audio: AudioBuffer) => Promise<NLUResult>;
736
737 // Brazilian Portuguese patterns with regional variations
738 brazilianPatterns: {
739 regions: RegionalPattern[];
740 slangTerms: SlangTerm[];
741 financialTerminology: FinancialTerm[];
742 };
743
744 // Learning analytics with hit/miss tracking
745 analytics: {
746 trackHitMiss: (command: string, success: boolean) => void;
747 getAccuracyMetrics: () => AccuracyMetrics;
748 generateLearningReport: () => LearningReport;
749 };
750
751 // Error recovery with multiple strategies
752 errorRecovery: {
753 classifyError: (error: NLUError) => ErrorType;
754 applyRecoveryStrategy: (error: NLUError) => Promise<NLUResult>;
755 learnFromCorrection: (original: string, corrected: string) => void;
756 };
757
758 // Performance monitoring and optimization
759 performance: {
760 trackProcessingTime: (duration: number) => void;
761 getSystemHealth: () => HealthMetrics;
762 generatePerformanceReport: () => PerformanceReport;
763 };
764}
765
766// Voice Activity Detection for real-time speech processing
767interface VoiceActivityDetection {
768 // Real-time speech detection with <20ms latency
769 detectSpeech: (audioChunk: AudioBuffer) => boolean;
770
771 // Automatic speech end detection
772 detectSpeechEnd: (silenceDuration: number) => boolean;
773
774 // Energy-based voice activity detection
775 calculateEnergyLevel: (audio: AudioBuffer) => number;
776}
777
778// Performance optimization patterns
779const VOICE_PERFORMANCE_TARGETS = {
780 speechToText: 200, // milliseconds (reduced from 500ms)
781 intentProcessing: 150, // milliseconds
782 actionExecution: 100, // milliseconds
783 textToSpeech: 50, // milliseconds
784 totalResponse: 500, // milliseconds maximum (reduced from 2000ms)
785
786 // Voice recognition settings
787 autoStopTimeout: 3000, // 3 seconds (reduced from 10s)
788 processingDelay: 100, // 100ms (reduced from 500ms)
789 minAudioDuration: 300, // 0.3 seconds minimum
790 maxAudioDuration: 10000, // 10 seconds maximum
791 silenceDuration: 1500, // 1.5 seconds (reduced from 2s)
792};
793
794// Brazilian Portuguese regional patterns
795interface BrazilianRegionalPatterns {
796 // São Paulo variations
797 saoPaulo: {
798 slang: ["meu bem", "grana", "boleta", "rolê", "parça"];
799 patterns: ["quanto tá", "me fala", "tipo assim"];
800 };
801
802 // Rio de Janeiro variations
803 rioDeJaneiro: {
804 slang: ["maneiro", "caraca", "você é brabo", "demais"];
805 patterns: ["me ajuda", "qualé", "sinistro"];
806 };
807
808 // Nordeste variations
809 nordeste: {
810 slang: ["oxente", "bão", "arre", "massa", "visse"];
811 patterns: ["me diga", "como cê tá", "vamos nessa"];
812 };
813
814 // Sul variations
815 sul: {
816 slang: ["bah", "tchê", "guri", "legal", "show"];
817 patterns: ["me mostra", "quanto é", "vamos fazer"];
818 };
819}
820
821// Enhanced voice command hook with optimizations
822interface OptimizedVoiceRecognition {
823 // Performance monitoring
824 processingTime: number;
825 successRate: number;
826 errorRate: number;
827
828 // Voice Activity Detection
829 voiceActivityDetection: VoiceActivityDetection;
830
831 // Brazilian Portuguese processing
832 regionalProcessor: BrazilianRegionalProcessor;
833
834 // Learning and analytics
835 analytics: NLUAnalytics;
836
837 // Error recovery
838 errorRecovery: ErrorRecoverySystem;
839
840 // Performance optimization methods
841 optimizeProcessing: () => void;
842 clearCache: () => void;
843 getPerformanceMetrics: () => PerformanceMetrics;
844}
845
846// Memory leak prevention patterns
847const MEMORY_MANAGEMENT = {
848 // Cleanup intervals and timeouts
849 clearAllTimers: () => {
850 clearInterval(refreshInterval.current);
851 clearTimeout(timeoutRef.current);
852 clearTimeout(clearResponseRef.current);
853 },
854
855 // Abort controller for async operations
856 abortController: new AbortController(),
857
858 // Proper cleanup on unmount
859 cleanup: () => {
860 voiceActivityDetection?.cleanup();
861 abortController.abort();
862 clearAllTimers();
863 },
864};
865```
866
867### API Design Patterns
868```typescript
869// tRPC procedure with comprehensive validation
870export const createTransactionRouter = router({
871 create: protectedProcedure
872 .input(z.object({
873 amount: z.number().positive().max(1000000),
874 description: z.string().min(1).max(500),
875 category: z.enum(['food', 'transport', 'housing', 'entertainment', 'other']),
876 date: z.string().datetime().optional(),
877 voiceCommand: z.string().optional(),
878 }))
879 .mutation(async ({ ctx, input }) => {
880 // Business logic validation
881 if (input.amount > ctx.user.dailyLimit) {
882 throw new TRPCError({
883 code: 'FORBIDDEN',
884 message: 'Amount exceeds daily spending limit'
885 });
886 }
887
888 // Create transaction with audit trail
889 const transaction = await createTransaction({
890 userId: ctx.user.id,
891 ...input,
892 source: 'voice_command',
893 metadata: {
894 ip: ctx.ip,
895 userAgent: ctx.userAgent,
896 }
897 });
898
899 // Real-time update
900 await ctx.realtime.publish(`user:${ctx.user.id}:transactions`, {
901 type: 'transaction_created',
902 data: transaction
903 });
904
905 return transaction;
906 }),
907});
908
909// Enhanced voice command processing API
910export const voiceCommandRouter = router({
911 process: protectedProcedure
912 .input(z.object({
913 audioData: z.string(), // base64 encoded audio
914 region: z.enum(['SP', 'RJ', 'NE', 'SUL', 'NORTE', 'CO']).optional(),
915 context: z.object({
916 previousCommands: z.array(z.string()).optional(),
917 userPreferences: z.object({
918 language: z.string().optional(),
919 slangLevel: z.number().optional(), // 0-1 formality level
920 }).optional(),
921 }).optional(),
922 }))
923 .mutation(async ({ ctx, input }) => {
924 // Process with enhanced NLU system
925 const startTime = Date.now();
926
927 try {
928 const result = await enhancedNLUEngine.processCommand({
929 audioData: input.audioData,
930 userId: ctx.user.id,
931 region: input.region || 'SP',
932 context: input.context,
933 });
934
935 const processingTime = Date.now() - startTime;
936
937 // Track performance metrics
938 await voiceAnalytics.trackProcessing({
939 userId: ctx.user.id,
940 processingTime,
941 success: result.success,
942 confidence: result.confidence,
943 intent: result.intent,
944 });
945
946 return {
947 ...result,
948 processingTime,
949 performanceTarget: processingTime <= VOICE_PERFORMANCE_TARGETS.totalResponse,
950 };
951
952 } catch (error) {
953 // Error recovery attempt
954 const recoveryResult = await errorRecovery.attemptRecovery({
955 error,
956 userId: ctx.user.id,
957 originalInput: input,
958 });
959
960 return recoveryResult;
961 }
962 }),
963
964 // Brazilian Portuguese pattern learning
965 learnPattern: protectedProcedure
966 .input(z.object({
967 originalCommand: z.string(),
968 correctedCommand: z.string(),
969 region: z.string(),
970 context: z.string().optional(),
971 }))
972 .mutation(async ({ ctx, input }) => {
973 await brazilianPatterns.learnFromCorrection({
974 userId: ctx.user.id,
975 original: input.originalCommand,
976 corrected: input.correctedCommand,
977 region: input.region,
978 context: input.context,
979 });
980
981 return { success: true };
982 }),
983
984 // Performance analytics endpoint
985 getAnalytics: protectedProcedure
986 .input(z.object({
987 timeframe: z.enum(['hour', 'day', 'week', 'month']),
988 metrics: z.array(z.enum([
989 'accuracy', 'latency', 'success_rate', 'error_rate', 'regional_performance'
990 ])),
991 }))
992 .query(async ({ ctx, input }) => {
993 return voiceAnalytics.getDetailedMetrics({
994 userId: ctx.user.id,
995 timeframe: input.timeframe,
996 metrics: input.metrics,
997 });
998 }),
999});
1000
1001// Voice command optimization patterns
1002const VOICE_OPTIMIZATION_PATTERNS = {
1003 // Caching strategies for frequently used commands
1004 caching: {
1005 commonCommands: new Map([
1006 ['saldo', { cachedResponse: true, ttl: 30000 }], // 30s cache
1007 ['transferência', { cachedResponse: false, ttl: 0 }],
1008 ['boletos', { cachedResponse: true, ttl: 60000 }], // 1m cache
1009 ]),
1010
1011 // Regional pattern caching
1012 regionalPatterns: new Map([
1013 ['SP', { patterns: saoPauloPatterns, lastUpdated: Date.now() }],
1014 ['RJ', { patterns: rioPatterns, lastUpdated: Date.now() }],
1015 ['NE', { patterns: nordestePatterns, lastUpdated: Date.now() }],
1016 ]),
1017 },
1018
1019 // Performance monitoring
1020 monitoring: {
1021 // Real-time metrics collection
1022 collectMetrics: (command: string, processingTime: number, success: boolean) => {
1023 performanceTracker.record({
1024 command,
1025 processingTime,
1026 success,
1027 timestamp: Date.now(),
1028 userId: getCurrentUserId(),
1029 });
1030 },
1031
1032 // Health check system
1033 healthCheck: async () => {
1034 const health = await systemHealth.check({
1035 voiceRecognition: { targetLatency: 200, currentLatency: getCurrentLatency() },
1036 nluProcessing: { targetLatency: 150, currentLatency: getNLULatency() },
1037 databaseOperations: { targetLatency: 100, currentLatency: getDBLatency() },
1038 });
1039
1040 return health;
1041 },
1042 },
1043
1044 // Error recovery strategies
1045 errorRecovery: {
1046 strategies: [
1047 'pattern_matching', // Try to match known patterns
1048 'context_inference', // Use conversation context
1049 'regional_adaptation', // Adapt for regional variations
1050 'user_history', // Learn from user's past corrections
1051 'clarification_request', // Ask user for help
1052 ],
1053
1054 applyStrategy: async (error: NLUError) => {
1055 for (const strategy of errorRecovery.strategies) {
1056 try {
1057 const result = await applyRecoveryStrategy(strategy, error);
1058 if (result.success) return result;
1059 } catch (e) {
1060 // Try next strategy
1061 }
1062 }
1063
1064 // Final fallback - ask for clarification
1065 return requestClarification(error);
1066 },
1067 },
1068};
1069```
1070
1071## Validation & Quality Gates
1072
1073### Architecture Compliance Checklist
1074- [ ] **KISS Principle**: Simple, direct implementation without over-engineering
1075- [ ] **YAGNI Principle**: Only essential features from requirements implemented
1076- [ ] **Type Safety**: End-to-end TypeScript with no implicit any
1077- [ ] **Voice First**: Primary interaction through voice commands
1078- [ ] **Real-time**: Instant updates via Supabase subscriptions
1079- [ ] **Security**: Row Level Security on all database tables
1080- [ ] **Performance**: Sub-500ms voice response times (updated to ≤500ms target)
1081- [ ] **Accessibility**: WCAG 2.1 AA+ compliance
1082- [ ] **LGPD**: Brazilian data protection compliance
1083- [ ] **Brazilian Market**: PIX, boletos, Portuguese localization
1084- [ ] **NLU System**: Enhanced Natural Language Understanding with Brazilian Portuguese specialization
1085- [ ] **Performance Monitoring**: Real-time analytics and learning systems
1086- [ ] **Voice Activity Detection**: Real-time speech processing with <20ms detection
1087- [ ] **Error Recovery**: Multi-strategy recovery with 80%+ success rate
1088- [ ] **Regional Adaptation**: Support for 6 major Brazilian regional variations
1089
1090### Enhanced Code Quality Standards
1091- **Test Coverage**: 90%+ for critical business logic including NLU systems
1092- **TypeScript**: Strict mode enabled, zero implicit any
1093- **Error Handling**: Comprehensive error boundaries and user feedback
1094- **Security**: Input validation, SQL injection prevention, XSS protection
1095- **Performance**: Lighthouse score ≥90, Core Web Vitals compliance
1096- **Voice Performance**: Sub-200ms processing for 95% of voice commands
1097- **Memory Management**: Zero memory leaks from intervals/timeouts
1098- **Regional Accuracy**: 90%+ accuracy for Brazilian Portuguese variations
1099- **System Health**: 99.9% uptime with automated monitoring
1100
1101### Enhanced Performance Standards
1102```typescript
1103// Updated performance targets based on latest optimizations
1104const ENHANCED_PERFORMANCE_TARGETS = {
1105 // Voice processing (reduced from previous targets)
1106 speechToText: 200, // milliseconds (reduced from 500ms)
1107 intentProcessing: 150, // milliseconds (reduced from 300ms)
1108 actionExecution: 100, // milliseconds (reduced from 200ms)
1109 textToSpeech: 50, // milliseconds (reduced from 100ms)
1110 totalResponse: 500, // milliseconds maximum (reduced from 1000ms)
1111
1112 // Voice recognition optimizations
1113 autoStopTimeout: 3000, // 3 seconds (reduced from 10s)
1114 processingDelay: 100, // 100ms (reduced from 500ms)
1115 minAudioDuration: 300, // 0.3 seconds minimum
1116 maxAudioDuration: 10000, // 10 seconds maximum (reduced from 30s)
1117 silenceDuration: 1500, // 1.5 seconds (reduced from 2s)
1118
1119 // NLU system performance
1120 nluProcessing: 150, // milliseconds target
1121 accuracyThreshold: 0.90, // 90% accuracy target
1122 errorRecoveryRate: 0.80, // 80% error recovery rate
1123 cacheHitRate: 0.60, // 60% cache hit rate
1124
1125 // Regional performance targets
1126 regionalAccuracy: {
1127 SP: 0.95, // São Paulo: 95%
1128 RJ: 0.92, // Rio de Janeiro: 92%
1129 NE: 0.88, // Nordeste: 88%
1130 SUL: 0.90, // Sul: 90%
1131 NORTE: 0.85, // Norte: 85%
1132 CO: 0.87, // Centro-Oeste: 87%
1133 },
1134
1135 // System health targets
1136 systemUptime: 0.999, // 99.9% uptime
1137 memoryUsage: 0.75, // 75% maximum memory usage
1138 cpuUsage: 0.70, // 70% maximum CPU usage
1139 databaseLatency: 100, // 100ms maximum database latency
1140};
1141```
1142
1143### Enhanced Quality Gates Checklist
1144- [ ] **Voice Processing**: Sub-200ms speech-to-text processing
1145- [ ] **NLU Accuracy**: 90%+ accuracy for Brazilian financial commands
1146- [ ] **Regional Support**: 6 major Brazilian regions with dedicated patterns
1147- [ ] **Error Recovery**: 80%+ success rate for intelligent error recovery
1148- [ ] **Performance Monitoring**: Real-time analytics with automated alerting
1149- [ ] **Learning System**: Continuous learning from user corrections
1150- [ ] **Memory Management**: Zero memory leaks from intervals/timeouts
1151- [ ] **Voice Activity Detection**: Real-time speech detection with <20ms latency
1152- [ ] **Cache Performance**: 60%+ hit rate for common commands
1153- [ ] **System Health**: 99.9% uptime with comprehensive monitoring
1154
1155### Enhanced Testing Requirements
1156```typescript
1157// Comprehensive testing patterns for voice systems
1158const ENHANCED_TESTING_REQUIREMENTS = {
1159 // Unit tests
1160 unitTests: {
1161 nluEngine: 95, // 95% coverage for NLU engine
1162 brazilianPatterns: 100, // 100% coverage for regional patterns
1163 errorRecovery: 90, // 90% coverage for error recovery
1164 performanceTracking: 85, // 85% coverage for performance systems
1165 },
1166
1167 // Integration tests
1168 integrationTests: {
1169 voiceProcessing: 90, // 90% coverage for end-to-end voice processing
1170 regionalVariations: 85, // 85% coverage for regional pattern testing
1171 realTimeUpdates: 80, // 80% coverage for real-time systems
1172 errorRecovery: 85, // 85% coverage for error recovery scenarios
1173 },
1174
1175 // Performance tests
1176 performanceTests: {
1177 voiceLatency: 'sub_500ms', // All voice operations under 500ms
1178 memoryUsage: 'no_leaks', // Zero memory leaks
1179 concurrency: '100_users', // Support for 100 concurrent users
1180 regionalAccuracy: '90_percent_plus', // 90%+ accuracy across regions
1181 },
1182
1183 // Accessibility tests
1184 accessibilityTests: {
1185 screenReader: 'wcag_aa_plus', // WCAG 2.1 AA+ compliance
1186 voiceNavigation: 'full_support', // Full voice navigation support
1187 keyboardNavigation: 'complete', // Complete keyboard navigation
1188 colorContrast: '4_5_ratio', // 4.5:1 minimum contrast ratio
1189 },
1190
1191 // Security tests
1192 securityTests: {
1193 sqlInjection: 'prevention', // SQL injection prevention
1194 xssPrevention: 'full', // XSS prevention
1195 dataEncryption: 'aes256', // AES-256 encryption
1196 lgpdCompliance: 'full', // Full LGPD compliance
1197 },
1198};
1199```
1200```
1201
1202## Common Architectural Decisions
1203
1204### Technology Choices
1205- **Bun over Node.js**: 3-5x performance improvement for voice processing
1206- **Supabase over Firebase**: PostgreSQL for financial data, better querying capabilities
1207- **tRPC over REST**: End-to-end type safety eliminates runtime errors
1208- **Hono over Express**: Edge-first architecture for sub-150ms API responses
1209- **React 19 over Vue**: Better voice processing hooks and concurrent features
1210
1211### Integration Patterns
1212- **Voice Commands**: Speech-to-text → Intent classification → Action execution → Text-to-speech
1213- **Real-time Updates**: Supabase subscriptions → Optimistic UI updates → Conflict resolution
1214- **Security**: JWT authentication → Row Level Security → Audit logging → LGPD compliance
1215- **Performance**: Edge deployment → Client-side caching → Lazy loading → Bundle optimization
1216
1217## Troubleshooting Common Issues
1218
1219### Voice Processing Performance
1220```typescript
1221// Optimize voice command processing
1222const optimizeVoiceProcessing = {
1223 // Preload speech recognition models
1224 preloadModels: true,
1225
1226 // Use Web Workers for heavy processing
1227 useWebWorkers: true,
1228
1229 // Cache common command patterns
1230 cacheCommonPatterns: true,
1231
1232 // Batch processing for multiple commands
1233 batchCommands: true,
1234};
1235```
1236
1237### Real-time Sync Issues
1238```typescript
1239// Handle real-time synchronization conflicts
1240const handleSyncConflicts = {
1241 // Version-based conflict resolution
1242 useVersioning: true,
1243
1244 // Optimistic updates with rollback
1245 optimisticUpdates: true,
1246
1247 // Automatic retry with exponential backoff
1248 retryStrategy: 'exponential-backoff',
1249
1250 // User notification for manual resolution
1251 notifyOnConflict: true,
1252};
1253```
1254
1255### Performance Monitoring and Analytics System
1256```typescript
1257// Comprehensive performance tracking for voice operations
1258interface VoicePerformanceAnalytics {
1259 // Real-time metrics collection
1260 realTimeMetrics: {
1261 processingTimes: number[]; // Track command processing times
1262 accuracyRates: Map<string, number>; // Accuracy by command type
1263 errorRates: Map<string, number>; // Error rates by category
1264 userSatisfaction: number[]; // User feedback scores
1265
1266 // Brazilian regional performance
1267 regionalPerformance: {
1268 SP: { accuracy: number, latency: number };
1269 RJ: { accuracy: number, latency: number };
1270 NE: { accuracy: number, latency: number };
1271 SUL: { accuracy: number, latency: number };
1272 NORTE: { accuracy: number, latency: number };
1273 CO: { accuracy: number, latency: number };
1274 };
1275 };
1276
1277 // System health monitoring
1278 systemHealth: {
1279 voiceRecognition: {
1280 targetLatency: 200; // milliseconds
1281 currentLatency: number;
1282 successRate: number;
1283 memoryUsage: number;
1284 };
1285
1286 nluProcessing: {
1287 targetLatency: 150; // milliseconds
1288 currentLatency: number;
1289 accuracy: number;
1290 confidenceThreshold: number;
1291 };
1292
1293 databaseOperations: {
1294 targetLatency: 100; // milliseconds
1295 currentLatency: number;
1296 connectionPool: number;
1297 queryPerformance: number;
1298 };
1299
1300 overallSystem: {
1301 uptime: number;
1302 errorCount: number;
1303 activeUsers: number;
1304 performanceScore: number; // 0-100
1305 };
1306 };
1307
1308 // Learning analytics
1309 learningAnalytics: {
1310 patternEvolution: {
1311 newPatterns: string[];
1312 improvedPatterns: string[];
1313 deprecatedPatterns: string[];
1314 adaptationRate: number;
1315 };
1316
1317 userAdaptation: {
1318 correctionsPerUser: Map<string, number>;
1319 learningRate: number;
1320 retentionRate: number;
1321 satisfactionImprovement: number;
1322 };
1323
1324 brazilianContextLearning: {
1325 regionalSlangAdoption: Map<string, number>;
1326 culturalContextUnderstanding: number;
1327 financialTerminologyAccuracy: number;
1328 };
1329 };
1330
1331 // Performance alerts and notifications
1332 alertSystem: {
1333 thresholds: {
1334 maxLatency: 500; // milliseconds
1335 minAccuracy: 0.85; // 85%
1336 maxErrorRate: 0.15; // 15%
1337 minSystemHealth: 80; // 80/100
1338 };
1339
1340 alerts: {
1341 performanceDegradation: boolean;
1342 accuracyDrop: boolean;
1343 systemFailure: boolean;
1344 userComplaints: boolean;
1345 };
1346
1347 notificationChannels: [
1348 'dashboard',
1349 'email',
1350 'slack',
1351 'sms'
1352 ];
1353 };
1354}
1355
1356// Implementation of performance tracking
1357const performanceTracker = {
1358 // Track individual command performance
1359 trackCommand: async (command: VoiceCommand, result: NLUResult) => {
1360 const metrics = {
1361 commandId: command.id,
1362 userId: command.userId,
1363 region: command.region,
1364 processingTime: result.processingTime,
1365 success: result.success,
1366 confidence: result.confidence,
1367 intent: result.intent,
1368 timestamp: Date.now(),
1369 };
1370
1371 // Store in performance database
1372 await supabase.from('voice_command_metrics').insert(metrics);
1373
1374 // Update real-time metrics
1375 updateRealTimeMetrics(metrics);
1376
1377 // Check for performance alerts
1378 checkPerformanceThresholds(metrics);
1379
1380 // Update learning analytics
1381 updateLearningAnalytics(metrics);
1382 },
1383
1384 // Generate performance reports
1385 generateReport: async (timeframe: 'hour' | 'day' | 'week' | 'month') => {
1386 const report = await supabase
1387 .from('voice_command_metrics')
1388 .select('*')
1389 .gte('timestamp', getTimestampForTimeframe(timeframe));
1390
1391 return {
1392 summary: calculateSummaryStats(report.data),
1393 regionalBreakdown: calculateRegionalStats(report.data),
1394 trends: calculateTrends(report.data),
1395 recommendations: generateRecommendations(report.data),
1396 };
1397 },
1398
1399 // Performance optimization suggestions
1400 optimizePerformance: async () => {
1401 const currentMetrics = await getCurrentMetrics();
1402 const optimizations = [];
1403
1404 if (currentMetrics.voiceRecognition.latency > 200) {
1405 optimizations.push({
1406 area: 'voice_recognition',
1407 suggestion: 'Increase VAD sensitivity or reduce audio buffer size',
1408 expectedImprovement: '15-25% latency reduction',
1409 });
1410 }
1411
1412 if (currentMetrics.nluProcessing.accuracy < 0.90) {
1413 optimizations.push({
1414 area: 'nlu_processing',
1415 suggestion: 'Add more Brazilian Portuguese training data',
1416 expectedImprovement: '5-10% accuracy increase',
1417 });
1418 }
1419
1420 if (currentMetrics.databaseOperations.latency > 100) {
1421 optimizations.push({
1422 area: 'database',
1423 suggestion: 'Add query indexes or implement caching',
1424 expectedImprovement: '20-30% latency reduction',
1425 });
1426 }
1427
1428 return optimizations;
1429 },
1430};
1431
1432// Brazilian Portuguese learning system
1433const brazilianLearningSystem = {
1434 // Learn from user corrections
1435 learnFromCorrection: async (correction: UserCorrection) => {
1436 const learningData = {
1437 originalCommand: correction.original,
1438 correctedCommand: correction.corrected,
1439 region: correction.region,
1440 userId: correction.userId,
1441 timestamp: Date.now(),
1442 };
1443
1444 // Store learning data
1445 await supabase.from('brazilian_portuguese_learning').insert(learningData);
1446
1447 // Update pattern recognition
1448 await updatePatternRecognition(learningData);
1449
1450 // Improve regional models
1451 await improveRegionalModels(correction.region, learningData);
1452
1453 // Track learning effectiveness
1454 await trackLearningEffectiveness(correction);
1455 },
1456
1457 // Adapt to regional variations
1458 adaptToRegionalVariations: async (region: string, patterns: string[]) => {
1459 const adaptationData = {
1460 region,
1461 patterns,
1462 adaptationDate: Date.now(),
1463 confidence: calculateConfidence(patterns),
1464 };
1465
1466 // Update regional patterns
1467 await supabase.from('regional_patterns').upsert(adaptationData);
1468
1469 // Deploy to production if confidence is high enough
1470 if (adaptationData.confidence > 0.8) {
1471 await deployRegionalAdaptation(region, patterns);
1472 }
1473 },
1474
1475 // Generate learning insights
1476 generateLearningInsights: async () => {
1477 const insights = await supabase
1478 .from('brazilian_portuguese_learning')
1479 .select('*')
1480 .gte('timestamp', Date.now() - 7 * 24 * 60 * 60 * 1000); // Last week
1481
1482 return {
1483 topCorrections: getTopCorrections(insights.data),
1484 regionalInsights: getRegionalInsights(insights.data),
1485 accuracyImprovements: calculateAccuracyImprovements(insights.data),
1486 futureRecommendations: generateFutureRecommendations(insights.data),
1487 };
1488 },
1489};
1490
1491// Error analysis and recovery patterns
1492const errorAnalysisSystem = {
1493 // Analyze common error patterns
1494 analyzeErrorPatterns: async () => {
1495 const errors = await supabase
1496 .from('voice_command_errors')
1497 .select('*')
1498 .gte('timestamp', Date.now() - 24 * 60 * 60 * 1000); // Last 24 hours
1499
1500 const errorPatterns = {
1501 regionalErrors: categorizeErrorsByRegion(errors.data),
1502 intentErrors: categorizeErrorsByIntent(errors.data),
1503 entityErrors: categorizeErrorsByEntity(errors.data),
1504 systemErrors: categorizeSystemErrors(errors.data),
1505 };
1506
1507 return {
1508 patterns: errorPatterns,
1509 recommendations: generateErrorRecommendations(errorPatterns),
1510 automatedFixes: identifyAutomatedFixes(errorPatterns),
1511 };
1512 },
1513
1514 // Implement automated error recovery
1515 implementErrorRecovery: async (errorType: string, fix: ErrorFix) => {
1516 const recoveryImplementation = {
1517 errorType,
1518 fixType: fix.type,
1519 implementation: fix.implementation,
1520 rolloutPercentage: fix.rolloutPercentage || 0.1, // Start with 10%
1521 effectiveness: 0,
1522 createdAt: Date.now(),
1523 };
1524
1525 // Store recovery implementation
1526 await supabase.from('error_recovery_implementations').insert(recoveryImplementation);
1527
1528 // Monitor effectiveness
1529 monitorRecoveryEffectiveness(recoveryImplementation);
1530
1531 return recoveryImplementation;
1532 },
1533};
1534```
1535
1536## Resources and References
1537
1538### Essential Documentation
1539- `references/tech-stack.md`: Complete technology specifications (Bun + Hono + React 19 + Supabase + tRPC)
1540- `references/database-schema.md`: Database design patterns with RLS and LGPD compliance
1541- `references/security-guidelines.md`: Security implementation guide with financial regulations
1542- `references/voice-interface.md`: Enhanced voice interaction patterns with regional variations
1543- `references/lgpd-compliance.md`: Brazilian data protection and privacy regulations
1544- `references/nlu-system.md`: Complete NLU architecture with Brazilian Portuguese specialization
1545- `references/performance-optimization.md`: Voice performance optimization patterns and benchmarks
1546
1547### Implementation Files (Latest)
1548- `src/lib/nlu/enhancedNLUEngine.ts`: Complete integrated NLU system
1549- `src/lib/nlu/brazilianPatterns.ts`: Brazilian Portuguese patterns with regional variations
1550- `src/lib/nlu/analytics.ts`: Hit/miss tracking and learning analytics
1551- `src/lib/nlu/contextProcessor.ts`: Context-aware processing with multi-turn support
1552- `src/lib/nlu/errorRecovery.ts`: Multi-strategy error recovery with 80%+ success rate
1553- `src/lib/nlu/performance.ts`: Real-time performance monitoring and health tracking
1554- `src/lib/stt/voiceActivityDetection.ts`: Real-time speech detection with <20ms latency
1555- `src/hooks/useVoiceRecognition.ts`: Optimized voice recognition with VAD integration
1556- `src/components/voice/VoiceDashboard.tsx`: Enhanced voice interface with performance indicators
1557
1558### Enhanced Tools and Scripts
1559- `scripts/validate-architecture.py`: Architecture compliance validation with NLU checks
1560- `scripts/performance-audit.py`: Performance benchmarking for voice operations (<500ms target)
1561- `scripts/security-scan.py`: Security vulnerability scanning with financial compliance
1562- `scripts/database-validator.py`: Schema validation and migration checking with RLS verification
1563- `scripts/voice-performance-test.ts`: Comprehensive voice command performance testing
1564- `scripts/regional-accuracy-validator.py`: Brazilian regional pattern validation
1565- `scripts/memory-leak-detector.py`: Memory leak detection for voice components
1566
1567### Updated Templates and Assets
1568- `assets/api-template/`: Enhanced tRPC procedure templates with NLU integration
1569- `assets/component-templates/`: React component boilerplates with voice optimization
1570- `assets/database-migrations/`: Migration script templates with performance indexes
1571- `assets/diagrams/`: Updated architecture diagrams including NLU and performance systems
1572- `assets/brazilian-patterns/`: Regional pattern templates for all 6 major regions
1573- `assets/voice-testing/`: Voice command testing templates and benchmarks
1574- `assets/error-recovery/`: Error recovery strategy templates and implementations
1575
1576### Performance Benchmarks
1577```typescript
1578// Latest performance benchmarks achieved
1579const CURRENT_PERFORMANCE_BENCHMARKS = {
1580 // Voice processing benchmarks
1581 averageVoiceProcessingTime: 180, // milliseconds (target: 200ms)
1582 p95VoiceProcessingTime: 220, // milliseconds (target: 500ms)
1583
1584 // NLU accuracy benchmarks
1585 overallAccuracy: 0.92, // 92% (target: 90%)
1586 brazilianRegionalAccuracy: {
1587 SP: 0.94, RJ: 0.91, NE: 0.87,
1588 SUL: 0.89, NORTE: 0.84, CO: 0.86
1589 },
1590
1591 // System performance benchmarks
1592 errorRecoverySuccessRate: 0.83, // 83% (target: 80%)
1593 cacheHitRate: 0.65, // 65% (target: 60%)
1594 systemUptime: 0.9992, // 99.92% (target: 99.9%)
1595
1596 // User satisfaction metrics
1597 userSatisfactionScore: 4.6, // 4.6/5.0
1598 taskCompletionRate: 0.94, // 94%
1599 voiceCommandAdoptionRate: 0.78, // 78%
1600};
1601```
1602
1603## How to Use This Skill
1604
16051. **Architecture Design**: Ask for guidance on voice-first financial architecture
16062. **Technology Decisions**: Get recommendations for Brazilian fintech stack choices
16073. **Implementation Patterns**: Use proven patterns for NLU, voice processing, and performance
16084. **Performance Optimization**: Apply latest optimizations for sub-200ms voice processing
16095. **Regional Adaptation**: Implement Brazilian Portuguese variations for better user experience
16106. **Quality Assurance**: Use enhanced testing patterns and validation criteria
16117. **Troubleshooting**: Resolve common issues with voice processing and NLU systems
1612
1613## Integration Points
1614
1615This skill integrates seamlessly with:
1616- **Enhanced NLU System**: Complete Brazilian Portuguese specialization
1617- **Performance Monitoring**: Real-time analytics and health tracking
1618- **Voice Activity Detection**: Optimized speech processing
1619- **Error Recovery**: Multi-strategy recovery with learning
1620- **Regional Adaptation**: 6 major Brazilian regional patterns
1621- **Learning Analytics**: Continuous improvement from user feedback
1622
1623---
1624
1625## Version History
1626
1627- **v2.1**: Enhanced with latest NLU system, voice performance optimizations, and comprehensive analytics
1628- **v2.0**: Added Brazilian Portuguese specialization and enhanced architecture patterns
1629- **v1.0**: Initial architecture skill for AegisWallet voice-first financial assistant
1630
1631This skill provides the complete architectural foundation needed to build scalable, secure, and performant voice-first financial applications for the Brazilian market, with the latest optimizations and enhanced NLU capabilities based on real-world implementation experience.