### Setup Local Backend with Python Source: https://github.com/guivaricoda/riskhub/blob/main/docs/central/03-operacoes-e-deploy.md Sets up a local Python backend environment using a virtual environment, installs dependencies, applies database migrations, and starts the uvicorn server. It relies on a `.env.local` file for configuration and allows offline work with `SKIP_DB_STARTUP=1`. ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt -r requirements-dev.txt alembic upgrade head uvicorn app.main:app --reload # http://127.0.0.1:8000 ``` -------------------------------- ### Setup Local Frontend with Node.js Source: https://github.com/guivaricoda/riskhub/blob/main/docs/central/03-operacoes-e-deploy.md Sets up the local frontend development environment by navigating to the frontend directory, installing npm packages, creating and configuring a local environment file, and starting the development server. It requires `VITE_PUBLIC_API_BASE_URL` to be correctly set. ```bash cd frontend npm install cp .env.example .env.local # ajustar variáveis npm run dev # http://localhost:5173 ``` -------------------------------- ### Initial Setup Script Source: https://github.com/guivaricoda/riskhub/blob/main/NOTION_UPDATE_OPENAPI.md A shell script named 'setup.sh' used for the initial setup of the project. Executing this script within the 'api/' directory installs all necessary dependencies and performs an initial validation of the API. ```bash cd api ./setup.sh # Instala tudo e valida ``` -------------------------------- ### Local Development Setup and Commands (Shell, Make) Source: https://github.com/guivaricoda/riskhub/blob/main/OPENAPI_PIPELINE_SUMMARY.md This snippet provides essential commands for setting up and interacting with the API locally. `setup.sh` handles initial dependency installation and artifact generation. The `Makefile` offers convenient shortcuts for daily tasks like validation, opening documentation, starting the mock server, and generating the Postman collection. It also includes instructions for developing the frontend using the mock server. ```shell cd api ./setup.sh ``` ```makefile # Validate spec make validate # Ver documentação make docs-open # Iniciar mock server make mock # Gerar Postman make postman ``` ```shell # Terminal 1 cd api && npm run mock # Terminal 2 cd frontend export VITE_PUBLIC_API_BASE_URL=http://localhost:4010 npm run dev ``` -------------------------------- ### Install Dependencies and Run Scripts Source: https://github.com/guivaricoda/riskhub/blob/main/api/README.md Installs project dependencies using npm and provides commands to validate the OpenAPI specification, generate HTML documentation, start a mock server, publish to SwaggerHub, and run contract tests. Assumes Node.js 20+ is installed. ```bash # Node.js 20+ check node --version # Install dependencies npm install # Available Commands: # Validate OpenAPI specification npm run validate # Generate HTML documentation npm run docs # Start mock server npm run mock # Publish to SwaggerHub npm run publish:swaggerhub # Run contract tests npm run test:contract # Generate Postman collection npm run generate:postman # Run all commands npm run all ``` -------------------------------- ### Start Prism Mock Server for RiskHub API Source: https://github.com/guivaricoda/riskhub/blob/main/api/README.md Starts a mock server for the RiskHub API using Prism. Supports static responses based on examples or dynamic responses. The mock server is accessible at http://localhost:4010. ```bash # Start mock server (static responses) npm run mock # Start mock server (dynamic responses) npm run mock:dynamic # Example Usage: # Healthcheck curl http://localhost:4010/healthz # List companies (mock) curl -H "Authorization: Bearer test" \ -H "x-tenant-id: 00000000-0000-0000-0000-000000000000" \ http://localhost:4010/companies # Create application (mock) curl -X POST http://localhost:4010/applications \ -H "Content-Type: application/json" \ -H "Authorization: Bearer test" \ -H "x-tenant-id: 00000000-0000-0000-0000-000000000000" \ -d '{"company_id": 1, "finalidade": "Capital de giro", "valor": 50000}' ``` -------------------------------- ### Install Frontend Dependencies and Run E2E Tests Source: https://github.com/guivaricoda/riskhub/blob/main/docs/staging-setup.md This section details the steps to set up the frontend environment for E2E testing. It includes installing Node.js dependencies using `npm ci`, installing Playwright browsers, and executing the staging E2E tests. ```bash cd frontend npm ci --legacy-peer-deps npx playwright install --with-deps npm run test:e2e:staging ``` -------------------------------- ### Install Project Dependencies (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/README.md Installs all necessary project dependencies using npm. This is typically the first step after cloning the repository. ```bash npm install ``` -------------------------------- ### Run Local Development Server (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/README.md Starts a local development server to preview the frontend application. The application will be accessible at http://localhost:5173. ```bash npm run dev ``` -------------------------------- ### Install Playwright Browsers for RiskHub E2E Tests Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet provides the solution for E2E test failures in RiskHub when using Playwright, caused by missing browser installations. It includes the command to install Playwright browsers with dependencies and then run the E2E tests. ```bash cd frontend npx playwright install --with-deps npm run test:e2e ``` -------------------------------- ### Start Staging Docker Stack Source: https://github.com/guivaricoda/riskhub/blob/main/docs/staging-setup.md This command starts the Docker Compose stack for the staging environment using the specified `docker-compose.staging.yml` file and the previously created `.env.staging` file for environment variables. ```bash docker-compose -f docker-compose.staging.yml --env-file .env.staging up -d ``` -------------------------------- ### Quick Diagnostic Commands (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/README.md A series of bash commands used for quick troubleshooting. Includes starting the dev server, checking Vercel environment variables, and verifying Supabase status. ```bash # 1. Test local npm run dev # 2. Verificar variáveis vercel env ls | grep VITE # 3. Status do Supabase supabase status ``` -------------------------------- ### New API Client Usage (TypeScript) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/CONSOLIDATION_REPORT.md Example of using the new official apiClient for making GET requests. This is the recommended approach for new code, utilizing the apiClient and API_ENDPOINTS for centralized configuration. ```typescript // ✅ FAZER - Usar apiClient oficial import { apiClient, API_ENDPOINTS } from '@/services/api'; const { data } = await apiClient.get( API_ENDPOINTS.companies.root ); ``` -------------------------------- ### Troubleshoot Health Check Failures for RiskHub Deployment Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet helps diagnose health check failures for the RiskHub service, indicated by load balancers reporting the service as down. It provides commands to manually check the `/health` and `/ready` endpoints and suggests checking `SKIP_DB_STARTUP`, `DATABASE_URL`, and Vercel function cold starts if issues persist. ```bash # Verificar manualmente: curl https://riskhub-fastapi-guilherme-varicodas-projects.vercel.app/health curl https://riskhub-fastapi-guilherme-varicodas-projects.vercel.app/ready # Se 503: verificar SKIP_DB_STARTUP e DATABASE_URL # Se timeout: verificar cold start (Vercel Functions) ``` -------------------------------- ### Run Application Locally with Docker Compose Source: https://github.com/guivaricoda/riskhub/blob/main/backend/README.Docker.md This command builds the Docker image if it doesn't exist and starts the application services defined in the docker-compose.yml file. It's the primary way to run the application during development. ```bash docker compose up --build ``` -------------------------------- ### Configure RiskHub Backend Database Connection Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet outlines solutions for database connection errors in the RiskHub backend. It includes commands to verify database connectivity using `psql`, instructions for skipping database startup during local development, and the correct format for `DATABASE_URL` with pooling for production. ```bash # Verificar conectividade: psql "$DATABASE_URL" -c "SELECT 1" # Para desenvolvimento local sem DB: export SKIP_DB_STARTUP=1 uvicorn app.main:app --reload # Produção: garantir DATABASE_URL com pooling: # postgresql+asyncpg://user:pass@host:5432/db?pool_size=10 ``` -------------------------------- ### Markdown Progress Tracking Example Source: https://github.com/guivaricoda/riskhub/blob/main/NEXT_STEPS_CRITICAL.md This snippet shows an example of a markdown list used for tracking the progress of the secret rotation and security incident. It includes placeholders for future actions and marks completed tasks with checkboxes. ```markdown - [x] 2025-09-30 13:44 - Varredura inicial (49 vazamentos) - [x] 2025-09-30 13:45 - Limpeza do working directory - [x] 2025-09-30 13:46 - Commit de segurança - [ ] YYYY-MM-DD HH:MM - Rotação de credenciais iniciada - [ ] YYYY-MM-DD HH:MM - Vercel Secrets configurados - [ ] YYYY-MM-DD HH:MM - Testes concluídos com sucesso - [ ] YYYY-MM-DD HH:MM - git-filter-repo executado - [ ] YYYY-MM-DD HH:MM - Force push concluído - [ ] YYYY-MM-DD HH:MM - Equipe notificada e re-clonou - [ ] YYYY-MM-DD HH:MM - Prevenção configurada - [ ] YYYY-MM-DD HH:MM - Incidente encerrado ✅ ``` -------------------------------- ### Continuous Operation Scripts Source: https://github.com/guivaricoda/riskhub/blob/main/docs/central/03-operacoes-e-deploy.md Lists useful scripts for maintaining continuous operation, including resetting Supabase environments, quick Vercel setup, and an orchestrator script. These scripts aid in managing and automating operational tasks. ```bash scripts/reset_supabase_env.sh scripts/quick_vercel_setup.sh scripts/orchestrator.py ``` -------------------------------- ### Install git-filter-repo using Homebrew Source: https://github.com/guivaricoda/riskhub/blob/main/NEXT_STEPS_CRITICAL.md Installs the 'git-filter-repo' tool, which is essential for rewriting Git history by removing specific files or paths. Homebrew is used as the package manager for installation on macOS. The installation is verified by checking the tool's version. ```bash brew install git-filter-repo # Verificar instalação: git filter-repo --version ``` -------------------------------- ### API Mock Endpoints for Kanban Board Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/src/components/kanban/README.md This snippet shows example API endpoint URLs for interacting with the Kanban board. These are mock endpoints and should be replaced with actual backend integration URLs in `/hooks/useKanban.tsx` for real-world usage. ```typescript // Substituir estas URLs por endpoints reais: GET /api/kanban/board/:id // Carregar board POST /api/kanban/cards // Criar card PATCH /api/kanban/card/:id // Editar card POST /api/kanban/move // Mover card ``` -------------------------------- ### Run RiskHub API Mock Server Locally Source: https://github.com/guivaricoda/riskhub/blob/main/api/README.md Starts a mock server for the RiskHub API using Prism. This is useful for frontend development to interact with API endpoints without a live backend. The server runs on http://localhost:4010. ```bash # Start mock server (static responses) npm run mock # Start mock server (dynamic responses) npm run mock:dynamic ``` -------------------------------- ### Local Development Environment Setup Source: https://github.com/guivaricoda/riskhub/blob/main/docs/ENV.md This section details how to set up a local development environment using .env files. It emphasizes copying a template file and filling it with development-specific values, explicitly warning against using production credentials locally. ```bash # Copiar template: cp env.example.txt .env # Preencher com valores de desenvolvimento # NUNCA usar credenciais de produção localmente! ``` -------------------------------- ### Storybook Setup and Configuration (TypeScript) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/REFACTORING_COMPLETED.md Configures Storybook for a Vite + React project, including essential addons for essentials, accessibility (a11y), and interaction testing. Demonstrates basic story creation and configuration files. ```typescript // .storybook/main.ts export default { stories: ['../src/**/*.stories.@(ts|tsx)'], addons: [ '@storybook/addon-essentials', '@storybook/addon-a11y', '@storybook/addon-interactions', ], framework: '@storybook/react-vite', }; ``` -------------------------------- ### Supabase CLI Operations Source: https://github.com/guivaricoda/riskhub/blob/main/docs/central/03-operacoes-e-deploy.md Commands for interacting with Supabase, including applying SQL migrations, starting the local Supabase stack, and running smoke tests after RLS policy adjustments. It specifies the expected bucket name for document storage. ```bash supabase db push supabase start supabase/tests/20250910_smoke_tests.sql ``` -------------------------------- ### Configure Frontend Environment Variables for RiskHub Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet shows how to configure environment variables for the RiskHub frontend. It covers setting up demo mode without Supabase or configuring it with real Supabase credentials. It also lists fallback values for essential environment variables. ```bash cd frontend # Opção 1: Modo demo (sem Supabase) echo "VITE_DEMO_MODE=true" > .env npm run dev # Opção 2: Com Supabase real// cp env.example .env # Preencher VITE_PUBLIC_SUPABASE_URL e VITE_PUBLIC_SUPABASE_ANON_KEY npm run dev ``` -------------------------------- ### Verify Migration Files Exist Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md Lists all SQL files within the Supabase migrations directory. This ensures that version-controlled database migrations are present and correctly named, which is critical for managing database schema changes. ```bash ls -la supabase/migrations/*.sql # Esperar: lista de arquivos SQL versionados ``` -------------------------------- ### Commit and Push with Detailed Message (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/OPENAPI_PIPELINE_SUMMARY.md This bash script outlines the process of committing all staged changes with a comprehensive commit message. The message details the specific improvements made to the OpenAPI validation and publishing pipeline, including endpoint additions, Spectral configuration, Dredd testing, Prism mock server setup, documentation generation, CI/CD pipeline setup, and ADR documentation. This detailed commit message aids in understanding the changes made. -------------------------------- ### Verify API Endpoints with cURL Examples Source: https://github.com/guivaricoda/riskhub/blob/main/infra/report.md Provides cURL commands to verify the functionality of various backend API endpoints after frontend alignment. These examples cover health checks, score creation, report retrieval, and company lookup by CNPJ, ensuring that the changes have resolved issues and the endpoints are functioning as expected. ```bash # Health GET {API_BASE}/api/v1/health # Score POST {API_BASE}/api/v1/score with { cnpj: "11222333000181" } (valid org and data required) # Report GET {API_BASE}/api/v1/report/{application_id} # Company by CNPJ GET {API_BASE}/api/v1/companies/cnpj/11222333000181?org_id={UUID} ``` -------------------------------- ### API Specification and Configuration (YAML, JSON, Shell, Make) Source: https://github.com/guivaricoda/riskhub/blob/main/OPENAPI_PIPELINE_SUMMARY.md This snippet covers essential configuration files for the OpenAPI specification. It includes the main OpenAPI definition (openapi.yaml), validation rules (.spectral.yaml), contract testing configuration (dredd.yml), package management (package.json), ignore rules (.gitignore), build automation (Makefile), setup script (setup.sh), and documentation files (README.md, QUICK_START.md). ```yaml openapi: 3.0.3 info: title: RiskHub API version: v1 paths: /healthz: get: summary: Health check responses: '200': description: OK servers: - url: http://localhost:4010/api ``` ```yaml extends: spectral:oas rules: info-contact: error path-declarations-must-exist: error ``` ```yaml language: node = func: "(event, context) => { console.log('Dredd hooks running!'); }" ``` ```json { "name": "riskhub-api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js", "mock": "prism mock openapi.yaml --port 4010" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@spectral/cli": "^6.0.0", "dredd": "^13.0.0", "prism": "^4.0.0", "redoc-cli": "^0.13.0" } } ``` ```git # Node modules node_modules/ # Build output build/ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory: coverage coverage/ # Directory: dist dist/ # Directory: docs docs/ # Directory: api api/ ``` ```makefile VALIDATE_CMD=spectral lint --skip-extend-errors api/openapi.yaml DOCS_CMD=redoc build --options-file redoc-config.json --output api/docs/index.html POSTMAN_CMD=openapi2postmanv2 -s api/openapi.yaml -o api/postman_collection.json MOCK_CMD=prism mock api/openapi.yaml --port 4010 validate: $(VALIDATE_CMD) docs-open: $(DOCS_CMD) @open api/docs/index.html postman: $(POSTMAN_CMD) mock: $(MOCK_CMD) setup: npm install make validate make docs-open make postman .PHONY: validate docs-open postman mock setup ``` ```shell #!/bin/bash set -e echo "Setting up RiskHub API environment..." # Install dependencies npm install # Validate OpenAPI spec echo "Validating OpenAPI spec..." make validate # Generate HTML documentation echo "Generating HTML documentation..." make docs-open # Generate Postman collection echo "Generating Postman collection..." make postman echo "RiskHub API setup complete." ``` -------------------------------- ### React Lazy Loading for Page Components Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/src/guidelines/Guidelines.md Provides an example of implementing code splitting and lazy loading for React page components using `React.lazy` and dynamic `import`. This is crucial for improving initial load performance. ```tsx // ✅ Sempre use lazy loading para páginas const Dashboard = React.lazy(() => import('./components/pages/Dashboard').then(m => ({ default: m.Dashboard })) ); ``` -------------------------------- ### Project File Structure Overview Source: https://github.com/guivaricoda/riskhub/blob/main/API_IMPLEMENTATION_REPORT.md This tree displays the directory and file structure of the project. It highlights key files such as the OpenAPI specification (openapi.yaml), Spectral validation rules (.spectral.yaml), Dredd configuration (dredd.yml), package.json, Makefile, setup script, and the generated HTML documentation. It also shows the location of CI/CD workflows and architectural decision records. ```tree api/ ├── openapi.yaml # ✅ Spec OpenAPI 3.1 (839 linhas) ├── .spectral.yaml # ✅ Regras de validação ├── dredd.yml # ✅ Config testes de contrato ├── package.json # ✅ Dependências e scripts ├── Makefile # ✅ Comandos facilitadores ├── setup.sh # ✅ Script de instalação ├── .gitignore # ✅ Ignora gerados e node_modules ├── README.md # ✅ Documentação completa ├── hooks/ │ └── dredd-hooks.js # ✅ Hooks para Dredd ├── scripts/ │ └── publish-swaggerhub.js # ✅ Script de publicação └── docs/ # ⚙️ Gerado: HTML documentation └── index.html # ✅ 1.26 MB standalone .github/workflows/ └── openapi-validation.yml # ✅ Pipeline CI/CD completo docs/adr/ └── ADR-004-openapi-validation-pipeline.md # ✅ Documentação arquitetural ``` -------------------------------- ### Temporary Legacy API Client Usage (TypeScript) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/CONSOLIDATION_REPORT.md Example of temporarily continuing to use the legacy API client. This is acceptable during the migration period but requires a TODO comment indicating the need for future migration. ```typescript // ⚠️ TEMPORÁRIO - Continuar usando se necessário import { api } from '@/utils/api'; // TODO: Migrate to apiClient (ADR-004) by 2025-12-31 const { data } = await api.get('/companies'); ``` -------------------------------- ### Test PostgreSQL Connection and Version Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md Connects to the Supabase PostgreSQL database using a provided connection string and executes a query to check the PostgreSQL version. It also lists available tables, verifying database accessibility and its major version compatibility. ```bash # Usar connection string do dashboard: psql "postgresql://postgres:PASSWORD@db.vsngipnudgoosiaaafhj.supabase.co:5432/postgres" # Testar query: SELECT version(); # Esperar: PostgreSQL 15.x # Verificar tabelas: \dt # Esperar: lista de tabelas do RiskHub ``` -------------------------------- ### Configure Backend Tests for Database Isolation in RiskHub Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet provides guidance for backend test failures in RiskHub that occur due to database connection issues. It recommends using specific flags like `SKIP_DB_STARTUP=1` and `PYTEST_CURRENT_TEST=1` for isolated test runs, and also shows how to execute integration tests that require a database connection. ```bash # Usar flags de teste: SKIP_DB_STARTUP=1 PYTEST_CURRENT_TEST=1 pytest tests/ -q # Para testes de integração com DB: ``` -------------------------------- ### Provision Staging Environment and Run E2E Tests Source: https://github.com/guivaricoda/riskhub/blob/main/EXECUTION_REPORT.md Steps to set up a staging environment using Supabase and Docker, including configuring environment variables and running end-to-end tests to ensure functionality before production deployment. ```bash # Criar projeto Supabase staging # Configurar env.staging.example.txt → .env.staging # docker-compose -f docker-compose.staging.yml up -d # npm run test:e2e:staging ``` -------------------------------- ### GitHub Actions Workflow for OpenAPI Validation Source: https://github.com/guivaricoda/riskhub/blob/main/NOTION_UPDATE_OPENAPI.md An example of a GitHub Actions workflow file located at '.github/workflows/openapi-validation.yml'. This file defines the CI/CD pipeline for validating the OpenAPI specification and potentially other related tasks as part of the project's automation strategy. ```yaml # .github/workflows/openapi-validation.yml # Example content, actual content may vary. name: OpenAPI Validation Pipeline on: push: branches: [ main ] pull_request: jobs: validate-spec: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Validate OpenAPI Spec uses: oasdiff/oasdiff-action@main # Example action, replace with actual if different with: spec_path: 'api/openapi.yaml' # Add other configurations as needed ``` -------------------------------- ### Check Port Conflicts with lsof Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md Identifies potential port conflicts for Supabase services by listing processes using specific ports. This is important for ensuring that the API and database services can start without interference from other applications. ```bash lsof -i :54321 -i :54322 # Esperar: vazio ou apenas processos supabase ``` -------------------------------- ### Create Missing Database Indexes in PostgreSQL Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md This SQL snippet provides examples of how to create missing database indexes in PostgreSQL. Use the `CREATE INDEX IF NOT EXISTS` command to add indexes to columns frequently used in queries to improve performance. ```sql -- Exemplo: CREATE INDEX IF NOT EXISTS idx_companies_cnpj ON companies(cnpj); CREATE INDEX IF NOT EXISTS idx_applications_company_id ON applications(company_id); ``` -------------------------------- ### Push Docker Image to Registry Source: https://github.com/guivaricoda/riskhub/blob/main/backend/README.Docker.md This command pushes the previously built and tagged Docker image ('myapp') to a specified container registry. Replace 'myregistry.com/myapp' with your actual registry path. This makes the image available for deployment on cloud platforms. ```bash docker push myregistry.com/myapp ``` -------------------------------- ### Bypass Storybook Peer Dependency Errors in RiskHub Frontend Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet provides a solution for build failures in the RiskHub frontend caused by conflicting Storybook peer dependencies. It suggests using `npm install --legacy-peer-deps` or `npm ci --legacy-peer-deps` to resolve these issues. ```bash cd frontend npm install --legacy-peer-deps # ou npm ci --legacy-peer-deps ``` -------------------------------- ### Build Docker Image for Deployment Source: https://github.com/guivaricoda/riskhub/blob/main/backend/README.Docker.md This command builds a Docker image for the application using the specified Dockerfile and tags it with 'myapp'. It's a prerequisite for deploying the application to a cloud environment. Ensure you are in the correct directory containing the Dockerfile. ```bash docker build -f backend/Dockerfile -t myapp . ``` -------------------------------- ### Adjust Content Security Policy (CSP) in RiskHub Frontend Source: https://github.com/guivaricoda/riskhub/blob/main/docs/TROUBLESHOOTING.md This snippet demonstrates how to modify the Content Security Policy (CSP) headers for the RiskHub frontend to resolve CSP violation errors. It shows an example of updating the `frontend/vercel.json` file to include necessary domains for connection sources. ```json // frontend/vercel.json { "headers": [{ "key": "Content-Security-Policy", "value": "...connect-src 'self' https://novo-dominio.com..." }] } ``` -------------------------------- ### Testar Contrato de API com Dredd Source: https://github.com/guivaricoda/riskhub/blob/main/API_IMPLEMENTATION_REPORT.md Configura e executa testes de contrato para a API usando Dredd. Garante que a implementação da API corresponda à sua especificação OpenAPI. Inclui configuração de hooks para setup e validação, injeção de headers e gerenciamento dinâmico de IDs. ```javascript // api/hooks/dredd-hooks.js const uuid = require('uuid'); module.exports = { before: function (done) { this.companyId = uuid.v4(); this.applicationId = uuid.v4(); done(); }, beforeEach: function (done) { // Inject dynamic IDs into requests if needed if (this.request) { this.request.url = this.request.url.replace('{companyId}', this.companyId).replace('{applicationId}', this.applicationId); } done(); } }; ``` ```yaml # api/dredd.yml {% extends 'dredd-hooks' %} local: http://127.0.0.1:8000 = language: nodejs hooks: 'api/hooks/dredd-hooks.js' path: api/openapi.yaml ignore: - paths: ['/documents/upload'] # Skipping multipart upload for now headers: x-tenant-id: "{{ "tenant-id" | random }}" correlation-id: "{{ "correlation-id" | random }}" ``` -------------------------------- ### Deploy Frontend to Vercel (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/README.md Commands to link the local project to a Vercel project, pull Vercel configurations, and deploy the application to production. ```bash vercel link --project=prj_x9S1wgfnJYzxq0o6hDQg3oGRegS3 --yes vercel pull --yes vercel deploy --prod ``` -------------------------------- ### Executar Mock Server com Prism Source: https://github.com/guivaricoda/riskhub/blob/main/API_IMPLEMENTATION_REPORT.md Inicia um mock server para a API usando Prism. Permite que os desenvolvedores frontend e outros consumidores da API trabalhem sem a necessidade do backend em execução. Suporta modos estático e dinâmico. ```bash # Modo Estático npm run mock # Modo Dinâmico npm run mock:dynamic ``` -------------------------------- ### Build Frontend for Production (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/README.md Builds the frontend application for production deployment. This command optimizes assets and generates static files. ```bash npm run build ``` -------------------------------- ### Document React Hook with JSDoc Examples Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/REFACTORING_COMPLETED.md This JSDoc provides comprehensive documentation for the `useEvaluation` hook, detailing its purpose, functionality, parameters, return values, and usage examples. It also includes links to related state management files and detailed workflow documentation, enhancing code understanding and maintainability. ```typescript /** * Hook for credit evaluation workflow * * Manages CNPJ lookup, document upload, scoring, and decision making. * Implements auto-save to localStorage and keyboard shortcuts. * * @returns {Object} Evaluation state and actions * @returns {EvaluationState} state - Current evaluation state * @returns {Function} handleCNPJSubmit - Submit CNPJ for analysis * * @example * ```tsx * function EvaluationPage() { * const { state, handleCNPJSubmit } = useEvaluation(); * return
handleCNPJSubmit(state.cnpj)} />; * } * ``` * * @see {@link ../stores/evaluationStore.ts} for state management * @see {@link docs/features/evaluation.md} for detailed workflow */ export function useEvaluation() { ... } ``` -------------------------------- ### Development and Preview Commands (Bash) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/REFACTORING_COMPLETED.md Scripts for running the development server, building the production application, and previewing the production build. Includes commands for bundle analysis and enforcing size limits. ```bash # Development npm run dev # http://localhost:3000 # Production build npm run build npm run preview # Build analysis npm run build:analyze # Bundle visualization npm run size-limit # Enforce size limits ``` -------------------------------- ### Gerar Documentação HTML com Redoc Source: https://github.com/guivaricoda/riskhub/blob/main/API_IMPLEMENTATION_REPORT.md Gera documentação interativa em HTML para a especificação OpenAPI usando Redoc. A documentação é autônoma, responsiva e inclui funcionalidades como busca e 'Try-it-out'. ```bash # Executar a geração da documentação npm run docs # Abrir a documentação gerada (exemplo para macOS) open docs/index.html ``` -------------------------------- ### Configure Staging Environment Variables Source: https://github.com/guivaricoda/riskhub/blob/main/docs/staging-setup.md This step configures the `.env.staging` file by fetching Supabase URL and anon key from GitHub secrets. It's crucial for the staging environment to connect to the correct Supabase instance. ```bash echo "VITE_PUBLIC_SUPABASE_URL=${{ secrets.STAGING_SUPABASE_URL }}" > .env.staging echo "VITE_PUBLIC_SUPABASE_ANON_KEY=${{ secrets.STAGING_SUPABASE_ANON_KEY }}" >> .env.staging # ... outras vars ``` -------------------------------- ### Deploy na Vercel (Previews e Produção) Source: https://github.com/guivaricoda/riskhub/blob/main/MasterPlan/02-agents/AGENT_backend_api_guardiao.md Instruções para realizar o deploy da aplicação na Vercel. O comando `vercel deploy` é usado para previews, enquanto `vercel --prod` é para deploy em produção. O CLI da Vercel mantém o contexto de deploy. ```bash vercel deploy vercel --prod ``` -------------------------------- ### Health Check API Endpoint Source: https://github.com/guivaricoda/riskhub/blob/main/docs/central/03-operacoes-e-deploy.md Demonstrates how to perform a health check on the backend API using `curl`. It shows the standard endpoint and an example if a `root_path` is configured, such as through a proxy. ```bash # Prefixo padrão /api/v1 curl -i https://riskhub-fastapi.vercel.app/api/v1/health # Se o root_path for "/api" (ex.: proxy adicionando prefixo), o caminho muda: curl -i https://riskhub-fastapi.vercel.app/api/api/v1/health ``` -------------------------------- ### Build Docker Image for Specific Platform Source: https://github.com/guivaricoda/riskhub/blob/main/backend/README.Docker.md This command builds a Docker image for a specific CPU architecture, which is useful when deploying to cloud environments with different architectures than the development machine (e.g., building for amd64 on an M1 Mac). The '--platform' flag specifies the target architecture. ```bash docker build --platform=linux/amd64 -f backend/Dockerfile -t myapp . ``` -------------------------------- ### Vercel Deploy and Environment Management Source: https://github.com/guivaricoda/riskhub/blob/main/docs/central/03-operacoes-e-deploy.md Outlines backend and frontend deployment strategies for Vercel. The backend uses Python 3.11, with GitHub Actions recommended for triggering production deploys. The frontend requires building with `npm run build` and pulling environment variables before deployment. ```bash # Backend: # Root: diretório raiz (api/index.py). # Runtime Python 3.11. Secrets privados; não usar prefixos VITE_. # Pipeline recomendado: GitHub Actions disparando `vercel deploy --prod` após testes. # Frontend: # Root: frontend/. # Build: npm run build. # Output: dist/. # Verificar envs VITE_PUBLIC_* antes do deploy (`vercel env pull`). ``` -------------------------------- ### Test Connection Pooling with PgBouncer Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md This snippet shows how to test connection pooling with PgBouncer by connecting to a PostgreSQL database with the `pgbouncer=true` parameter. It also includes a command to verify the active pools. ```bash # Testar connection pooling: psql "postgresql://postgres:PASSWORD@db.vsngipnudgoosiaaafhj.supabase.co:6543/postgres?pgbouncer=true" # Verificar pool: SHOW POOLS; # Esperar: lista de pools ativos ``` -------------------------------- ### Secrets Inventory and Rotation Source: https://github.com/guivaricoda/riskhub/blob/main/EXECUTION_REPORT.md Procedure for managing and rotating secrets to enhance security. This includes following a specific documentation guide and adhering to a scheduled rotation to minimize risks associated with compromised credentials. ```bash # Seguir docs/secrets-inventory.md # Agendado: 30 de dezembro de 2025 ``` -------------------------------- ### Makefile Help Command (Shell) Source: https://github.com/guivaricoda/riskhub/blob/main/OPENAPI_PIPELINE_SUMMARY.md This command is used to display help information for the Makefile. It lists available targets and their descriptions, providing guidance on how to use the project's build and task automation scripts. ```shell make help ``` -------------------------------- ### React Button Component Variants Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/src/guidelines/Guidelines.md Shows examples of how to use the Button component with different variants: primary, secondary, and destructive. These variants likely control the button's appearance and semantic meaning. ```tsx // Primário (ação principal) // Secundário (ação secundária) // Destrutivo (ações de risco) ``` -------------------------------- ### Check Project ID in TOML Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md Extracts and checks the `project_id` value from the `config.toml` file. This command verifies that a valid UUID format is used for the project identifier, which is essential for Supabase project management. ```bash grep "project_id"supabase/config.toml | awk '{print $3}' # Esperar: UUID válido (formato: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) ``` -------------------------------- ### Validate TOML Configuration Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md Validates the syntax of the Supabase `config.toml` file using the `toml-cli` tool. Ensures the configuration file adheres to the correct TOML format, which is crucial for Supabase CLI operations. ```bash npx toml-cli validate supabase/config.toml ``` -------------------------------- ### React JSX: Displaying Informative Error States Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/src/guidelines/Guidelines.md An example of how to render informative error messages to the user. It displays an alert box with an icon and descriptive text when an error occurs, likely related to connectivity. ```tsx // ✅ Estados de erro informativos {error && (
Erro de Conexão

Verifique sua internet. A aplicação está funcionando em modo demonstração.

)} ``` -------------------------------- ### Deprecated Axios API Client Usage (TypeScript) Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/CONSOLIDATION_REPORT.md Example of deprecated usage of the legacy API client ('api' from '@/utils/api'). This pattern should be avoided for new development and marked for migration. ```typescript // ❌ NÃO FAZER - Não usar axios legado import { api } from '@/utils/api'; // DEPRECATED! const { data } = await api.get('/companies'); ``` -------------------------------- ### Configure GitHub Secrets for CI/CD Source: https://github.com/guivaricoda/riskhub/blob/main/EXECUTION_REPORT.md Instructions for setting up necessary secrets within GitHub Actions settings. These secrets are crucial for authenticating and authorizing deployment processes using Vercel. ```bash # Settings → Secrets → Actions # Adicionar: VERCEL_TOKEN, VERCEL_PROJECT_ID, VERCEL_ORG_ID ``` -------------------------------- ### Configure CI/CD Jobs in GitHub Actions Source: https://github.com/guivaricoda/riskhub/blob/main/MasterPlan/01-roadmap.md Configures Continuous Integration and Continuous Deployment (CI/CD) jobs using GitHub Actions. This includes setting up jobs for linting, testing, contract validation, building artifacts, and automating deployments with approval gates. ```yaml # Example GitHub Actions workflow (conceptual) # name: CI/CD Pipeline # on: # push: # branches: [ main ] # pull_request: # jobs: # build-and-test: # runs-on: ubuntu-latest # steps: # - uses: actions/checkout@v3 # - name: Set up Python # uses: actions/setup-python@v3 # with: # python-version: '3.x' # - name: Install dependencies # run: pip install -r requirements.txt # - name: Lint with flake8 # run: | # pip install flake8 # flake8 . # - name: Run tests # run: pytest # deploy: # runs-on: ubuntu-latest # needs: build-and-test # if: github.ref == 'refs/heads/main' # steps: # - name: Deploy to Production # # Add deployment steps here (e.g., using scripts, cloud provider CLI) # run: echo "Deploying to production..." ``` -------------------------------- ### Instrument FastAPI and Frontend with OpenTelemetry and Sentry Source: https://github.com/guivaricoda/riskhub/blob/main/MasterPlan/01-roadmap.md Instruments the FastAPI backend and frontend applications using OpenTelemetry (OTel) for metrics collection and Sentry for error tracking. This includes configuring JSON logging for better log analysis and setting up dashboards for metrics and burn rate alerts. ```python # Example FastAPI instrumentation with OpenTelemetry (conceptual) # from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor # from opentelemetry.sdk.trace import TracerProvider # from opentelemetry.sdk.trace.export import BatchSpanProcessor # from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter # tracer_provider = TracerProvider() # tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) # tracer = tracer_provider.get_tracer(__name__) # app = FastAPI() # FastAPIInstrumentor.instrument_app(app) # Example Sentry integration (conceptual) # import sentry_sdk # sentry_sdk.init(dsn="YOUR_SENTRY_DSN") ``` ```javascript // Example frontend instrumentation with OpenTelemetry (conceptual) // import { WebTracerProvider } from '@opentelemetry/web'; // import { getWebTracer } from '@opentelemetry/api'; // import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; // const provider = new WebTracerProvider(); // provider.addSpanProcessor(new BatchSpanProcessor(new OTLPTraceExporter())); // provider.register(); // const tracer = getWebTracer('frontend'); // Example Sentry integration (conceptual) // import * as Sentry from '@sentry/browser'; // Sentry.init({ dsn: 'YOUR_SENTRY_DSN' }); ``` -------------------------------- ### Generate HTML Documentation with Redoc Source: https://github.com/guivaricoda/riskhub/blob/main/api/README.md Generates HTML documentation for the RiskHub API using Redoc. The generated documentation will be available at `api/docs/index.html`. Requires npm. ```bash npm run docs # Opens api/docs/index.html ``` -------------------------------- ### Check for Secrets in config.toml Source: https://github.com/guivaricoda/riskhub/blob/main/docs/supabase-audit-guide.md Searches the `config.toml` file for sensitive keywords like 'password', 'secret', or 'key'. This is a security measure to ensure that no sensitive credentials are accidentally committed to version control within the configuration file. ```bash grep -Ei "(password|secret|key)" supabase/config.toml # Esperar: vazio (secrets devem estar em .env) ``` -------------------------------- ### Document Feature Structure and API Implementation Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/CONSOLIDATION_REPORT.md This snippet outlines the directory structure for a new 'documents' feature, emphasizing the use of `apiClient` from the start for `documentsApi.ts`. It also includes a placeholder for API definition. ```typescript features/documents/ ├── api/ │ ├── documentsApi.ts ← Usar apiClient desde início │ └── queryKeys.ts ├── components/ │ ├── DocumentsPage.tsx │ ├── DocumentCard.tsx │ ├── DocumentFilters.tsx │ └── DocumentUpload.tsx ├── hooks/ │ └── useDocuments.ts ├── stores/ │ └── documentsStore.ts ├── types/ │ └── index.ts ├── index.ts └── README.md ``` -------------------------------- ### Initialize and Run Orchestrator Agent (Codex CLI) Source: https://github.com/guivaricoda/riskhub/blob/main/MasterPlan/02-agents/AGENT_orquestrador_estrategico.md This snippet shows how to initialize a session with the orchestrator agent and start a task using the Codex CLI. It requires specifying the agent name and the task to be performed. ```bash codex run --agent orquestrador --task "Planejar sprint MT2" ``` -------------------------------- ### React JSX: Single Call-to-Action per Viewport Source: https://github.com/guivaricoda/riskhub/blob/main/frontend/src/guidelines/Guidelines.md An example demonstrating the UI principle of having a single primary call-to-action (CTA) per viewport. It shows a simple layout with a title and a primary input, followed by a secondary button. ```tsx // ✅ Uma ação principal por tela

Análise de Crédito

{/* CTA principal */}
``` -------------------------------- ### Pydantic Settings for Application Configuration Source: https://github.com/guivaricoda/riskhub/blob/main/supabase/tasks/backend_updates_required.md This Pydantic BaseSettings class defines configuration variables for the application, including database connection details, Supabase keys, default organization settings for multi-tenancy, and user limits for different subscription plans. These settings are typically loaded from environment variables. ```python # app/core/config.py from pydantic import BaseSettings class Settings(BaseSettings): # ... configurações existentes # Supabase Service Role (para operações administrativas) SUPABASE_SERVICE_ROLE_KEY: str = None # Configurações de multi-tenant DEFAULT_ORG_NAME: str = "Default Organization" DEFAULT_ORG_DOMAIN: str = "default.riskhub.com" # Limites por plano BASIC_PLAN_USER_LIMIT: int = 5 PRO_PLAN_USER_LIMIT: int = 20 ENTERPRISE_PLAN_USER_LIMIT: int = -1 # Ilimitado class Config: env_file = '.env' env_file_encoding = 'utf-8' ``` -------------------------------- ### Post-Deployment Validation Commands Source: https://github.com/guivaricoda/riskhub/blob/main/EXECUTION_REPORT.md Commands to validate the frontend and backend after deployment. Includes checking HTTP status codes, verifying environment variables, and performing basic health and readiness checks for the backend services. ```bash # Frontend: curl -I https://riskhub.com.br/ # Esperar: 200 OK # Verificar console (DevTools): # - Sem erros de ENV # - Warnings esperados: "[ENV] Missing optional variables..." (se sem .env) # Backend: curl https://riskhub-fastapi-guilherme-varicodas-projects.vercel.app/health # Esperar: {"status":"ok"} curl https://riskhub-fastapi-guilherme-varicodas-projects.vercel.app/ready # Esperar: {"status":"ready"} # Smoke test completo: # 1. Abrir https://riskhub.com.br # 2. Fazer login # 3. Cadastrar empresa (ou visualizar) # 4. Verificar logs (sem 500) # Monitorar por 24h: vercel logs riskhub --since 24h | grep -Ei "error|exception" | wc -l # Baseline: < 10 erros/dia (noise normal) ```