Imagine o Claude Code rodando 100% de forma autônoma por horas, codificando e revisando seu próprio código até que tudo esteja completamente concluído.
Este é o Claudiomiro! https://github.com/samuelfaj/claudiomiro
O Problema com o Claude Code
Ao usar o Claude Code diretamente para tarefas complexas, você provavelmente já notou que ele para antes de concluir o trabalho. Isso acontece por boas razões:
- Economia de tokens: o Claude Code tenta conservar tokens parando após uma quantidade razoável de trabalho.
- Limitações de escopo: ele pressupõe que você quer revisar o progresso antes de continuar.
- Gerenciamento de contexto: tarefas longas podem esgotar as janelas de contexto.
O resultado? Você se vê digitando "continue" repetidamente, gerenciando o fluxo de trabalho manualmente.
O que é o Claudiomiro?
O Claudiomiro é uma aplicação CLI em Node.js que encapsula o Claude AI em um fluxo de trabalho estruturado e autônomo. Ele não apenas responde perguntas ou gera código; ele conclui funcionalidades e refatorações inteiras seguindo um processo disciplinado de 5 etapas:
- Inicialização: analisa a tarefa, cria um branch git, aprimora o prompt.
- Pesquisa: pesquisa profundamente a base de código e a documentação relevante.
- Implementação: executa múltiplas vezes, escrevendo todo o código, testes e documentação.
- Testes: executa todos os testes, corrige falhas, valida que tudo funciona.
- Commit & Push: cria commits significativos e envia para o repositório.
A Solução Claudiomiro: Loop Autônomo
Veja como funciona:
O Mecanismo de Loop
┌─────────────────────────────────────────────────────────────┐
│ AUTONOMOUS LOOP │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. Check State: What step are we on? │
│ ↓ │
│ 2. Execute Current Step │
│ ↓ │
│ 3. Check Completion Markers: │
│ • PROMPT.md exists? → Move to Research │
│ • TODO.md exists? → Check if "Fully implemented: YES" │
│ • Not fully implemented? → Run Implementation again │
│ • Fully implemented? → Move to Testing │
│ • GITHUB_PR.md exists? → Move to Commit │
│ ↓ │
│ 4. Loop back to Step 1 │
│ │
│ Maximum 15 iterations to prevent infinite loops │
│ │
└─────────────────────────────────────────────────────────────┘
Exemplo de Loop Autônomo
Veja o que acontece quando você executa uma tarefa complexa:
$ claudiomiro --prompt="Refactor authentication system"
Cycle 1: [Step 1] Creating PROMPT.md and TODO.md
Cycle 2: [Step 2] Researching codebase and updating TODO.md
Cycle 3: [Step 3] Implementing tasks (TODO.md shows "Fully implemented: NO")
Cycle 4: [Step 3] Continue implementing (still "NO")
Cycle 5: [Step 3] Continue implementing (still "NO")
Cycle 6: [Step 3] Final implementation (changes to "Fully implemented: YES")
Cycle 7: [Step 4] Running tests... ❌ 3 tests failed
Cycle 8: [Step 3] Fixing failing tests
Cycle 9: [Step 4] Running tests... ✅ All tests passed!
Cycle 10: [Step 5] Creating commit and pushing
✓ Task completed in 10 autonomous cycles
Mecanismos de Segurança
- Máximo de 15 ciclos para evitar execução infinita.
- A validação do arquivo de estado garante que o progresso está sendo feito de fato.
- A detecção de erros interrompe a execução se o mesmo erro ocorrer repetidamente.
- Use
--push=falsepara revisar antes do commit final.
A parte útil não é a ferramenta em si; é como o Claudiomiro persiste através de problemas complexos até a conclusão.
Instalação e Uso Básico
# Install globally
npm install -g claudiomiro
# Run with a complex prompt
claudiomiro --prompt="Your complex task description here"
# Or run interactively
claudiomiro
Pré-requisitos para Desempenho Ideal
Para o Claudiomiro funcionar bem, sua base de código deve ter linting e testes unitários configurados.
Por que o Linting é Importante
Linters fornecem feedback imediato sobre qualidade do código, violações de estilo e possíveis erros. Quando o Claudiomiro executa um linter (como ESLint, Prettier ou Pylint), ele recebe sinais claros sobre erros de sintaxe, violações de estilo, possíveis bugs, variáveis não utilizadas e problemas de importação.
Sem linting, o Claudiomiro pode escrever código que compila mas não segue as convenções do seu projeto.
Com linting, o Claudiomiro corrige automaticamente problemas de estilo e detecta erros cedo, garantindo que o código se integre à sua base de código existente.
Por que os Testes Unitários São Críticos
Os testes unitários são o ciclo de feedback do Claudiomiro. Eles informam à IA se a sua implementação realmente funciona:
- Testes passam: o Claudiomiro sabe que teve sucesso e avança.
- Testes falham: o Claudiomiro sabe que precisa corrigir problemas e volta ao início.
Sem testes, o Claudiomiro escreve código mas não tem como verificar se funciona corretamente. Ele pode pensar que terminou quando ainda existem bugs.
Com testes, o Claudiomiro executa a suíte de testes, vê as falhas, analisa os erros, corrige os problemas e re-executa os testes até que tudo passe.
O Loop Autônomo em Ação
Step 3: Implementation
↓
Claudiomiro writes code
↓
Runs tests
↓
Tests fail? → Analyzes errors → Fixes code → Runs tests again
↓
Tests pass? → Marks task complete → Moves to next task
↓
All tasks done? → Proceeds to Step 4
Esse loop pode ser executado múltiplas vezes automaticamente até que todos os testes passem. É isso que torna o Claudiomiro autônomo: ele não precisa que você diga "continue" ou "tente novamente."
Configuração Recomendada
Mínimo: linting básico e alguns testes unitários para funcionalidades principais.
Ideal: linting abrangente com regras estritas, alta cobertura de testes (>80%), testes de integração para caminhos críticos, hooks de pré-commit e MCPs configurados.
Exemplo package.json:
{
"scripts": {
"lint": "eslint . --fix",
"test": "jest --coverage",
"test:watch": "jest --watch"
}
}
O Claudiomiro descobrirá e usará esses scripts automaticamente.
Caso de Uso 1: Eliminando Código Duplicado em Múltiplos Módulos
O Cenário
Você tem um sistema de gestão financeira com módulos quase idênticos: Contas a Pagar (Formulário e Lista) e Contas a Receber (Formulário e Lista). O código é 95% idêntico. Toda vez que você muda um, precisa replicar manualmente a mudança no outro.
O Prompt
claudiomiro --prompt="
/Users/dev/project/frontend/src/modules/financial/bills/bills-to-pay-form
/Users/dev/project/frontend/src/modules/financial/bills/bills-to-pay-list
/Users/dev/project/frontend/src/modules/financial/bills/bills-to-receive-form
/Users/dev/project/frontend/src/modules/financial/bills/bills-to-receive-list
These are practically identical and will continue to be. The only difference is that
one is for accounts payable and the other for accounts receivable.
I want you to analyze each of them and unify as much as possible to avoid complexity.
Unify and componentize to share the maximum amount of code possible.
Normally, whenever I change something in accounts payable, I expect the same change
in accounts receivable. The structure is exactly the same. Only the backend table differs.
"
Como o Claudiomiro Pensa
Fase 1: Análise
Processo de Raciocínio do Claudiomiro:
💭 "I've been given 4 file paths. Let me first read all of them to understand
the full scope of duplication."
Reading:
- bills-to-pay-form (523 lines)
- bills-to-pay-list (612 lines)
- bills-to-receive-form (531 lines)
- bills-to-receive-list (618 lines)
💭 "Interesting patterns emerging:
1. Both forms have identical field structures:
- amount, date, description, category, payment_method
- Same validation rules (required fields, date format, amount > 0)
- Same form layout and styling
2. Both lists have identical features:
- Same table columns (date, description, amount, status, actions)
- Same filtering options (date range, status, search)
- Same pagination logic
- Same action buttons (edit, delete, view details)
3. Only differences:
- API endpoints: /api/bills-to-pay vs /api/bills-to-receive
- Page titles: 'Bills to Pay' vs 'Bills to Receive'
- Some status labels: 'Paid' vs 'Received'
4. Total duplication: ~2,200 lines of nearly identical code"
Prompt Aprimorado Gerado (PROMPT.md):
# Task: Unify Duplicated Bills Management Modules
## Problem Analysis
- 2,200+ lines of duplicated code across 4 files
- 95% code similarity between accounts payable and receivable
- High maintenance burden: changes must be replicated manually
- Risk of inconsistencies and bugs from incomplete synchronization
## Solution Strategy
Create a unified, configurable architecture:
1. **Shared Components**
- BillForm (configurable for pay/receive)
- BillList (configurable for pay/receive)
- BillFilters (common filtering logic)
- BillTableRow (common row rendering)
2. **Configuration-Based Approach**
- Single source of truth for business logic
- Type parameter distinguishes pay/receive
- Backend API routes dynamically constructed
3. **Benefits**
- Reduce codebase by ~1,800 lines
- Single place to make changes
- Eliminate synchronization bugs
- Easier testing and maintenance
## Technical Approach
- Create shared components in: modules/financial/bills/shared/
- Use TypeScript generics for type safety
- Implement hooks for shared business logic
- Comprehensive tests for both configurations
Fase 2: Pesquisa
Processo de Pesquisa do Claudiomiro:
💭 "Let me research the codebase patterns and best practices..."
Analyzing project structure:
✓ Found: React with TypeScript
✓ Found: React Hook Form for form management
✓ Found: React Query for API calls
✓ Found: Existing shared components in /shared folder
✓ Found: Theme system with consistent styling
Researching similar patterns in codebase:
✓ Found: /modules/inventory - uses similar shared component pattern
✓ Found: /modules/customers - good example of type-based configuration
Context7 research:
✓ React Hook Form best practices for dynamic forms
✓ TypeScript discriminated unions for type safety
✓ React Query configuration patterns
💭 "I have enough information to create a robust, maintainable solution."
TODO.md Gerado:
Fully implemented: NO
## Analysis Complete
- Total code to unify: 2,264 lines
- Duplication percentage: 94.8%
- Estimated reduction: 1,847 lines (~82%)
## Implementation Tasks
### Phase 1: Create Shared Types & Configuration
- [ ] Create BillType enum ('payable' | 'receivable')
- [ ] Create BillConfig interface for configuration
- [ ] Create shared type definitions
- [ ] Create API endpoint resolver utility
### Phase 2: Extract Shared Business Logic
- [ ] Create useBillForm hook (shared form logic)
- [ ] Create useBillList hook (shared list logic)
- [ ] Create useBillFilters hook (shared filtering)
- [ ] Create useBillAPI hook (dynamic API calls)
### Phase 3: Build Shared Components
- [ ] Create BillForm component (configurable)
- [ ] Create BillList component (configurable)
- [ ] Create BillFilters component (shared)
- [ ] Create BillTableRow component (shared)
- [ ] Create BillStatusBadge component (shared)
- [ ] Create BillActions component (shared)
### Phase 4: Create Entry Point Components
- [ ] Create BillsToPayPage (thin wrapper)
- [ ] Create BillsToReceivePage (thin wrapper)
- [ ] Update routing configuration
### Phase 5: Migration & Cleanup
- [ ] Migrate all existing functionality to shared components
- [ ] Verify feature parity
- [ ] Remove old duplicated files
- [ ] Update imports across codebase
### Phase 6: Testing
- [ ] Unit tests for all shared hooks
- [ ] Component tests for shared components
- [ ] Integration tests for both bill types
- [ ] E2E tests for complete workflows
- [ ] Test edge cases and error handling
### Phase 7: Documentation
- [ ] Add JSDoc comments to shared components
- [ ] Update README with new architecture
- [ ] Create migration guide for future similar modules
Fase 3: Implementação
Raciocínio de Implementação do Claudiomiro:
💭 "Starting with the foundation - types and configuration..."
Creating: modules/financial/bills/shared/types.ts
Rationale: Type safety is crucial for this refactoring. Strong types will catch
configuration errors at compile time.
O que o Claudiomiro Cria:
// modules/financial/bills/shared/types.ts
export enum BillType {
PAYABLE = 'payable',
RECEIVABLE = 'receivable'
}
export interface BillConfig {
type: BillType;
title: string;
endpoint: string;
statusLabels: {
pending: string;
completed: string;
cancelled: string;
};
actionLabels: {
create: string;
edit: string;
delete: string;
markComplete: string;
};
}
export const BILL_CONFIGS: Record<BillType, BillConfig> = {
[BillType.PAYABLE]: {
type: BillType.PAYABLE,
title: 'Bills to Pay',
endpoint: '/api/bills-to-pay',
statusLabels: {
pending: 'Pending Payment',
completed: 'Paid',
cancelled: 'Cancelled'
},
actionLabels: {
create: 'Add Bill to Pay',
edit: 'Edit Bill',
delete: 'Delete Bill',
markComplete: 'Mark as Paid'
}
},
[BillType.RECEIVABLE]: {
type: BillType.RECEIVABLE,
title: 'Bills to Receive',
endpoint: '/api/bills-to-receive',
statusLabels: {
pending: 'Pending Receipt',
completed: 'Received',
cancelled: 'Cancelled'
},
actionLabels: {
create: 'Add Bill to Receive',
edit: 'Edit Bill',
delete: 'Delete Bill',
markComplete: 'Mark as Received'
}
}
};
💭 "Now the shared form logic. This was duplicated in both forms with 500+ lines each.
I'll extract all common logic into a reusable hook."
Creating: modules/financial/bills/shared/hooks/useBillForm.ts
Rationale: React Hook Form logic was 98% identical. This hook will handle all form
state, validation, and submission logic for both bill types.
// modules/financial/bills/shared/hooks/useBillForm.ts
export const useBillForm = (config: BillConfig, billId?: string) => {
const { control, handleSubmit, formState: { errors } } = useForm<BillFormData>({
resolver: zodResolver(billFormSchema),
defaultValues: {
amount: 0,
date: new Date(),
description: '',
category: '',
paymentMethod: ''
}
});
// Fetch existing bill if editing
const { data: existingBill, isLoading } = useQuery(
['bill', config.type, billId],
() => billId ? fetchBill(config.endpoint, billId) : null,
{ enabled: !!billId }
);
// Save mutation
const saveMutation = useMutation(
(data: BillFormData) => saveBill(config.endpoint, billId, data),
{
onSuccess: () => {
toast.success(`Bill ${billId ? 'updated' : 'created'} successfully`);
queryClient.invalidateQueries(['bills', config.type]);
}
}
);
const onSubmit = handleSubmit((data) => saveMutation.mutate(data));
return {
control,
errors,
isLoading,
existingBill,
onSubmit,
isSaving: saveMutation.isLoading
};
};
💭 "The list component had complex filtering, pagination, and action handling.
All of it was duplicated. Let me extract that into a hook."
Creating: modules/financial/bills/shared/hooks/useBillList.ts
Rationale: 600+ lines of list logic in each file. This consolidates filtering,
sorting, pagination, and actions into one reusable hook.
// modules/financial/bills/shared/hooks/useBillList.ts
export const useBillList = (config: BillConfig) => {
const [filters, setFilters] = useState<BillFilters>({
search: '',
status: 'all',
dateFrom: null,
dateTo: null
});
const [pagination, setPagination] = useState({ page: 1, pageSize: 20 });
// Fetch bills with filters
const { data, isLoading, refetch } = useQuery(
['bills', config.type, filters, pagination],
() => fetchBills(config.endpoint, filters, pagination)
);
// Delete mutation
const deleteMutation = useMutation(
(billId: string) => deleteBill(config.endpoint, billId),
{
onSuccess: () => {
toast.success('Bill deleted successfully');
refetch();
}
}
);
// Mark as complete mutation
const completeMutation = useMutation(
(billId: string) => markComplete(config.endpoint, billId),
{
onSuccess: () => {
toast.success(config.statusLabels.completed);
refetch();
}
}
);
return {
bills: data?.bills || [],
totalCount: data?.totalCount || 0,
isLoading,
filters,
setFilters,
pagination,
setPagination,
handleDelete: deleteMutation.mutate,
handleComplete: completeMutation.mutate,
config
};
};
💭 "Now the UI components. They can be thin wrappers around the hooks."
Creating: modules/financial/bills/shared/components/BillForm.tsx
Rationale: Generic form component that works for both bill types through configuration.
// modules/financial/bills/shared/components/BillForm.tsx
interface BillFormProps {
config: BillConfig;
billId?: string;
onSuccess?: () => void;
}
export const BillForm: React.FC<BillFormProps> = ({ config, billId, onSuccess }) => {
const { control, errors, isLoading, onSubmit, isSaving } = useBillForm(config, billId);
if (isLoading) return <LoadingSpinner />;
return (
<form onSubmit={onSubmit}>
<FormField
name="amount"
control={control}
label="Amount"
type="currency"
error={errors.amount}
/>
<FormField
name="date"
control={control}
label="Date"
type="date"
error={errors.date}
/>
<FormField
name="description"
control={control}
label="Description"
type="textarea"
error={errors.description}
/>
<FormField
name="category"
control={control}
label="Category"
type="select"
options={CATEGORIES}
error={errors.category}
/>
<FormField
name="paymentMethod"
control={control}
label="Payment Method"
type="select"
options={PAYMENT_METHODS}
error={errors.paymentMethod}
/>
<FormActions>
<Button type="submit" loading={isSaving}>
{billId ? 'Update' : config.actionLabels.create}
</Button>
<Button variant="secondary" onClick={onSuccess}>
Cancel
</Button>
</FormActions>
</form>
);
};
💭 "The list component follows the same pattern."
Creating: modules/financial/bills/shared/components/BillList.tsx
// modules/financial/bills/shared/components/BillList.tsx
interface BillListProps {
config: BillConfig;
}
export const BillList: React.FC<BillListProps> = ({ config }) => {
const {
bills,
totalCount,
isLoading,
filters,
setFilters,
pagination,
setPagination,
handleDelete,
handleComplete
} = useBillList(config);
return (
<div>
<PageHeader>
<h1>{config.title}</h1>
<Button onClick={() => navigate(`/bills/${config.type}/new`)}>
{config.actionLabels.create}
</Button>
</PageHeader>
<BillFilters filters={filters} onChange={setFilters} />
<Table>
<TableHeader>
<TableRow>
<TableHead>Date</TableHead>
<TableHead>Description</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bills.map(bill => (
<BillTableRow
key={bill.id}
bill={bill}
config={config}
onDelete={handleDelete}
onComplete={handleComplete}
/>
))}
</TableBody>
</Table>
<Pagination
currentPage={pagination.page}
pageSize={pagination.pageSize}
totalCount={totalCount}
onPageChange={(page) => setPagination({ ...pagination, page })}
/>
</div>
);
};
💭 "Finally, the entry points become incredibly simple - just configuration wrappers."
Creating: modules/financial/bills/BillsToPayPage.tsx
Creating: modules/financial/bills/BillsToReceivePage.tsx
Rationale: These go from 600+ lines each to ~10 lines each.
// modules/financial/bills/BillsToPayPage.tsx
export const BillsToPayPage: React.FC = () => {
return <BillList config={BILL_CONFIGS[BillType.PAYABLE]} />;
};
// modules/financial/bills/BillsToReceivePage.tsx
export const BillsToReceivePage: React.FC = () => {
return <BillList config={BILL_CONFIGS[BillType.RECEIVABLE]} />;
};
💭 "Now updating TODO.md to track progress..."
Updating: TODO.md
Status: Fully implemented: YES
Fase 4: Testes
Estratégia de Testes do Claudiomiro:
💭 "I need comprehensive tests to ensure both bill types work identically."
Running: npm test
Creating tests:
✓ useBillForm.test.ts - Tests hook with both configurations
✓ useBillList.test.ts - Tests filtering, pagination, actions
✓ BillForm.test.tsx - Tests form rendering and validation
✓ BillList.test.tsx - Tests list rendering and interactions
✓ integration.test.tsx - Tests complete workflows for both types
Test Results:
✅ 45 tests passed
Coverage:
- Statements: 98.7%
- Branches: 96.2%
- Functions: 100%
- Lines: 98.5%
💭 "All tests passing. Let me verify both configurations work identically..."
Running manual verification:
✓ Bills to Pay form works correctly
✓ Bills to Receive form works correctly
✓ Both lists display properly
✓ Filtering works on both
✓ Actions (edit, delete, complete) work on both
✓ Pagination works on both
💭 "Perfect. Creating GITHUB_PR.md..."
Descrição do Pull Request Gerada (GITHUB_PR.md):
## Summary
Unified duplicated Bills management modules by extracting shared logic into configurable components.
## Problem
- 2,264 lines of duplicated code across Bills to Pay and Bills to Receive
- Manual synchronization of changes between modules
- High risk of inconsistencies and bugs
## Solution
Created a configuration-based architecture with shared components:
- Single source of truth for business logic
- Type parameter distinguishes payable vs receivable
- All common logic extracted into reusable hooks and components
## Changes Made
### New Shared Architecture
- ✅ Created `shared/types.ts` - Configuration system
- ✅ Created `shared/hooks/useBillForm.ts` - Unified form logic
- ✅ Created `shared/hooks/useBillList.ts` - Unified list logic
- ✅ Created `shared/components/BillForm.tsx` - Generic form component
- ✅ Created `shared/components/BillList.tsx` - Generic list component
- ✅ Created `shared/components/BillTableRow.tsx` - Shared row rendering
- ✅ Created `shared/components/BillFilters.tsx` - Shared filtering
- ✅ Created `shared/components/BillStatusBadge.tsx` - Shared status display
### Simplified Entry Points
- ✅ Refactored `BillsToPayPage.tsx` - From 612 lines to 8 lines
- ✅ Refactored `BillsToReceivePage.tsx` - From 618 lines to 8 lines
- ✅ Refactored `BillsToPayForm.tsx` - From 523 lines to 8 lines
- ✅ Refactored `BillsToReceiveForm.tsx` - From 531 lines to 8 lines
### Testing
- ✅ 45 comprehensive tests (unit + integration)
- ✅ 98.7% code coverage
- ✅ Both bill types tested identically
## Impact
### Code Reduction
- Before: 2,264 lines
- After: 417 lines
- Reduction: 1,847 lines (81.6%)
### Maintenance Benefits
- Changes now made in ONE place instead of FOUR
- Zero risk of synchronization bugs
- Easier to add new features
- Simpler to understand and onboard new developers
### Future Extensibility
This pattern can be applied to other similar modules:
- Invoices (issued vs received)
- Orders (purchase vs sales)
- Contracts (customer vs supplier)
## Migration Required
None - All functionality preserved, architecture improved
## Breaking Changes
None - All public APIs remain unchanged
## Testing
All tests passing: ✅
- Unit tests: 32 passed
- Integration tests: 13 passed
- Coverage: 98.7%
Fase 5: Commit & Push
💭 "Creating meaningful commit message from the work done..."
git add .
git commit -m "refactor: unify bills management modules into shared architecture
- Extracted 1,847 lines of duplicated code into shared components
- Created configuration-based system for payable/receivable bills
- Reduced codebase complexity by 81.6%
- Maintained 100% feature parity with comprehensive tests
- Simplified future maintenance with single source of truth"
git push origin feature/unify-bills-modules
✓ Commit created and pushed successfully
O Resultado
Antes do Claudiomiro: 4 arquivos separados com 2.264 linhas de código duplicado. Cada mudança exigia sincronização manual. Alto risco de bugs por atualizações incompletas.
Após o Claudiomiro: arquitetura compartilhada com 417 linhas de código reutilizável. Abordagem baseada em configuração. Redução de 81,6% no código. Zero duplicação. Cobertura de testes abrangente. Tempo total: 12 minutos.
Caso de Uso 2: Implementando uma Funcionalidade Complexa de Múltiplas Etapas
O Cenário
Você precisa construir um fluxo completo de onboarding de usuários com múltiplas etapas, processamento no backend, notificações por e-mail e rastreamento de analytics.
O Prompt
claudiomiro --prompt="
Create a comprehensive user onboarding system:
1. Multi-step wizard (5 steps):
- Step 1: Basic profile (name, email, password)
- Step 2: Company information (name, size, industry)
- Step 3: Team setup (invite team members)
- Step 4: Integrations (connect external services)
- Step 5: Preferences (notifications, timezone, language)
2. Backend requirements:
- Create user record with email verification
- Send welcome email
- Process team invitations (send emails)
- Set up integrations via OAuth
- Create analytics events for each step
- Save progress (allow resume later)
3. Frontend requirements:
- Beautiful step indicator
- Form validation with real-time feedback
- Save & continue later functionality
- Progress bar
- Congratulations screen on completion
- Mobile responsive
4. Testing:
- Full test coverage for all steps
- Test email sending (mocked)
- Test OAuth flows (mocked)
- Test progress saving/resuming
"
Como o Claudiomiro Aborda Isso
Etapa 1: Análise e Planejamento
💭 "This is a complex feature with multiple interconnected parts. Let me break it down..."
Analyzing requirements:
- Frontend: Multi-step wizard (complex state management)
- Backend: 7 new API endpoints
- Database: 3 new tables (users, invitations, onboarding_progress)
- External integrations: Email service, OAuth providers
- Testing: ~50 tests needed
Creating PROMPT.md with enhanced breakdown...
Creating TODO.md with 47 specific tasks...
TODO.md Gerado (trecho):
Fully implemented: NO
## Architecture Decisions
- Use React Context for wizard state management
- Zustand for step progress persistence
- React Hook Form for each step's validation
- React Query for API calls
- Backend: Node.js + Express + PostgreSQL
- Email: Nodemailer with template system
- OAuth: Passport.js
## Implementation Plan
### Phase 1: Database & Migrations (6 tasks)
- [ ] Create users table migration
- [ ] Create onboarding_progress table migration
- [ ] Create team_invitations table migration
- [ ] Add OAuth tokens table
- [ ] Create database indexes for performance
- [ ] Create database seed data for development
### Phase 2: Backend API (12 tasks)
- [ ] POST /api/onboarding/step1 - Save basic profile
- [ ] POST /api/onboarding/step2 - Save company info
- [ ] POST /api/onboarding/step3 - Send team invitations
- [ ] GET /api/onboarding/integrations - List available integrations
- [ ] POST /api/onboarding/step4 - Connect integration
- [ ] POST /api/onboarding/step5 - Save preferences
- [ ] GET /api/onboarding/progress - Get current progress
- [ ] POST /api/onboarding/complete - Mark onboarding complete
- [ ] Email service - Welcome email template
- [ ] Email service - Team invitation template
- [ ] OAuth service - Google integration
- [ ] OAuth service - Slack integration
### Phase 3: Frontend Components (15 tasks)
- [ ] OnboardingProvider (Context)
- [ ] useOnboarding hook
- [ ] StepIndicator component
- [ ] ProgressBar component
- [ ] Step1BasicProfile component
- [ ] Step2CompanyInfo component
- [ ] Step3TeamSetup component
- [ ] Step4Integrations component
- [ ] Step5Preferences component
- [ ] OnboardingComplete component
- [ ] SaveProgressButton component
- [ ] NavigationButtons component
- [ ] FormField components
- [ ] Validation schemas (Zod)
- [ ] Mobile responsive styling
### Phase 4: Testing (14 tasks)
- [ ] Unit tests: OnboardingProvider
- [ ] Unit tests: useOnboarding hook
- [ ] Unit tests: All 5 step components
- [ ] Unit tests: Backend API endpoints
- [ ] Integration tests: Complete flow
- [ ] Email mocking tests
- [ ] OAuth flow tests (mocked)
- [ ] Progress save/resume tests
- [ ] Validation tests
- [ ] Mobile responsiveness tests
Etapa 2: Pesquisa
💭 "Let me research best practices and existing patterns in this codebase..."
Researching via Context7:
✓ React Context patterns for complex state
✓ Multi-step form best practices
✓ OAuth implementation guides
✓ Email template best practices
Analyzing existing codebase:
✓ Found existing email service - can extend it
✓ Found auth system - can integrate OAuth there
✓ Found design system - consistent UI components
✓ Found analytics service - can add tracking events
Updating TODO.md with refined approach...
Etapa 3: Implementação
O Claudiomiro constrói sistematicamente: migrações de banco de dados, serviços de backend (e-mail, OAuth), endpoints de API com validação, estado do frontend (Context provider, hooks), componentes de UI para todas as 5 etapas, estilização responsiva para mobile e integração conectando todas as partes.
Etapa 4: Testes
Running all tests...
Backend Tests:
✅ User creation and email verification - 6 tests passed
✅ Onboarding progress save/load - 4 tests passed
✅ Team invitation emails - 5 tests passed
✅ OAuth integration flow - 8 tests passed
✅ Preferences saving - 3 tests passed
✅ API validation - 12 tests passed
Frontend Tests:
✅ OnboardingProvider state management - 8 tests passed
✅ Step components rendering - 15 tests passed
✅ Form validation - 18 tests passed
✅ Navigation between steps - 6 tests passed
✅ Progress save/resume - 5 tests passed
✅ Mobile responsive behavior - 4 tests passed
Integration Tests:
✅ Complete onboarding flow - 8 tests passed
✅ Resume interrupted onboarding - 3 tests passed
Total: 105 tests passed ✅
Coverage: 97.3%
Etapa 5: Documentação e Commit
Creating comprehensive PR description...
git commit -m "feat: implement complete user onboarding system
- Multi-step wizard with 5 steps and progress tracking
- Backend API with 8 endpoints
- Email notifications for welcome and team invitations
- OAuth integrations (Google, Slack)
- Save & resume functionality
- Mobile responsive design
- 105 comprehensive tests with 97.3% coverage"
git push origin feature/user-onboarding
✓ Complete onboarding system ready for review
O Resultado
O que o Claudiomiro construiu em 25 minutos: 3 migrações de banco de dados, 8 endpoints de API backend, um sistema de templates de e-mail, um framework de integração OAuth, 12 componentes React, um sistema completo de gerenciamento de estado, UI responsiva para mobile, 105 testes abrangentes e documentação completa. Estimativa manual para o mesmo trabalho: 3 a 5 dias.
Caso de Uso 3: Refatoração em Larga Escala em Múltiplas Camadas
O Cenário
Sua aplicação usa autenticação baseada em sessão. Você precisa refatorar para JWT em toda a stack: mais de 25 rotas protegidas e mais de 15 endpoints de API.
O Prompt
claudiomiro --prompt="
Refactor authentication from session-based to JWT tokens:
Current state:
- Backend uses Express sessions with Redis
- Frontend stores session cookie
- 25+ protected routes
- 15+ API endpoints check session
- User context relies on session data
Target state:
- JWT tokens (access + refresh)
- Secure httpOnly cookies for refresh tokens
- Access token in memory
- All endpoints validate JWT
- Frontend automatically refreshes tokens
- Logout blacklists tokens
- Maintain all existing functionality
Important:
- Zero downtime migration
- Backward compatible during transition
- Comprehensive tests
- Update all 25+ routes
- Update all 15+ API endpoints
"
Como o Claudiomiro Lida com Isso
Fase de Análise:
💭 "This is a large-scale refactoring touching multiple layers. Let me map out everything..."
Scanning codebase for authentication usage:
Found 127 files using authentication:
- 25 protected routes
- 15 API endpoints with auth middleware
- 8 frontend components using user context
- 12 services making authenticated requests
- Backend session configuration in 3 files
- Redis session store
- Logout functionality in 5 places
💭 "I need a phased migration strategy to avoid breaking anything..."
Creating migration strategy:
Phase 1: Add JWT alongside sessions (both work)
Phase 2: Update backend to accept both
Phase 3: Update frontend to use JWT
Phase 4: Remove session code
This ensures zero downtime and allows rollback at any point.
Estratégia de Implementação:
## Migration Plan
### Phase 1: Foundation
1. Install JWT libraries
2. Create JWT service (generate, verify, refresh)
3. Create token blacklist (Redis)
4. Add JWT middleware (parallel to session)
5. Update login endpoint to return both session + JWT
### Phase 2: Backend Migration
6. Update all 15 API endpoints to accept JWT OR session
7. Add refresh token endpoint
8. Add token blacklist to logout
9. Tests for JWT flow
### Phase 3: Frontend Migration
10. Create token management service
11. Update auth context to use JWT
12. Add token refresh interceptor
13. Update all API calls to include JWT
14. Update logout to clear tokens
15. Tests for new auth flow
### Phase 4: Cleanup
16. Remove session code from backend
17. Remove Redis session store
18. Remove session cookies from frontend
19. Update documentation
Execução:
O Claudiomiro cria o serviço JWT, adiciona refresh de token, atualiza cada um dos 15 endpoints, atualiza o contexto de autenticação do frontend, atualiza cada uma das 25 rotas, adiciona testes abrangentes, remove o código de sessão antigo e verifica que tudo ainda funciona.
Resultados dos Testes:
Running comprehensive test suite...
✅ JWT generation and validation - 12 tests
✅ Token refresh mechanism - 8 tests
✅ Token blacklist on logout - 4 tests
✅ All 15 API endpoints accept JWT - 30 tests
✅ All 25 frontend routes protected - 25 tests
✅ Auth context state management - 15 tests
✅ Automatic token refresh - 8 tests
✅ Logout clears all tokens - 6 tests
✅ Expired token handling - 10 tests
✅ Invalid token handling - 8 tests
Total: 126 tests passed ✅
No breaking changes detected ✅
O Resultado
127 arquivos atualizados. Sistema de autenticação completo substituído. Migração sem downtime. Toda a funcionalidade preservada. Segurança melhorada. Tempo: 35 minutos. Estimativa manual: 2 semanas.
Caso de Uso 4: Investigação e Correção de Bug Complexo
O Cenário
Usuários relatam corrupção intermitente de dados em um sistema de cálculo financeiro. O bug ocorre apenas sob condições específicas.
O Prompt
claudiomiro --prompt="
Investigate and fix bug:
User reports: 'Transaction totals are sometimes incorrect'
Symptoms:
- Happens randomly (can't reproduce consistently)
- Only on transactions with multiple line items
- More likely during high traffic
- Database shows correct data, but API returns wrong totals
Additional context:
- Financial calculation service: backend/services/FinancialService.js
- Transaction API: backend/routes/transactions.js
- Frontend displays: frontend/components/TransactionSummary.tsx
Requirements:
- Find root cause
- Fix the bug
- Add tests to prevent regression
- Add logging for future debugging
"
Como o Claudiomiro Investiga
Fase de Investigação:
💭 "Random bugs are usually race conditions or caching issues. Let me investigate..."
Reading: backend/services/FinancialService.js
Found suspicious code:
```javascript
let runningTotal = 0; // ⚠️ Global variable!
function calculateTotal(lineItems) {
runningTotal = 0; // Reset
for (const item of lineItems) {
runningTotal += item.amount;
}
return runningTotal;
}
💭 "There's the bug! Global variable in a concurrent environment."
Analysis:
- Global 'runningTotal' is shared across all requests
- Under concurrent requests: Request A: runningTotal = 0 Request B: runningTotal = 0 Request A: runningTotal = 100 Request B: runningTotal = 50 // Overwrites! Request A: returns 50 // Wrong! Request B: returns 50 // Wrong!
This explains:
- Why it's random (depends on request timing)
- Why it's more common during high traffic
- Why database is correct (bug is in calculation, not storage)
💭 "Let me check if this pattern exists elsewhere..."
Scanning codebase for similar patterns: ⚠️ Found in: DiscountService.js (similar global variable) ⚠️ Found in: TaxCalculator.js (similar global variable) ✓ No issues in: PaymentProcessor.js
💭 "Three files to fix. Let me create a comprehensive solution..."
**Projeto da Solução:**
```markdown
## Root Cause
Global variables in calculation functions cause race conditions under concurrent requests.
## Fix Strategy
1. Remove all global variables
2. Use pure functions (local variables only)
3. Add concurrency tests
4. Add logging for calculation tracking
5. Apply fix to all affected services
## Affected Files
- backend/services/FinancialService.js
- backend/services/DiscountService.js
- backend/services/TaxCalculator.js
Implementação:
// BEFORE (buggy code):
let runningTotal = 0;
function calculateTotal(lineItems) {
runningTotal = 0;
for (const item of lineItems) {
runningTotal += item.amount;
}
return runningTotal;
}
// AFTER (fixed code):
function calculateTotal(lineItems) {
// Local variable - safe for concurrent requests
let runningTotal = 0;
for (const item of lineItems) {
runningTotal += item.amount;
}
// Add logging for debugging
logger.debug('Transaction total calculated', {
lineItemCount: lineItems.length,
total: runningTotal,
timestamp: Date.now()
});
return runningTotal;
}
Testes Criados:
// Concurrency test to prevent regression
describe('FinancialService - Concurrency Safety', () => {
it('should handle concurrent calculations correctly', async () => {
// Simulate 100 concurrent requests
const promises = [];
for (let i = 0; i < 100; i++) {
const lineItems = [
{ amount: 10 * i },
{ amount: 20 * i },
{ amount: 30 * i }
];
promises.push(FinancialService.calculateTotal(lineItems));
}
const results = await Promise.all(promises);
// Verify each result is correct (no interference)
results.forEach((total, i) => {
expect(total).toBe(60 * i);
});
});
it('should log calculation details', () => {
const lineItems = [{ amount: 100 }, { amount: 200 }];
FinancialService.calculateTotal(lineItems);
expect(logger.debug).toHaveBeenCalledWith(
'Transaction total calculated',
expect.objectContaining({
lineItemCount: 2,
total: 300
})
);
});
});
O Resultado
Causa raiz encontrada em 3 arquivos. Todas as condições de corrida eliminadas. Testes de concorrência adicionados. Log adicionado para depuração futura. Tempo: 8 minutos.
Principais Conclusões
O que Torna o Claudiomiro Diferente
- Ele analisa e entende o problema antes de escrever código.
- Toma decisões arquiteturais baseadas nos padrões da base de código, não em templates genéricos.
- Lida com funcionalidades inteiras, não apenas trechos.
- Nunca pula os testes.
- O código chega totalmente testado e documentado.
Quando Usar o Claudiomiro
Bom para: eliminar duplicação de código, implementar funcionalidades completas, refatorações em larga escala, investigações de bugs complexos, migração de tecnologias e adição de cobertura de testes abrangente.
Menos adequado para: experimentos rápidos, exercícios de aprendizado, tarefas altamente ambíguas e decisões que requerem julgamento humano.
Melhores Práticas
Escreva prompts melhores incluindo caminhos de arquivo, descrevendo o estado atual e desejado, mencionando restrições específicas e referenciando padrões similares na sua base de código.
Deixe o Claudiomiro completar todas as 5 etapas sem interrupção. Revise o TODO.md gerado cedo. Use --push=false para revisar antes de enviar.
Use o Claudiomiro para trabalhos grandes e demorados: refatorações repetitivas, melhorias de cobertura de testes, mudanças arquiteturais.
Conclusão
O Claudiomiro converte a assistência de IA de chat interativo em desenvolvimento autônomo. Seguindo um fluxo de trabalho estruturado e tomando decisões inteligentes, ele lida com tarefas complexas de desenvolvimento que levariam dias em minutos.
Os números dos exemplos: redução de 81,6% no código na eliminação de duplicações, 95% de economia de tempo na implementação de funcionalidades, 98% de economia de tempo em grandes refatorações e correções de bugs críticos com prevenção de regressão integrada.
O objetivo não é substituir desenvolvedores. É eliminar o trabalho tedioso e demorado para que você possa se concentrar em arquitetura e resolução de problemas.
Comece Agora:
npm install -g claudiomiro
claudiomiro --prompt="Your complex task here"