Изоляция сеансов для проверок
Проводите проверку в новом экземпляре без контекста генерации
«Изоляция сеансов для проверок» — бесплатный урок Claude Architect на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Claude Architect, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Claude Architect содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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 jsonParseable 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.jsonTwo 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 jsonResume 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 jsonExplicit 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 jsonQuick 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 -pinvocation; never--resumethe generation session for review. - Non-interactive + JSON —
-pwith--output-format jsongives 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.
Часто задаваемые вопросы
Урок «Изоляция сеансов для проверок» бесплатный?
Да — полный текст урока «Изоляция сеансов для проверок» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Claude Architect, подпишись на CoddyKit PRO. Курс Claude Architect содержит 4 уроков всего.
Чему я научусь в уроке «Изоляция сеансов для проверок»?
Проводите проверку в новом экземпляре без контекста генерации Ты практикуешь Claude Architect с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Claude Architect?
Предыдущий опыт не требуется. Claude Architect на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Изоляция сеансов для проверок»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Claude Architect?
Да. Каждый урок Claude Architect включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Неинтерактивный режим
- Структурированный вывод
- Изоляция сеансов для проверок
- Генерация тестов и стандарты