# FluxiQ PIX — Codebase Audit, Cloud-Agnostic Deployment & Implementation Guide

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** Audit and clean the entire PIX codebase, create cloud-agnostic deployment artifacts, and produce a comprehensive VitePress implementation guide for both FluxiQ-managed and client self-deploy scenarios.

**Approach:** Audit-First, Then Parallel (Phase A → Phase B streams)

**Date:** 2026-02-13

---

## Context

FluxiQ PIX is a Brazilian instant payment processing platform:
- Backend: Elixir umbrella (4 apps, ~394 endpoints, 27 migrations)
- Frontend: 2 Vue 3 portals (admin: 82 routes, user: 30 routes)
- Infrastructure: PostgreSQL, Redis, NATS JetStream
- Currently deployed on GCP (GKE, Cloud SQL, Memorystore)
- Target: deployable to AWS, GCP, Azure, OCI, and on-premises (ProxMox + OPNsense + HAProxy)

## Key Decisions

1. **Deployment model:** Both FluxiQ-managed hosting and client self-deploy
2. **Documentation format:** VitePress docs site (PT-BR primary, EN-US, ZH-CN)
3. **Audit scope:** Full audit + fix everything (clean baseline for client deployments)
4. **On-premises scale:** Both single-node and HA cluster supported
5. **On-premises infra:** PostgreSQL, Redis, NATS run native on VMs (no containers). Only application code (Elixir/Phoenix, Vue, VitePress) runs in containers.
6. **User Frontend:** Audit will evaluate whether to merge into Admin (RBAC modules), repurpose as operator portal, or remove. End-user features (send PIX, create key) belong in Core Banking IB, not PIX platform.

---

## Phase A: Deep Codebase Audit (10 Parallel Agents)

### Agent 1: Backend Architecture
- Module organization, supervision trees, OTP patterns
- Duplicate modules, dead code, improper abstractions
- Verify all `defdelegate` wrappers are necessary
- Check GenServer patterns (timeouts, handle_info coverage)

### Agent 2: Database & Migrations
- All 27 migrations: idempotent? Work on fresh DB?
- Schema coherence: Ecto schemas match actual DB tables?
- Seed data: 11 seed files ordered correctly? Repeatable?
- Missing indexes, constraints, or foreign keys for new deploy
- Partition strategy review (messages, activity_log, login_history)

### Agent 3: API Surface
- All ~394 endpoints: consistent error handling (RFC 7807)?
- Input validation completeness
- Response serialization consistency (snake_case vs camelCase)
- OpenAPI/Swagger readiness
- Missing CRUD operations or incomplete resources

### Agent 4: Auth & Security
- JWT flow: secret fallback chain, token lifecycle
- CSRF: double-submit pattern correctness
- RBAC: RequirePermission coverage (all sensitive endpoints?)
- Rate limiting: all entry points covered?
- Hardcoded secrets, default passwords in code
- RSA key management, certificate handling

### Agent 5: NATS & Workers
- 7 streams: subject naming, retention, replay policies
- BaseWorker: error handling, retry logic, DLQ flow
- Message contracts: documented? Validated?
- Backpressure: adaptive polling effectiveness
- Cross-service message propagation (trace_id, correlation)

### Agent 6: Frontend (Admin)
- 82 routes, 17 stores, 27 services, 86 views, 12 components
- Dead components, unused imports, duplicate logic
- API service alignment with backend endpoints
- i18n completeness (5 locales, 568 keys each)
- Chart.js integration, WebSocket monitoring store

### Agent 7: Frontend (User) — CRITICAL EVALUATION
- Full functionality audit: what does each view do?
- Identify end-user features that belong in Core Banking IB:
  - PIX key creation/management (individual user)
  - Send PIX payment
  - Transaction history (personal)
- Identify valid PIX platform features:
  - Institution key management (admin function)
  - Transaction monitoring (operator function)
- Recommendation: merge into Admin with RBAC, repurpose, or remove

### Agent 8: Config & Environment
- All env vars: documented? Defaults sensible?
- GCP-specific assumptions in code (project IDs, regions, service URLs)
- K8s manifests: portable or GCP-locked?
- Docker images: base images, multi-stage builds, size optimization
- Config files: runtime.exs patterns, compile-time vs runtime config

### Agent 9: Dependencies & Build
- mix.exs: unused deps, version pinning, security advisories
- package.json: unused packages, outdated versions
- Dockerfiles: layer caching, build reproducibility
- cloudbuild.yaml: portable? Can be replaced with generic CI/CD?
- Elixir releases: proper config, health checks in release

### Agent 10: Cross-Cutting Concerns
- Logging: consistent levels, structured output, correlation IDs
- Telemetry: metric coverage, custom events
- Error codes: complete catalog? Documented?
- i18n: missing translations, locale fallback
- Code style: consistent formatting, naming conventions

### Audit Output
Structured findings report per agent:
- Finding ID, severity (CRITICAL/HIGH/MEDIUM/LOW)
- File path, line number
- Description + recommended fix
- Effort estimate (S/M/L)

---

## Phase B, Stream 1: Code Fixes

Based on audit findings:

| Category | Expected Work |
|----------|---------------|
| Duplicate modules | Consolidate into canonical locations (Shared schema pattern) |
| Dead code | Remove unused modules, functions, aliases, imports |
| User Frontend | Merge/repurpose/remove based on Agent 7 findings |
| Migration cleanup | Ensure fresh-DB compatibility, fix ordering issues |
| Seed pipeline | Consolidate 11 seed files, document seed order |
| Hardcoded values | Extract to env vars / runtime config |
| Cloud abstraction | Replace GCP-specific code with generic interfaces |
| Binary handling | Consistent UUID, Decimal, DateTime across modules |
| Error consistency | RFC 7807 everywhere, consistent error atoms |
| API serialization | Consistent snake_case → camelCase in all controllers |

---

## Phase B, Stream 2: Cloud-Agnostic Deployment Artifacts

### Directory Structure

```
deploy/
├── docker-compose/
│   ├── docker-compose.yml          # Application services only
│   ├── docker-compose.dev.yml      # Dev override (includes DB/Redis/NATS in containers)
│   ├── docker-compose.ha.yml       # HA override (replicas, load balancer)
│   └── .env.example                # All env vars with documentation
├── kubernetes/
│   └── helm/pix/
│       ├── Chart.yaml
│       ├── values.yaml             # Cloud-agnostic defaults
│       ├── values-aws.yaml         # AWS (EKS, RDS, ElastiCache, MSK/NATS)
│       ├── values-gcp.yaml         # GCP (GKE, Cloud SQL, Memorystore)
│       ├── values-azure.yaml       # Azure (AKS, Azure DB, Redis Cache)
│       └── values-oci.yaml         # OCI (OKE, Autonomous DB)
├── on-premises/
│   ├── postgresql/
│   │   ├── install.sh              # PostgreSQL 16 cluster setup (Patroni + etcd)
│   │   ├── patroni.yml             # Patroni HA config
│   │   ├── pg_hba.conf             # Auth config template
│   │   └── postgresql.conf         # Tuned for PIX workload
│   ├── redis/
│   │   ├── install.sh              # Redis 7 cluster setup (3 masters + 3 replicas)
│   │   ├── redis.conf              # Base config
│   │   └── sentinel.conf           # Sentinel for failover (alternative to cluster)
│   ├── nats/
│   │   ├── install.sh              # NATS JetStream cluster setup (3 nodes)
│   │   ├── nats-server.conf        # JetStream enabled, clustering
│   │   └── streams.sh              # Create all 7 JetStream streams
│   ├── haproxy/
│   │   ├── haproxy.cfg             # Frontend + backend pools for all services
│   │   └── ssl/                    # TLS certificate management
│   ├── opnsense/
│   │   ├── firewall-rules.xml      # Import-ready firewall rules
│   │   └── network-diagram.md      # VLAN/subnet layout
│   ├── proxmox/
│   │   ├── vm-templates.md         # VM specs per role (DB, cache, NATS, app)
│   │   └── cloud-init/             # Cloud-init configs per VM role
│   └── single-node/
│       ├── install.sh              # All-in-one setup (PostgreSQL + Redis + NATS + app)
│       └── README.md               # Minimum requirements, step-by-step
├── terraform/
│   ├── modules/
│   │   ├── database/               # PostgreSQL (RDS/Cloud SQL/Azure DB/OCI)
│   │   ├── cache/                  # Redis (ElastiCache/Memorystore/Azure Cache)
│   │   ├── messaging/              # NATS (VM-based on all clouds)
│   │   ├── kubernetes/             # K8s cluster (EKS/GKE/AKS/OKE)
│   │   └── networking/             # VPC, subnets, firewalls
│   ├── aws/main.tf
│   ├── gcp/main.tf
│   ├── azure/main.tf
│   └── oci/main.tf
└── scripts/
    ├── setup.sh                    # Interactive setup wizard
    ├── migrate.sh                  # DB migration runner (any environment)
    ├── seed.sh                     # Seed data loader
    ├── healthcheck.sh              # Post-deploy verification
    ├── backup.sh                   # DB + config backup
    └── rotate-certs.sh             # Certificate rotation
```

### On-Premises Architecture (HA)

```
                    ┌─────────────┐
                    │  OPNsense   │
                    │  Firewall   │
                    └──────┬──────┘
                           │
                    ┌──────┴──────┐
                    │   HAProxy   │
                    │  (2 nodes)  │
                    └──────┬──────┘
                           │
              ┌────────────┼────────────┐
              │            │            │
        ┌─────┴─────┐ ┌───┴───┐ ┌─────┴─────┐
        │ App Node 1│ │App N 2│ │ App Node 3│
        │ (Docker)  │ │(Docker│ │ (Docker)  │
        │ Backend   │ │Backend│ │ Backend   │
        │ Frontend  │ │Fronten│ │ Frontend  │
        └───────────┘ └───────┘ └───────────┘
              │            │            │
    ┌─────────┼────────────┼────────────┼─────────┐
    │         │            │            │         │
┌───┴───┐ ┌──┴──┐ ┌──────┴──────┐ ┌──┴──┐ ┌───┴───┐
│PG Pri │ │PG R │ │ Redis Cluster│ │NATS1│ │NATS 3 │
│Patroni│ │Repl │ │ 3M + 3R     │ │NATS2│ │       │
└───────┘ └─────┘ └─────────────┘ └─────┘ └───────┘
  (VMs — native installations, no containers)
```

---

## Phase B, Stream 3: VitePress Implementation Guide

### Structure

```
docs/implementation/
├── .vitepress/
│   └── config.ts                   # Multi-locale, sidebar, nav
├── index.md                        # Landing page with quick links
├── pt-BR/                          # Portuguese (primary)
│   ├── guide/
│   │   ├── introduction.md         # What is FluxiQ PIX
│   │   ├── architecture.md         # System architecture overview
│   │   ├── requirements.md         # Hardware, software, network prereqs
│   │   ├── quick-start.md          # 15-min Docker Compose setup
│   │   └── concepts.md             # PIX, DICT, SPI, MED 2.0, ANS basics
│   ├── deployment/
│   │   ├── overview.md             # Deployment models (managed vs self)
│   │   ├── docker-compose.md       # Single-node + HA with Docker
│   │   ├── kubernetes.md           # Helm on any K8s
│   │   ├── aws.md                  # AWS-specific guide
│   │   ├── gcp.md                  # GCP-specific guide
│   │   ├── azure.md                # Azure-specific guide
│   │   ├── oci.md                  # OCI-specific guide
│   │   └── on-premises.md          # ProxMox + OPNsense + HAProxy
│   ├── configuration/
│   │   ├── environment.md          # All env vars reference
│   │   ├── database.md             # PostgreSQL setup + schemas
│   │   ├── nats.md                 # NATS JetStream cluster
│   │   ├── redis.md                # Redis cluster
│   │   ├── certificates.md         # ICP-Brasil, mTLS, XMLDSig
│   │   ├── bacen.md                # DICT/SPI connectivity
│   │   └── core-banking.md         # Core integration (NATS, JWT)
│   ├── administration/
│   │   ├── portal.md               # Admin portal usage
│   │   ├── users.md                # Users, groups, RBAC, MFA
│   │   ├── monitoring.md           # Real-time dashboard
│   │   ├── accounting.md           # GL, COSIF, BCB 4010
│   │   ├── settlement.md           # Netting, reconciliation
│   │   └── simulator.md            # BACEN simulator
│   ├── operations/
│   │   ├── backup.md               # Backup & disaster recovery
│   │   ├── scaling.md              # Horizontal scaling
│   │   ├── troubleshooting.md      # Common issues + fixes
│   │   ├── observability.md        # Logs, metrics, tracing
│   │   └── maintenance.md          # Upgrades, migrations, partitions
│   ├── integration/
│   │   ├── api.md                  # Full API reference
│   │   ├── webhooks.md             # Event webhooks
│   │   ├── nats-events.md          # NATS subject catalog
│   │   └── sso.md                  # SSO integration
│   └── reference/
│       ├── architecture-detail.md  # Detailed diagrams
│       ├── database-schema.md      # Full ERD
│       ├── error-codes.md          # Error catalog
│       ├── glossary.md             # Terminology
│       └── changelog.md            # Version history
├── en-US/                          # English (mirrors pt-BR structure)
└── zh-CN/                          # Chinese (mirrors pt-BR structure)
```

### Key Content Principles
- Every page has a "Prerequisites" and "Expected Outcome" section
- All commands are copy-pasteable with expected output shown
- Architecture diagrams use Mermaid (rendered by VitePress)
- Each cloud provider guide follows identical structure for easy comparison
- Troubleshooting is symptom-based ("I see X error" → solution)

---

## Execution Timeline

| Phase | Duration | Parallel? | Deliverables |
|-------|----------|-----------|-------------|
| A: Deep Audit | ~1 session | 10 agents parallel | Findings report |
| B1: Code Fixes | ~1-2 sessions | Sequential (depends on audit) | Clean codebase |
| B2: Deploy Artifacts | ~1 session | Parallel with B1 | Helm, Compose, Terraform, on-prem |
| B3: VitePress Guide | ~2-3 sessions | Parallel with B1 | Full docs site |

---

## Success Criteria

1. All audit findings CRITICAL/HIGH resolved
2. Fresh `mix ecto.setup` works from zero (clean DB)
3. `docker-compose up` starts full system in <5 minutes
4. Helm chart deploys to any K8s with only values file change
5. On-prem guide: tested single-node + HA scenarios documented
6. VitePress site builds, all 3 locales, no broken links
7. User Frontend decision implemented (merge/repurpose/remove)
