Módulo 2: Agent Memory y Scopes

5. Proyecto — Memory Hierarchy para 3 Subagents

5. Proyecto — Memory Hierarchy para 3 Subagents

Descripción del Proyecto

En el Módulo 1 construiste 3 subagents especializados — reviewer, implementer, tester — y los encadenaste en un pipeline. Funcionan. Pero cada vez que los ejecutas, empiezan desde cero. El reviewer no recuerda que tu proyecto usa cursor-based pagination. El implementer no sabe que el equipo decidió usar Pydantic v2 models separados para request y response. El tester no retiene que el test de integración del módulo de pagos tarda 8 segundos y debería ejecutarse último. Son competentes pero amnésicos.

En este proyecto vas a resolver eso configurando una jerarquía de memoria completa para los 3 subagents. No es solo agregar memory: project al frontmatter — es diseñar qué recuerda cada agente, cómo curé su memoria, y cómo la memoria de uno complementa (sin duplicar) la del otro. El reviewer recuerda patrones del codebase y issues recurrentes. El implementer recuerda convenciones de código y decisiones arquitecturales. El tester recuerda trends de tests y failure patterns. Cada agente tiene un scope deliberado: el reviewer y el implementer comparten via git (scope project), el tester mantiene datos locales que no tiene sentido compartir (scope local).

El resultado es un sistema de 3 agentes que acumulan conocimiento institucional. La primera ejecución es idéntica a lo que tenías antes. La segunda ya es diferente — el reviewer menciona "este issue es nuevo, no estaba en sesiones anteriores." La quinta ejecución es notablemente mejor — el implementer aplica convenciones sin que tengas que recordárselas, y el tester sabe qué tests son normalmente lentos. Cuando un nuevo miembro del equipo clona el repo, los subagents con scope project traen el conocimiento acumulado sin explicaciones.

Este es el proyecto culminante del Módulo 2. Si los 3 subagents retienen memoria entre sesiones, la curan proactivamente, y la memoria de scope project se comparte via git — has dominado agent memory management.


Objetivo del Proyecto

Configurar una jerarquía de memoria persistente para 3 subagents (reviewer, implementer, tester) con scopes diferenciados, instrucciones de auto-curación, y verificar persistencia entre sesiones.

Al completar este proyecto:

  • ✅ Los 3 subagents tendrán memoria persistente configurada en su frontmatter
  • ✅ El reviewer e implementer usarán scope project (compartible via git)
  • ✅ El tester usará scope local (privado, datos de máquina)
  • ✅ Cada subagent tendrá instrucciones de auto-curación en su system prompt
  • ✅ MEMORY.md se creará automáticamente en la primera ejecución de cada subagent
  • ✅ La memoria persistirá entre sesiones: cerrar y reabrir Claude Code no la borra
  • ✅ La segunda ejecución de cada subagent mostrará uso de memoria acumulada
  • ✅ Las memorias project estarán commiteadas en git para compartir con el equipo

Duración estimada: 1-1.5 horas (configuración: 20 min + ejecución inicial: 20 min + verificación de persistencia: 15 min + segunda ejecución: 15 min + git commit y validación: 10 min).


Especificaciones Técnicas

Stack Tecnológico

  • Herramienta: Claude Code v2.1.63+
  • Subagent files: Markdown con frontmatter YAML
  • Ubicación de subagents: .claude/agents/ (scope proyecto)
  • Ubicación de memoria project: .claude/agent-memory/{name}/MEMORY.md
  • Ubicación de memoria local: .claude/agent-memory-local/{name}/MEMORY.md
  • Proyecto base: El mismo proyecto usado en el Módulo 1 (con código en src/, tests, y commits en git)

Prerequisitos

RequisitoDetalle
Módulo 1 completadoLos 3 subagent files existen en .claude/agents/
Proyecto con códigosrc/ con archivos, tests con suite ejecutable
Git inicializadoCommits existentes, git status limpio
Claude Code v2.1.63+Soporte para campo memory en frontmatter

Estructura Final del Proyecto

Al terminar, tu proyecto tendrá esta estructura adicional:

your-project/
├── .claude/
│   ├── agents/
│   │   ├── code-reviewer.md          ← memory: project
│   │   ├── code-implementer.md       ← memory: project
│   │   └── code-tester.md            ← memory: local
│   ├── agent-memory/                  ← scope project (git tracked)
│   │   ├── code-reviewer/
│   │   │   └── MEMORY.md             ← patrones, issues recurrentes
│   │   └── code-implementer/
│   │       └── MEMORY.md             ← convenciones, decisiones
│   └── agent-memory-local/            ← scope local (gitignored)
│       └── code-tester/
│           └── MEMORY.md             ← test performance, failure patterns
├── src/
├── tests/
├── CLAUDE.md
└── .gitignore                         ← incluye .claude/agent-memory-local/

Guía Paso a Paso

Paso 1: Verificar el Estado Actual

Antes de agregar memoria, verifica que los 3 subagents del Módulo 1 existen y funcionan.

ls -la .claude/agents/

Deberías ver:

code-reviewer.md
code-implementer.md
code-tester.md

Abre Claude Code y verifica:

/agents

Los 3 deben aparecer listados. Si falta alguno, créalo primero (referencia: Módulo 1, cápsula 05).

Verifica que no existen directorios de memoria previos:

ls .claude/agent-memory/ 2>/dev/null || echo "No existe (esperado)"
ls .claude/agent-memory-local/ 2>/dev/null || echo "No existe (esperado)"

Paso 2: Configurar el Code Reviewer con Memory

Edita .claude/agents/code-reviewer.md. Agrega memory: project al frontmatter y una sección Memory Management al system prompt.

Archivo completo:

---
name: code-reviewer
description: Analyzes recent code changes against quality criteria with persistent memory of project patterns. Read-only — never modifies files.
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: haiku
maxTurns: 15
memory: project
---

## Role

You are a senior code reviewer with persistent memory. You analyze recent git changes and produce a structured report organized by severity. You NEVER modify any file. Your job is to find problems — fixing them is someone else's responsibility.

You have memory of previous sessions. Use your MEMORY.md to:
- Avoid re-reporting known issues that haven't changed
- Apply project conventions consistently
- Track patterns across sessions
- Note when a previously recurring issue has been fixed

## Process

1. Read your MEMORY.md to recall project context
2. Run `git diff HEAD~3 --name-only` to identify recently changed files
3. Filter: only review files in `src/` (skip tests, configs, docs)
4. For each changed file:
   a. Read the complete file
   b. Read related files (imports, parent classes, interfaces) for context
   c. Apply review criteria, informed by your memory of project patterns
5. Compare findings against your memory:
   - If an issue was already reported and not fixed → note as "recurring"
   - If a previously recurring issue was fixed → note as "resolved"
   - If a new pattern is discovered → note for memory update
6. Produce the report in the exact output format below
7. Update your MEMORY.md with new insights

If `git diff HEAD~3` returns no files, try `git diff HEAD~1` or report that no recent changes were found.

## Review Criteria

### 1. Readability
- Functions longer than 30 lines
- Deeply nested logic (3+ levels)
- Unclear control flow

### 2. Naming Conventions
- Variables/functions not following project conventions (check memory for conventions)
- Inconsistent naming style within a file

### 3. Error Handling
- Bare `except:` or `except Exception:`
- Silenced errors (empty except blocks)
- Missing error handling on I/O, network, or database operations

### 4. Security
- Hardcoded credentials, API keys, or secrets
- User input used without validation or sanitization
- SQL queries built with string concatenation or f-strings

### 5. Performance
- Database queries inside loops (N+1 pattern)
- Loading large collections without pagination or limits
- Blocking operations in async context

### 6. Edge Cases
- Missing null/None checks before attribute access
- No handling of empty collections
- Missing boundary value validation

### 7. DRY (Don't Repeat Yourself)
- Duplicated logic blocks (3+ lines repeated)
- Copy-pasted code with minor variations

### 8. Type Safety
- Missing type hints on function signatures
- Using `Any` where a specific type is known

## Output Format

Follow this EXACT structure:

Code Review Report

Date: [YYYY-MM-DD] Commit range: HEAD~3..HEAD Files reviewed: [list of files] Memory status: [n] entries loaded from previous sessions

CRITICAL (must fix before merge)

  • [file:line] — [Short description]
    • Criteria: [which of the 8 criteria]
    • Evidence: [relevant code snippet]
    • Recommendation: [specific fix]
    • Status: [NEW | RECURRING (seen in [n] previous sessions)]

WARNING (should fix)

  • [file:line] — [Short description]
    • Criteria: [which of the 8 criteria]
    • Recommendation: [specific fix]
    • Status: [NEW | RECURRING]

SUGGESTION (nice to have)

  • [file:line] — [Short description]
    • Recommendation: [specific improvement]

Previously Recurring Issues — Now Resolved

  • [issue description] — Fixed in [file]

Summary

PriorityCountNewRecurring
Critical[n][n][n]
Warning[n][n][n]
Suggestion[n][n][n]

Verdict: [PASS | PASS_WITH_WARNINGS | NEEDS_REVISION]


If no issues are found in a category, write "None found."

## Memory Management

At the END of each session, update your MEMORY.md following these rules:

### Categories (use exactly these)
- **Architecture Decisions:** High-level design decisions observed in the codebase
- **Coding Conventions:** Naming, formatting, import ordering, style patterns
- **Known Patterns:** Authentication, validation, error handling patterns used in the project
- **Recurring Issues:** Issues found in 2+ sessions — track frequency

### Organization rules
- Most important items at the TOP of each category
- Each entry is a single line starting with "- "
- For Recurring Issues, include frequency: "- [3x] N+1 queries in product listings"
- No timestamps, no session narratives

### Size constraint
- Keep MEMORY.md under 150 lines
- If approaching 150 lines, remove least frequent Recurring Issues first
- Architecture Decisions are PERMANENT unless explicitly reverted
- NEVER exceed 180 lines total

### What NOT to store
- Information already in CLAUDE.md
- Temporary debugging observations
- Information obvious from reading pyproject.toml or package.json
- Individual file contents or code snippets

Paso 3: Configurar el Code Implementer con Memory

Edita .claude/agents/code-implementer.md. Agrega memory: project y sección Memory Management.

Archivo completo:

---
name: code-implementer
description: Fixes code issues from review reports with persistent memory of project conventions. Only modifies files in src/. Follows CLAUDE.md and accumulated conventions.
tools: Read, Edit, Write, Grep, Glob
disallowedTools: Bash
model: sonnet
maxTurns: 25
memory: project
---

## Role

You are a senior developer with persistent memory who fixes code issues identified in review reports. You work exclusively in `src/`. You follow existing project conventions — and you remember them from previous sessions.

You have memory of previous sessions. Use your MEMORY.md to:
- Apply coding conventions consistently without rediscovering them
- Remember architectural decisions and follow them
- Recall CLAUDE.md conventions that you've learned
- Avoid repeating implementation mistakes from previous sessions

## Constraints

- ONLY modify files inside `src/`
- NEVER modify files in `tests/`, `test/`, or any test file
- NEVER modify configuration files (*.yml, *.toml, *.cfg, *.json at root)
- NEVER modify CLAUDE.md, README.md, or documentation files
- NEVER install new dependencies
- NEVER delete files
- Follow the coding style already present in the project AND in your memory

## When Receiving a Review Report

Read the entire report first. Then:

1. **CRITICAL items:** Fix ALL of them. These are blockers.
2. **WARNING items:** Fix if the change is straightforward (< 10 lines changed). Skip if it requires architectural changes.
3. **SUGGESTION items:** SKIP unless explicitly asked to address them.
4. **RECURRING items:** Prioritize these — they indicate systematic issues.

For each fix:
- Check your memory for relevant conventions before editing
- Read the file and surrounding context before editing
- Make the minimal change that resolves the issue
- Preserve existing code style (indentation, quotes, naming)
- If a fix could affect other files, read those files first

## Process

1. Read your MEMORY.md to recall project conventions and decisions
2. Read CLAUDE.md for project-level conventions
3. Parse the review report to extract all items by priority
4. For each CRITICAL item:
   a. Check memory for relevant conventions
   b. Read the file mentioned
   c. Understand the context around the problematic code
   d. Apply the fix following known conventions
   e. Record what you changed
5. For each WARNING item (if straightforward):
   a. Same process as CRITICAL
6. Produce the implementation report
7. Update your MEMORY.md with new conventions or decisions discovered

## Output Format

Follow this EXACT structure:

Implementation Report

Files modified: [list of files changed] Review items addressed: [n] of [total] Memory entries used: [list conventions/decisions from memory that guided implementation]

Changes Made

  1. [file:line] — [What was changed]
    • Review item: [CRITICAL|WARNING] — [original description]
    • Fix applied: [description of the fix]
    • Convention applied: [from memory or CLAUDE.md]
    • Lines changed: [n]

Items Not Addressed

  • [file:line] — [original description]
    • Reason: [why it was skipped]

New Conventions Discovered

  • [any new convention or pattern discovered during implementation]

Summary

CategoryFoundFixedSkipped
Critical[n][n][n]
Warning[n][n][n]
Suggestion[n][n][n]

## Memory Management

At the END of each session, update your MEMORY.md following these rules:

### Categories (use exactly these)
- **Architecture Decisions:** Design patterns, service boundaries, data flow decisions
- **Coding Conventions:** Naming, formatting, import ordering, docstring style, error handling patterns
- **File Organization:** Where different types of code live, module structure
- **Dependency Decisions:** Libraries chosen, versions, why alternatives were rejected

### Organization rules
- Most important items at the TOP of each category
- Each entry is a single line starting with "- "
- Be specific: "snake_case for functions" not "use good naming"
- Include the WHY when non-obvious: "- cursor pagination (not offset) — performance on tables > 1M rows"

### Complementary to reviewer's memory
- You own Coding Conventions and Architecture Decisions (most detailed here)
- The reviewer owns Known Patterns and Recurring Issues
- Don't duplicate what the reviewer tracks — focus on implementation knowledge

### Size constraint
- Keep MEMORY.md under 150 lines
- If approaching 150 lines, remove Dependency Decisions with obvious choices first
- Architecture Decisions and Coding Conventions are priority — never remove these to make space
- NEVER exceed 180 lines total

### What NOT to store
- Information already in CLAUDE.md (don't duplicate)
- Review findings (that's the reviewer's job)
- Test results or coverage data (that's the tester's job)
- Temporary implementation notes

Paso 4: Configurar el Code Tester con Memory

Edita .claude/agents/code-tester.md. Agrega memory: local y sección Memory Management.

El tester usa scope local porque:

  • Tiempos de ejecución de tests dependen del hardware
  • Paths de virtualenv y configuración de entorno son específicos de cada máquina
  • Coverage trends pueden diferir entre desarrolladores (subsets de tests, configuraciones)
  • Failure patterns por entorno (OS-specific, memoria, concurrent processes) son locales

Archivo completo:

---
name: code-tester
description: Runs test suites and reports results with persistent memory of test performance trends and failure patterns. Never modifies code.
tools: Bash, Read, Grep, Glob
disallowedTools: Write, Edit
model: haiku
maxTurns: 12
memory: local
---

## Role

You are a test runner and reporter with persistent memory. You execute the project's test suite and produce a detailed report. You NEVER modify source code, test files, or any other file. If tests fail, your job is to report WHY they fail — not to fix them.

You have memory of previous test runs. Use your MEMORY.md to:
- Compare current results with historical trends
- Identify new failures vs pre-existing failures
- Track test suite execution time trends
- Note which tests are consistently slow or flaky

## Process

1. Read your MEMORY.md to recall test history
2. **Detect the test framework:**
   - Check for `pyproject.toml`, `setup.cfg` → pytest
   - Check for `package.json` → jest, vitest, or mocha
   - Check for `Cargo.toml` → cargo test
   - If unclear, look for test files and infer
3. **Run the full test suite:**
   - Python (pytest): `python -m pytest -v --tb=short 2>&1`
   - Python (with coverage): `python -m pytest --cov=src --cov-report=term-missing -v 2>&1`
   - Node (jest): `npx jest --verbose 2>&1`
   - Node (vitest): `npx vitest run --reporter=verbose 2>&1`
   - Always redirect stderr to stdout with `2>&1`
4. **Analyze results against memory:**
   - New failures (not in memory) → mark as NEW
   - Known failures (in memory) → mark as KNOWN
   - Previously failing tests now passing → mark as FIXED
   - Execution time compared to memory → note if significantly slower/faster
5. **If tests fail:**
   - Read the failing test file to understand what it expects
   - Read the source file the test is testing
   - Determine likely root cause
   - Do NOT attempt to fix anything
6. Produce the report
7. Update your MEMORY.md with current run data

## Output Format

Follow this EXACT structure:

Test Report

Framework: [detected framework and versión] Command: [exact command executed] Execution time: [seconds] ([FASTER|SLOWER|STABLE] vs last run: [previous time])

Results

StatusCountvs Last Run
✅ Passed[n][+/-n]
❌ Failed[n][+/-n]
⏭️ Skipped[n][+/-n]
Total[n]

Failed Tests

(If no failures, write "All tests passed.")

  1. [test_file::TestClass::test_name]
    • Status: [NEW failure | KNOWN failure (seen [n] times) | REGRESSION (was passing)]
    • Expected: [what the test expected]
    • Got: [what actually happened]
    • Error: [error message]
    • Root cause: [your analysis]

Previously Failing — Now Fixed

  • [test name] — was failing since [first seen], now passes

Slow Tests (> 2s)

TestTimeTrend
[test name][seconds][STABLE

Coverage

(If coverage data is available)

ModuleCoveragevs Last Run
[module][%][+/-pp]
Total[%][+/-pp]

Verdict

[ALL_PASS | FAILURES | ERROR]


## Memory Management

At the END of each session, update your MEMORY.md following these rules:

### Categories (use exactly these)
- **Test Performance:** Suite execution times (keep last 5 runs), slow tests (> 2s)
- **Failure Patterns:** Tests that have failed in 2+ sessions with root cause
- **Coverage Trends:** Module coverage percentages (keep last 3 snapshots)
- **Environment Notes:** Test framework detected, command used, virtualenv path, OS-specific notes
- **Flaky Tests:** Tests that pass/fail inconsistently — track pass rate

### Organization rules
- Most recent data at the TOP within each category
- For Performance, keep a running log: "- [2026-03-13] 45s (82 tests)"
- For Failures, track frequency: "- [5x] test_payment_timeout — root cause: mock not cleaning up"
- For Coverage, keep snapshots: "- [2026-03-13] total: 78%, src/api: 85%, src/models: 72%"

### Size constraint
- Keep MEMORY.md under 120 lines (test data changes more frequently)
- Keep only last 5 performance entries (remove oldest)
- Keep only last 3 coverage snapshots
- Remove failure patterns for tests that have been deleted
- NEVER exceed 150 lines total

### What NOT to store
- Full test output or stack traces (only root cause summaries)
- Individual test results that passed (only failures and slow tests)
- Dependency versions (obvious from config files)
- One-time failures that didn't recur

Paso 5: Configurar .gitignore para Memoria Local

Agrega la carpeta de memoria local a .gitignore para que no se commitee accidentalmente.

echo "" >> .gitignore
echo "# Claude Code local memory (machine-specific, not shared)" >> .gitignore
echo ".claude/agent-memory-local/" >> .gitignore

Verifica:

grep "agent-memory-local" .gitignore

La memoria project (en .claude/agent-memory/) NO se agrega a .gitignore — esa es la que se comparte via git.

Paso 6: Primera Ejecución — Crear Memorias Iniciales

Ahora ejecuta cada subagent una vez para que creen sus archivos MEMORY.md iniciales.

6a. Ejecutar el reviewer:

Usa el code-reviewer para analizar los cambios recientes del proyecto

Después de la ejecución, verifica que se creó la memoria:

ls -la .claude/agent-memory/code-reviewer/
cat .claude/agent-memory/code-reviewer/MEMORY.md

Deberías ver un archivo MEMORY.md con las categorías definidas en el system prompt, poblado con insights de esta primera ejecución.

Qué verificar:

  • ✅ El archivo existe en .claude/agent-memory/code-reviewer/
  • ✅ Usa las categorías correctas: Architecture Decisions, Coding Conventions, Known Patterns, Recurring Issues
  • ✅ El contenido refleja patrones reales del proyecto (no genéricos)
  • ✅ Está bajo 150 líneas
  • ✅ No duplica información de CLAUDE.md

6b. Ejecutar el implementer:

Usa el code-implementer para agregar type hints a las funciones en src/ que no los tengan

Verificar:

ls -la .claude/agent-memory/code-implementer/
cat .claude/agent-memory/code-implementer/MEMORY.md

Qué verificar:

  • ✅ Archivo existe en .claude/agent-memory/code-implementer/
  • ✅ Categorías: Architecture Decisions, Coding Conventions, File Organization, Dependency Decisions
  • ✅ Complementario al reviewer (no duplica Known Patterns ni Recurring Issues)
  • ✅ Contenido específico: nombres concretos de convenciones, no genéricos

6c. Ejecutar el tester:

Usa el code-tester para ejecutar la suite de tests del proyecto

Verificar:

ls -la .claude/agent-memory-local/code-tester/
cat .claude/agent-memory-local/code-tester/MEMORY.md

Qué verificar:

  • ✅ Archivo existe en .claude/agent-memory-local/code-tester/ (local, no project)
  • ✅ Categorías: Test Performance, Failure Patterns, Coverage Trends, Environment Notes, Flaky Tests
  • ✅ Contiene datos reales: tiempo de ejecución, conteo de tests, coverage
  • ✅ Environment Notes tiene el framework detectado y el comando usado

Paso 7: Verificar Persistencia — Cerrar y Reabrir

Este es el paso más importante. La memoria solo vale si persiste entre sesiones.

7a. Cerrar Claude Code:

Sal de la sesión actual de Claude Code completamente.

/exit

7b. Verificar que los archivos siguen ahí:

cat .claude/agent-memory/code-reviewer/MEMORY.md
cat .claude/agent-memory/code-implementer/MEMORY.md
cat .claude/agent-memory-local/code-tester/MEMORY.md

Los 3 archivos deben existir con el contenido de la sesión anterior.

7c. Reabrir Claude Code:

claude

7d. Ejecutar el reviewer otra vez:

Usa el code-reviewer para analizar los cambios recientes del proyecto

Qué observar en la segunda ejecución:

  • ✅ El reporte menciona "Memory status: [n] entries loaded from previous sessions"
  • ✅ Si hay issues iguales a la sesión anterior, aparecen como "RECURRING" en lugar de "NEW"
  • ✅ Si algún issue fue resuelto, aparece en "Previously Recurring Issues — Now Resolved"
  • ✅ MEMORY.md se actualiza sin duplicar entries existentes

7e. Verificar que la memoria se actualizó (no se duplicó):

wc -l .claude/agent-memory/code-reviewer/MEMORY.md
cat .claude/agent-memory/code-reviewer/MEMORY.md

El conteo de líneas debería ser similar al de la sesión anterior (±10 líneas). Si se duplicó todo, las instrucciones de curación necesitan ajuste.

Paso 8: Segunda Ejecución del Pipeline Completo

Ejecuta el pipeline completo para verificar que la memoria funciona en el flujo encadenado:

Ejecuta reviewer → implementer → tester en secuencia.
El reviewer debe distinguir issues nuevos de recurrentes.
El implementer debe aplicar convenciones desde su memoria.
El tester debe comparar resultados con ejecuciones anteriores.
Dame un resumen consolidado al final.

Qué observar: El reviewer clasifica issues como NEW o RECURRING. El implementer menciona "Convention applied: [from memory]." El tester compara: "45s (vs 42s last run)", "test_X: KNOWN failure."

Paso 9: Git Commit para Compartir Memorias Project-Scope

Las memorias con scope project deben commitearse para que el equipo las comparta.

git add .claude/agent-memory/
git status

Verifica que git status muestra:

new file: .claude/agent-memory/code-reviewer/MEMORY.md
new file: .claude/agent-memory/code-implementer/MEMORY.md

Verifica que NO muestra archivos de .claude/agent-memory-local/ (deben estar en .gitignore).

git commit -m "Add agent memory for reviewer and implementer (project scope)

- Reviewer: codebase patterns, naming conventions, recurring issues
- Implementer: coding conventions, architecture decisions, file organization
- Tester memory is local scope (machine-specific, not committed)"

Paso 10: Verificar Scope Local del Tester

Confirma que la memoria del tester NO está en el commit:

git show HEAD --stat

Solo deberías ver archivos de code-reviewer y code-implementer. La memoria del tester está en .claude/agent-memory-local/ que es gitignored — existe localmente pero no se comparte.


Los 3 Subagent Files Completos — Referencia

Referencia rápida de diferencias

Aspectocode-reviewercode-implementercode-tester
Memory scopeprojectprojectlocal
Compartible via git✅✅❌
Categorías de memoriaPatterns, IssuesConventions, ArchitecturePerformance, Failures
Límite de líneas150150120
ComplementariedadPatterns + IssuesConventions + DecisionsTest-specific data
Curación auto✅ (en system prompt)✅ (en system prompt)✅ (en system prompt)

Dónde vive cada memoria

Reviewer (project):
  .claude/agent-memory/code-reviewer/MEMORY.md
  → git tracked, shared with team

Implementer (project):
  .claude/agent-memory/code-implementer/MEMORY.md
  → git tracked, shared with team

Tester (local):
  .claude/agent-memory-local/code-tester/MEMORY.md
  → gitignored, machine-specific

Por qué cada scope

AgenteScopeRazón
ReviewerprojectPatrones e issues son del equipo — un nuevo dev debe saberlos al clonar
ImplementerprojectConvenciones y decisiones son del equipo — todos deben seguirlas
TesterlocalTiempos de tests dependen del hardware, failure patterns varían por OS/entorno

Checklist de Validación

Archivos de subagent actualizados

  • code-reviewer.md tiene memory: project en el frontmatter
  • code-reviewer.md tiene sección Memory Management en el system prompt
  • code-implementer.md tiene memory: project en el frontmatter
  • code-implementer.md tiene sección Memory Management en el system prompt
  • code-tester.md tiene memory: local en el frontmatter
  • code-tester.md tiene sección Memory Management en el system prompt

Archivos de memoria creados

  • .claude/agent-memory/code-reviewer/MEMORY.md existe y tiene contenido
  • .claude/agent-memory/code-implementer/MEMORY.md existe y tiene contenido
  • .claude/agent-memory-local/code-tester/MEMORY.md existe y tiene contenido

Contenido de memoria correcto

  • Reviewer memory tiene: Architecture Decisions, Coding Conventions, Known Patterns, Recurring Issues
  • Implementer memory tiene: Architecture Decisions, Coding Conventions, File Organization, Dependency Decisions
  • Tester memory tiene: Test Performance, Failure Patterns, Coverage Trends, Environment Notes, Flaky Tests
  • No hay duplicación significativa entre reviewer e implementer
  • Todas las memorias están bajo su límite de líneas (150/150/120)

Persistencia verificada

  • Cerraste Claude Code y lo reabriste
  • Los archivos MEMORY.md siguen existentes con su contenido
  • La segunda ejecución del reviewer usa la memoria (muestra "entries loaded" o marca issues como RECURRING)
  • La segunda ejecución del tester compara con datos históricos

Scopes correctos

  • .gitignore incluye .claude/agent-memory-local/
  • git status NO muestra archivos de agent-memory-local
  • Memorias project están commiteadas en git
  • Memoria local NO está en el commit

Complementariedad

  • El reviewer no registra convenciones de código (eso lo hace el implementer)
  • El implementer no registra issues recurrentes (eso lo hace el reviewer)
  • El tester no registra patrones del codebase (eso lo hacen reviewer/implementer)

Pipeline con memoria

  • El pipeline completo (reviewer → implementer → tester) funciona con las 3 memorias activas
  • El resumen consolidado incluye referencias a memoria (issues recurrentes, convenciones aplicadas, comparación de tests)

Errores Comunes y Soluciones

Error 1: "MEMORY.md no se crea después de ejecutar el subagent"

Síntoma: Ejecutas el subagent pero .claude/agent-memory/{name}/ no existe o está vacío.

Causas posibles:

  • El campo memory no está en el frontmatter o está mal escrito
  • El valor del campo no es válido (memory: project, no memory: "project" con comillas en algunos parsers)
  • Claude Code no tiene permisos para crear directorios

Solución:

Verifica el frontmatter:

head -10 .claude/agents/code-reviewer.md

Confirma que memory: project aparece entre los ---. Si usas comillas, prueba sin ellas. El valor debe ser exactamente project, local, o user.

Si el directorio no se crea automáticamente, créalo manualmente y deja que el agente escriba el archivo:

mkdir -p .claude/agent-memory/code-reviewer

Error 2: "MEMORY.md se duplica en cada sesión"

Síntoma: Cada ejecución agrega todas las entradas de nuevo, duplicando el contenido.

Causa: Las instrucciones de Memory Management no especifican "update existing entries" — el agente interpreta que debe agregar siempre.

Solución: Agrega esta instrucción al inicio de la sección Memory Management:

### Update rules
- READ your current MEMORY.md before making ANY changes
- UPDATE existing entries if the information changed
- ADD new entries only if they don't already exist
- REMOVE entries that are no longer accurate
- NEVER duplicate an existing entry — update it in place

Error 3: "La memoria del tester aparece en git status"

Síntoma: git status muestra archivos en .claude/agent-memory-local/.

Causa: .gitignore no tiene la regla correcta, o se commiteó antes de agregar la regla.

Solución:

grep "agent-memory-local" .gitignore

Si no aparece, agrega:

echo ".claude/agent-memory-local/" >> .gitignore

Si ya está en .gitignore pero los archivos siguen apareciendo, es porque se trackearon antes:

git rm -r --cached .claude/agent-memory-local/
git commit -m "Remove local memory from tracking"

Error 4: "El reviewer y el implementer tienen información contradictoria"

Síntoma: El reviewer dice "offset pagination" y el implementer dice "cursor-based pagination."

Solución: Establece source of truth en ambos system prompts: el implementer es source of truth para Architecture Decisions y Coding Conventions, el reviewer para Known Patterns y Recurring Issues. Si hay contradicción, el agente que no es source of truth actualiza su memoria para coincidir.

Error 5: "La memoria crece sin control a pesar de las instrucciones"

Síntoma: MEMORY.md supera el límite de líneas.

Solución: Refuerza con "CRITICAL CONSTRAINT: Before adding ANY new entry, check the line count. If it exceeds [limit], remove at least one entry first. This is a HARD LIMIT." También puedes verificar y curar manualmente con wc -l y tu editor.

Error 6: "El subagent no usa la memoria"

Síntoma: Output idéntico al de un agente sin memoria. No marca issues como RECURRING.

Solución: Verifica que MEMORY.md tiene menos de 200 líneas (wc -l). Si tiene contenido pero el agente no lo usa, agrega al inicio del system prompt: "IMPORTANT: You have persistent memory. Read your MEMORY.md at the START of every session and reference specific entries in your output."

Error 7: "No sé si la memoria realmente persiste o se recrea desde cero"

Síntoma: Dudas sobre si el agente usa la memoria anterior o la recrea.

Solución: Agrega una entry "canary" manual:

echo "- [CANARY] This entry was manually added to verify persistence" >> \
  .claude/agent-memory/code-reviewer/MEMORY.md

Ejecuta el subagent. Si [CANARY] sigue presente después de la ejecución, la memoria persiste. Si desapareció, hay un problema con la persistencia.

Error 8: "El implementer no sigue las convenciones de su propia memoria"

Síntoma: MEMORY.md dice "snake_case for functions" pero el implementer crea funciones con camelCase.

Solución: En la sección Process, haz la conexión explícita: "For EVERY file you edit, check your Coding Conventions section and apply them. If a convention in your memory contradicts the current code, follow the code (it may have changed) and update your memory."


Recursos del Proyecto

  1. Subagents — Persistent Memory (Anthropic Docs) — Documentación oficial del campo memory, scopes, y el mecanismo de MEMORY.md
  2. Create Custom Subagents — Referencia completa de frontmatter YAML incluyendo memory, hooks, y todos los campos opcionales
  3. Claude Code Best Practices — Buenas prácticas de gestión de contexto y CLAUDE.md que complementan la memoria del agente
  4. Prompt Engineering: Be Clear and Direct — Técnicas de claridad aplicables a instrucciones de auto-curación y memory management
  5. Claude Code CLI Reference — Referencia del CLI para verificar subagents con /agents y debugging
  6. Claude Models Documentation — Referencia de modelos y ventanas de contexto para entender el impacto de la memoria en el rendimiento

Conexión con el Siguiente Módulo

Has construido un sistema de 3 agentes con memoria persistente. Cada uno recuerda lo que necesita, curé su propia memoria, y comparte (o no) via git según el scope. Es un avance fundamental sobre los agentes amnésicos del Módulo 1. Pero todavía tienen una limitación: trabajan en secuencia.

El reviewer termina antes de que el implementer empiece. El implementer termina antes de que el tester ejecute. En un pipeline de 3 agentes, esto es aceptable — el flujo es lineal y cada agente necesita el output del anterior. Pero imagina un proyecto donde necesitas:

  • Un agente revisando el backend mientras otro revisa el frontend
  • Un agente generando tests mientras otro actualiza la documentación
  • Tres agentes implementando features diferentes en paralelo

La ejecución secuencial triplicaría el tiempo. Lo que necesitas es delegación paralela — múltiples subagents trabajando simultáneamente.

Pero aquí es donde la memoria que configuraste se vuelve crítica. Si dos agentes trabajan en paralelo sin contexto compartido, pueden tomar decisiones contradictorias. El agente de backend decide usar snake_case mientras el de frontend usa camelCase. El agente de tests genera tests para una interfaz que el agente de implementación cambió. Sin la memoria compartida via scope project, la delegación paralela produce caos coordinado.

El Módulo 3: Parallel Sub-Agent Delegation te enseña a ejecutar subagents en paralelo con la garantía de que la memoria compartida mantiene la consistencia. Los subagents con memoria que creaste aquí son los que vas a paralelizar — y la memoria es lo que evita que la paralelización sacrifique la coherencia.


Resumen

  • Configuraste memory: project para reviewer e implementer — sus memorias se comparten via git con el equipo
  • Configuraste memory: local para el tester — sus datos de performance y entorno son específicos de cada máquina
  • Cada subagent tiene instrucciones de auto-curación en su system prompt con categorías, límites de líneas, y reglas de priorización
  • Las memorias son complementarias: el reviewer registra patterns e issues, el implementer registra conventions y decisions, el tester registra performance y failures
  • Verificaste persistencia cerrando y reabriendo Claude Code — los archivos MEMORY.md sobreviven entre sesiones
  • La segunda ejecución produce resultados distintos a la primera: issues marcados como RECURRING, convenciones aplicadas desde memoria, resultados de tests comparados con historial
  • Las memorias project están commiteadas en git — un nuevo miembro del equipo obtiene el conocimiento institucional al clonar
  • La memoria local está gitignored — datos de máquina no contaminan el repositorio compartido
  • La memoria configurada aquí es prerequisito para el Módulo 3 — sin contexto compartido, la delegación paralela produce decisiones contradictorias

Siguiente módulo: El Módulo 3 (Parallel Sub-Agent Delegation) te enseña a ejecutar múltiples subagents simultáneamente. Usarás los agentes con memoria que configuraste aquí y aprenderás a coordinar su trabajo en paralelo — review del backend y frontend al mismo tiempo, implementación de múltiples features concurrentes, ejecución de test suites en paralelo. La memoria compartida que configuraste es la base que garantiza consistencia en la ejecución paralela.