0Pricing
Claude Architect · Lección

Aislamiento de sesiones para revisiones

Revise en una instancia nueva, sin el contexto de generación.

Aislamiento de sesiones para revisiones es una lección gratuita de Claude Architect en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Claude Architect, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Claude Architect incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

The Author Bias Problem

When Claude generates code and then reviews it in the same session, the review is compromised. The model still holds its own reasoning in context, so it tends to defend its choices instead of challenging them.

This is the same-session self-review anti-pattern. The author retains the rationale for every decision and rarely flags its own assumptions as suspect.

The exam principle is blunt: independent, fresh-instance review beats same-session self-review. In CI/CD, that means the reviewer should never share context with the generator.

Why a Fresh Instance Wins

A reviewer that starts from a blank context window approaches the diff like an outsider. It has no investment in why a function was written a certain way, so it evaluates the code on its merits alone.

  • Generation context = the prompts, exploration, and reasoning that produced the code.
  • Review context = just the code, the standards, and the review criteria.

Keeping these separate removes the confirmation bias that makes a self-review wave its own work through. Session isolation is the mechanism that enforces this separation in a pipeline.

Non-Interactive Mode in CI

Pipelines have no terminal to type into, so Claude Code must run in non-interactive (print) mode. Use -p (or --print) to pass a single prompt and get a single result back, then exit.

This is the foundation for an isolated review step: each invocation is a fresh process with its own clean context, completely separate from any generation step that ran earlier.

# Non-interactive review invocation in a CI job
claude -p "Review the staged diff for correctness and security issues." \
  --output-format json

Parseable Output for the Gate

A CI step needs machine-readable results, not prose. Add --output-format json so the pipeline can parse findings and decide whether to pass or fail the build.

Pairing JSON output with a schema makes the result deterministic to consume: your gate script reads structured fields instead of grepping free text for words like "LGTM" or "done" — which is an anti-pattern.

claude -p "$(cat .ci/review-prompt.md)" \
  --output-format json \
  > review-result.json

# Gate script parses structured fields, never scans text
jq '.findings[] | select(.severity == "blocker")' review-result.json

Two Processes, Two Contexts

The cleanest isolation pattern in CI/CD is to split generation and review into two separate Claude Code invocations. The generation job writes code; a later, independent -p job reviews it.

Because each invocation is its own process, the reviewer never inherits the generator's conversation history. This mirrors the multi-agent rule from the exam: subagents do not inherit a coordinator's history — context must be passed explicitly, never assumed.

# Stage 1 — generation (its own session/context)
claude -p "Implement the feature described in TICKET-412."

# Stage 2 — review (a brand-new process, zero shared context)
claude -p "Review the resulting diff against our coding standards." \
  --output-format json

Resume Is Not Isolation

It is tempting to --resume the generation session and ask it to review its own work. Don't. A resumed session carries the original reasoning back into context — that is exactly the self-review bias you want to avoid.

There is a second hazard: resumed tool results can be stale if the codebase changed since they were captured. Sometimes a fresh session seeded with a structured summary beats resuming a named session outright.

For unbiased review, default to a fresh session every time.

# --resume continues a NAMED session (keeps prior context — biased for review)
claude --resume feature-412 -p "Now review what you wrote."   # avoid for review

# fork_session branches from a shared point — still inherits context
# For review, prefer a clean -p invocation instead.

Feed Only the Diff and the Rules

An isolated reviewer should receive a tight, relevant payload: the diff to inspect plus the standards to apply. Trim verbose tool output to the fields that matter — bloated context triggers the lost-in-the-middle effect, where the model attends to the start and end far more than the middle.

Keep the review criteria near the start or end of the prompt so they are not buried mid-context.

git diff --staged > /tmp/diff.patch

claude -p "You are an independent reviewer with no prior context.

Review ONLY this diff against the rules below.

<rules>$(cat .ci/review-rules.md)</rules>

<diff>$(cat /tmp/diff.patch)</diff>" \
  --output-format json

Explicit Criteria Beat Vague Asks

An isolated session has no shared assumptions to fall back on, so the criteria must be explicit. Precise rules dramatically cut false positives.

  • Vague: "be more precise" — produces noisy, inconsistent flags.
  • Explicit: "flag a comment only when it contradicts the code it describes" — produces actionable findings.

For CI reviews specifically, the goal is to minimize false positives — a reviewer that cries wolf gets ignored and erodes trust in the gate.

Few-Shot Examples for Consistency

To make an isolated reviewer behave consistently across runs, add 2-4 targeted few-shot examples covering the ambiguous cases. The model generalizes from them — it doesn't just echo them back.

Few-shot is the right tool for consistency, edge cases, output format, and reducing hallucinated findings. A couple of well-chosen flag / do-not-flag examples align the reviewer's judgment with your team's bar.

<examples>
  <example verdict="flag">
    Code swallows the exception silently — masks failures. Report it.
  </example>
  <example verdict="do-not-flag">
    A TODO comment about future work is not a defect. Ignore it.
  </example>
</examples>

Structured Output Locks the Verdict

Force the reviewer to emit a structured verdict via a tool and JSON Schema. Set tool_choice to "any" so the model must call a tool — this guarantees structured output instead of free prose.

Mark a field required only when it is always present. Never require a possibly-absent field, or the model will fabricate a value. Use an enum with an "other" option plus a free-text detail field so new finding types stay representable.

review_tool = {
    "name": "submit_review",
    "description": "Return the review verdict and findings.",
    "input_schema": {
        "type": "object",
        "properties": {
            "verdict": {"enum": ["pass", "fail"]},
            "findings": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "category": {"enum": ["bug", "security", "style", "other"]},
                        "detail": {"type": "string"}
                    },
                    "required": ["category", "detail"]
                }
            }
        },
        "required": ["verdict"]
    }
}

# tool_choice="any" guarantees a tool call (structured output)
message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=2048,
    tools=[review_tool],
    tool_choice={"type": "any"},
    messages=[{"role": "user", "content": review_prompt}],
)

Re-Runs: Report Only New Issues

When a pull request is updated and the review re-runs, a fresh session would re-flag everything from scratch — including already-acknowledged items. That creates noise.

The exam pattern: when re-running, include the prior results and report only new or still-unfixed issues. You preserve session isolation (still a clean reviewer) while passing the prior findings in explicitly as input — context handed over deliberately, not inherited from a resumed generation session.

claude -p "Independent re-review. Below are the diff and the findings
from the previous run. Report ONLY new issues or prior issues that
are still unfixed. Do not repeat resolved items.

<previous_findings>$(cat last-review.json)</previous_findings>
<diff>$(git diff --staged)</diff>" \
  --output-format json

Quick Check

Test your grasp of the core decision behind isolated reviews.

Recap: Isolation by Design

Key takeaways for session-isolated reviews in CI/CD:

  • Fresh instance beats self-review — the author defends its own work; an outsider doesn't.
  • Separate processes — review with a distinct claude -p invocation; never --resume the generation session for review.
  • Non-interactive + JSON — -p with --output-format json gives clean context and parseable results; never grep text for completion signals.
  • Explicit criteria + 2-4 few-shot examples minimize false positives and keep verdicts consistent.
  • tool_choice "any" forces structured output; require only always-present fields.
  • On re-runs, pass prior findings explicitly and report only new or unfixed issues.
  • Never route blocking pre-merge reviews through the Batch API.

Preguntas frecuentes

¿La lección «Aislamiento de sesiones para revisiones» es gratis?

Sí — el texto completo de «Aislamiento de sesiones para revisiones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Claude Architect, actualiza a CoddyKit PRO. El curso de Claude Architect incluye 4 lecciones en total.

¿Qué aprenderé en «Aislamiento de sesiones para revisiones»?

Revise en una instancia nueva, sin el contexto de generación. Practicas Claude Architect con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Claude Architect?

No se requiere experiencia previa. Claude Architect en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Aislamiento de sesiones para revisiones»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Claude Architect?

Sí. Cada lección de Claude Architect incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Modo no interactivo
  2. Salida estructurada
  3. Aislamiento de sesiones para revisiones
  4. Generación de pruebas y estándares
← Volver a Claude Architect