Imagina a Claude Code ejecutándose 100% de forma autónoma durante horas, codificando y revisando su propio código hasta que todo esté completamente terminado.
¡Esto es Claudiomiro! https://github.com/samuelfaj/claudiomiro
El Problema con Claude Code
Al usar Claude Code directamente para tareas complejas, probablemente hayas notado que se detiene antes de completar el trabajo. Esto ocurre por buenas razones:
- Economía de tokens: Claude Code intenta conservar tokens deteniéndose después de una cantidad razonable de trabajo.
- Limitaciones de alcance: asume que quieres revisar el progreso antes de continuar.
- Gestión del contexto: las tareas largas pueden agotar las ventanas de contexto.
¿El resultado? Te encuentras escribiendo "continue" una y otra vez, gestionando el flujo de trabajo manualmente.
¿Qué es Claudiomiro?
Claudiomiro es una aplicación CLI de Node.js que envuelve Claude AI en un flujo de trabajo estructurado y autónomo. No solo responde preguntas o genera código; completa funcionalidades y refactorizaciones enteras siguiendo un proceso disciplinado de 5 pasos:
- Inicialización: analiza la tarea, crea una rama git, mejora el prompt.
- Investigación: investiga en profundidad la base de código y la documentación relevante.
- Implementación: se ejecuta múltiples veces, escribiendo todo el código, tests y documentación.
- Pruebas: ejecuta todos los tests, corrige fallos, valida que todo funciona.
- Commit & Push: crea commits significativos y los sube al repositorio.
La Solución Claudiomiro: Bucle Autónomo
Así es como funciona:
El Mecanismo de Bucle
┌─────────────────────────────────────────────────────────────┐
│ 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 │
│ │
└─────────────────────────────────────────────────────────────┘
Ejemplo de Bucle Autónomo
Esto es lo que ocurre cuando ejecutas una tarea compleja:
$ 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 Seguridad
- Máximo de 15 ciclos para evitar la ejecución infinita.
- La validación del archivo de estado garantiza que el progreso se está produciendo realmente.
- La detección de errores detiene la ejecución si el mismo error ocurre repetidamente.
- Usa
--push=falsepara revisar antes del commit final.
La parte útil no es la herramienta en sí; es cómo Claudiomiro persiste a través de problemas complejos hasta completarlos.
Instalación y 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
Requisitos Previos para un Rendimiento Óptimo
Para que Claudiomiro funcione bien, tu base de código debe tener linting y tests unitarios configurados.
Por qué el Linting es Importante
Los linters proporcionan retroalimentación inmediata sobre la calidad del código, violaciones de estilo y posibles errores. Cuando Claudiomiro ejecuta un linter (como ESLint, Prettier o Pylint), recibe señales claras sobre errores de sintaxis, violaciones de estilo, posibles bugs, variables no utilizadas y problemas de importación.
Sin linting, Claudiomiro puede escribir código que compila pero no sigue las convenciones de tu proyecto.
Con linting, Claudiomiro corrige automáticamente los problemas de estilo y detecta errores de forma temprana, asegurando que el código se integre con tu base de código existente.
Por qué los Tests Unitarios Son Críticos
Los tests unitarios son el ciclo de retroalimentación de Claudiomiro. Le indican a la IA si su implementación funciona realmente:
- Los tests pasan: Claudiomiro sabe que tuvo éxito y avanza.
- Los tests fallan: Claudiomiro sabe que necesita corregir problemas y vuelve al inicio.
Sin tests, Claudiomiro escribe código pero no tiene forma de verificar si funciona correctamente. Puede pensar que ha terminado cuando aún existen bugs.
Con tests, Claudiomiro ejecuta la suite de tests, observa los fallos, analiza los errores, corrige los problemas y vuelve a ejecutar los tests hasta que todo pase.
El Bucle Autónomo en Acción
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
Este bucle puede ejecutarse múltiples veces automáticamente hasta que todos los tests pasen. Eso es lo que hace autónomo a Claudiomiro: no necesita que le digas "continue" o "inténtalo de nuevo."
Configuración Recomendada
Mínimo: linting básico y algunos tests unitarios para la funcionalidad principal.
Óptimo: linting exhaustivo con reglas estrictas, alta cobertura de tests (>80%), tests de integración para rutas críticas, hooks de pre-commit y MCPs configurados.
Ejemplo package.json:
{
"scripts": {
"lint": "eslint . --fix",
"test": "jest --coverage",
"test:watch": "jest --watch"
}
}
Claudiomiro descubrirá y usará estos scripts automáticamente.
Caso de Uso 1: Eliminando Código Duplicado en Múltiples Módulos
El Escenario
Tienes un sistema de gestión financiera con módulos casi idénticos: Facturas a Pagar (Formulario y Lista) y Facturas a Cobrar (Formulario y Lista). El código es un 95% idéntico. Cada vez que cambias uno, debes replicar manualmente el cambio en el otro.
El 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.
"
Cómo Piensa Claudiomiro
Paso 1: Fase de Análisis
Proceso de Razonamiento de 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 Mejorado Generado (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
Paso 2: Fase de Investigación
Proceso de Investigación de 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 Generado:
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
Paso 3: Implementación
Razonamiento de Implementación de 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.
Lo que Claudiomiro Crea:
// 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
Paso 4: Pruebas
Estrategia de Pruebas de 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..."
Descripción del Pull Request Generada (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%
Paso 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
El Resultado
Antes de Claudiomiro: 4 archivos separados con 2.264 líneas de código duplicado. Cada cambio requería sincronización manual. Alto riesgo de bugs por actualizaciones incompletas.
Después de Claudiomiro: arquitectura compartida con 417 líneas de código reutilizable. Enfoque basado en configuración. Reducción del 81,6% en el código. Cero duplicación. Cobertura de tests exhaustiva. Tiempo total: 12 minutos.
Caso de Uso 2: Implementando una Funcionalidad Compleja de Múltiples Pasos
El Escenario
Necesitas construir un flujo completo de onboarding de usuarios con múltiples pasos, procesamiento en el backend, notificaciones por correo electrónico y seguimiento de analytics.
El 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
"
Cómo Aborda Esto Claudiomiro
Paso 1: Análisis y Planificación
💭 "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 Generado (extracto):
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
Paso 2: Investigación
💭 "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...
Paso 3: Implementación
Claudiomiro construye sistemáticamente: migraciones de base de datos, servicios de backend (correo electrónico, OAuth), endpoints de API con validación, estado del frontend (Context provider, hooks), componentes de UI para los 5 pasos, estilos responsivos para móvil e integración conectando todas las piezas.
Paso 4: Pruebas
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%
Paso 5: Documentación y 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
El Resultado
Lo que Claudiomiro construyó en 25 minutos: 3 migraciones de base de datos, 8 endpoints de API backend, un sistema de plantillas de correo electrónico, un framework de integración OAuth, 12 componentes React, un sistema completo de gestión de estado, UI responsiva para móvil, 105 tests exhaustivos y documentación completa. Estimación manual para el mismo trabajo: 3 a 5 días.
Caso de Uso 3: Refactorización a Gran Escala en Múltiples Capas
El Escenario
Tu aplicación usa autenticación basada en sesión. Necesitas refactorizar a JWT en toda la stack: más de 25 rutas protegidas y más de 15 endpoints de API.
El 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
"
Cómo Maneja Esto Claudiomiro
Fase de Análisis:
💭 "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.
Estrategia de Implementación:
## 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
Ejecución:
Claudiomiro crea el servicio JWT, añade el refresco de tokens, actualiza cada uno de los 15 endpoints, actualiza el contexto de autenticación del frontend, actualiza cada una de las 25 rutas, añade tests exhaustivos, elimina el código de sesión antiguo y verifica que todo sigue funcionando.
Resultados de las Pruebas:
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 ✅
El Resultado
127 archivos actualizados. Sistema de autenticación completo reemplazado. Migración sin tiempo de inactividad. Toda la funcionalidad preservada. Seguridad mejorada. Tiempo: 35 minutos. Estimación manual: 2 semanas.
Caso de Uso 4: Investigación y Corrección de un Bug Complejo
El Escenario
Los usuarios reportan corrupción intermitente de datos en un sistema de cálculo financiero. El bug solo ocurre bajo condiciones específicas.
El 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
"
Cómo Investiga Claudiomiro
Fase de Investigación:
💭 "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..."
**Diseño de la Solución:**
```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
Implementación:
// 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;
}
Tests Creados:
// 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
})
);
});
});
El Resultado
Causa raíz encontrada en 3 archivos. Todas las condiciones de carrera eliminadas. Tests de concurrencia añadidos. Logging añadido para depuración futura. Tiempo: 8 minutos.
Conclusiones Clave
Lo que Hace Diferente a Claudiomiro
- Analiza y comprende el problema antes de escribir código.
- Toma decisiones arquitectónicas basadas en los patrones de la base de código, no en plantillas genéricas.
- Maneja funcionalidades completas, no solo fragmentos.
- Nunca omite los tests.
- El código llega completamente testeado y documentado.
Cuándo Usar Claudiomiro
Adecuado para: eliminar duplicación de código, implementar funcionalidades completas, refactorizaciones a gran escala, investigaciones de bugs complejos, migración de tecnologías y adición de cobertura de tests exhaustiva.
Menos adecuado para: experimentos rápidos, ejercicios de aprendizaje, tareas muy ambiguas y decisiones que requieren juicio humano.
Mejores Prácticas
Escribe mejores prompts incluyendo rutas de archivos, describiendo el estado actual y deseado, mencionando restricciones específicas y referenciando patrones similares en tu base de código.
Deja que Claudiomiro complete los 5 pasos sin interrupciones. Revisa el TODO.md generado con antelación. Usa --push=false para revisar antes de subir los cambios.
Usa Claudiomiro para trabajo grande y que consume tiempo: refactorizaciones repetitivas, mejoras de cobertura de tests, cambios arquitectónicos.
Conclusión
Claudiomiro convierte la asistencia de IA de chat interactivo en desarrollo autónomo. Siguiendo un flujo de trabajo estructurado y tomando decisiones inteligentes, maneja tareas complejas de desarrollo que llevarían días en cuestión de minutos.
Los números de los ejemplos: reducción del 81,6% en el código al eliminar duplicaciones, 95% de ahorro de tiempo en implementación de funcionalidades, 98% de ahorro de tiempo en grandes refactorizaciones y correcciones de bugs críticos con prevención de regresión integrada.
El objetivo no es reemplazar a los desarrolladores. Es eliminar el trabajo tedioso y que consume tiempo para que puedas concentrarte en la arquitectura y la resolución de problemas.
Empieza Ahora:
npm install -g claudiomiro
claudiomiro --prompt="Your complex task here"