Skip to content

Search articles, repositories, topics and pages.

Coding Agents

Survival Rules for Working with Claude Code

An evidence-graded field guide to using Claude Code safely and reproducibly: constrain the task, protect the context window, verify every change and automate only inside explicit boundaries.

TIAN NEWS AI

Published Updated 10 min read

A minimal four-stage coding workflow loops through repository files, a code change, executable verification and diff review inside a permission boundary

Updated

Commands, context behavior, memory files, checkpoints, subagents, permissions, hooks and non-interactive execution were checked against current first-party Claude Code documentation on October 1, 2026.

Tested with

Claude Code documentation · TACL 2024 long-context study · ICLR 2024 SWE-bench paper

Claude Code can inspect a repository, edit files and execute tools. That makes it more useful than a completion system and more consequential than a chat interface. The central question is therefore not whether the model can produce plausible code. It is whether a human–agent workflow can make the resulting change bounded, testable, reviewable and recoverable.

The rules below are operational controls, not guarantees of correctness. Most come from Anthropic's first-party documentation. Two independent research results provide useful background: long-context models can underuse information depending on where it appears, and repository-level issue resolution is evaluated by applying patches and running tests rather than by judging prose. Neither result, by itself, proves that a particular Claude Code workflow is optimal.

Scope and standard of evidence

This article distinguishes three kinds of statement:

Evidence classWhat it supportsWhat it does not support
Current Claude Code documentationProduct behavior, commands and recommended workflowsIndependent estimates of productivity or defect reduction
Peer-reviewed experimentsFindings under a published dataset and evaluation protocolUniversal claims about every model, repository or future release
Engineering recommendationA reproducible way to reduce operational riskA vendor-independent law or guaranteed outcome

The phrase survival rule is deliberately practical. It means a control that limits the cost of a predictable failure mode: misunderstood scope, irrelevant context, unverifiable output, excessive authority or unsafe automation.

The system to control

An agentic coding session can be represented as a feedback system:

  1. A user specifies an objective, constraints and an acceptable result.
  2. The agent observes repository state through files, search and commands.
  3. It selects an action under the available tool permissions.
  4. The environment returns evidence: diffs, diagnostics, tests or rendered output.
  5. The agent or reviewer compares that evidence with the acceptance criteria.

Failure can enter at every stage. A vague objective produces the wrong target. Incomplete observation produces a locally plausible patch. Broad permissions increase the effect of a mistaken action. Weak verification allows an incorrect change to appear complete.

A bounded software engineering loop connects scope, repository inspection, implementation, verification and review, with context, permissions and version control surrounding the loop
A useful coding-agent loop is bounded by context, permissions and recoverable version control; passing through the loop does not itself prove correctness. Image generated by AI.

Rule 1: Define an observable finish condition

Claude Code's official best-practices guide recommends giving the agent a check it can run: tests, a build, a linter, a fixture comparison or a screenshot. This is stronger than asking the agent to “make it work,” because it turns completion into an observable condition.

A useful task specification contains four parts:

FieldExample
OutcomeSession refresh succeeds after the access token expires
ScopeAuthentication application service and its tests
ConstraintsPreserve the public API; add no dependency
EvidenceReproduction test fails before the patch and passes after it; full typecheck passes

Tests are evidence, not proof. A passing suite establishes only that the tested properties held in that environment. For security-sensitive or user-facing work, combine automated checks with a diff review, threat-oriented reasoning or visual inspection.

Key takeaway

Ask for artifacts that can falsify success: a failing reproduction, a passing command, a rendered screenshot or a constrained diff. Confidence expressed in prose is not verification.

A verification ladder rises from explicit acceptance criteria through a reproduction, targeted checks, broader regression checks and independent review, with evidence recorded at each step
Verification should accumulate evidence from the narrow failure condition to broader regression checks and review. Each layer answers a different question. Image generated by AI.

Rule 2: Separate observation, decision and mutation

For unfamiliar or cross-cutting work, separate exploration from implementation:

  1. Observe. Identify entry points, dependencies, tests and repository constraints without editing.
  2. Plan. State the intended files, invariants, failure cases and verification commands.
  3. Mutate. Make the smallest coherent change that implements the plan.
  4. Evaluate. Run the specified checks, inspect the diff and account for failures.

Claude Code supports a plan permission mode that allows analysis without file changes. The documentation recommends planning when the approach is uncertain, the code is unfamiliar or several files are involved. It also warns that planning adds overhead; a typo or obvious one-line edit usually does not need a separate planning phase.

The important principle is not ritual. It is preventing an irreversible or wide-reaching action from occurring before the agent has enough evidence to select it.

Rule 3: Specify boundaries, not every keystroke

Effective prompts name the target, the observed symptom, constraints and a verification method. They can also point to an existing implementation pattern. This reduces ambiguity without dictating an implementation that the repository may contradict.

task-contract.txt
Users are logged out when an access token expires even though the refresh token
is valid. Inspect the existing session flow before editing. Keep the public API
unchanged, add a regression test for this exact failure and run the auth tests
plus the typechecker. Do not change files outside src/auth without explaining why.

This contract leaves room for investigation while constraining the observable result and blast radius. By contrast, “fix auth” underspecifies the outcome, while a long sequence of guessed code edits may overconstrain the solution.

Rule 4: Treat context as a budget

Anthropic documents the context window as a principal operational constraint: conversation history, files and command output all consume it; Claude Code automatically compacts history near its limit; /clear starts fresh context; and /compact can guide summarisation.

Independent long-context research offers a narrower but relevant warning. Liu et al. found that several language models performed worse when relevant evidence appeared in the middle of long inputs. The experiments were retrieval and question-answering tasks, not Claude Code sessions, so they support caution about context utilisation rather than a precise threshold for coding quality.

Good context management follows from information value:

  • Start a new session for an unrelated task.
  • Prefer symbol search, focused file ranges and targeted test output over indiscriminate repository dumps.
  • Keep the active objective, constraints, modified-file list and unresolved failures through compaction.
  • Move verbose, independent investigation into an isolated subagent only when its summary will be sufficient.
  • Avoid repeatedly injecting full logs when the relevant error and surrounding trace are enough.
A limited context budget contains the current objective, repository evidence, decisions and compact command results, while verbose research is isolated in a subagent and stale material is removed
Context management is an information-selection problem: retain decision-relevant evidence, isolate disposable exploration and remove stale task history. Image generated by AI.

Rule 5: Design persistent instructions as a hierarchy

Claude Code currently supports CLAUDE.md, AGENTS.md, path-scoped rules, skills and auto memory. These mechanisms do not have the same purpose.

MechanismAppropriate contentMain risk
CLAUDE.md or AGENTS.mdCommands, architecture invariants and rules needed in most sessionsAlways-on context becomes noisy or contradictory
Path-scoped rulesConstraints that apply only to selected filesIncorrect patterns load rules in the wrong scope
SkillsDetailed domain knowledge or repeatable, on-demand workflowsVague descriptions prevent appropriate activation
Auto memoryLearned preferences and repository observationsStale or incorrect notes persist until reviewed
HooksDeterministic enforcement around tool eventsFaulty automation blocks valid work or creates noisy output

Anthropic explicitly describes memory files as context rather than enforced configuration. A statement such as “never edit .env” is advisory when written only in an instruction file. If the prohibition must hold, enforce it with permissions, sandbox policy or a PreToolUse hook.

The practical test for an always-loaded instruction is: would its absence predictably cause an expensive mistake in many sessions? If not, move it closer to the task or omit it.

Rule 6: Match authority to the task

A coding agent processes repository text, command output, issue descriptions and sometimes web content. Some of those inputs may be untrusted. Prompt injection is therefore an operational security problem, not merely a prompting problem.

Claude Code provides permission rules and optional filesystem/network sandboxing. The exact starting permission mode varies by configuration and product surface, so do not assume a universal default. Instead, inspect the active policy and apply least privilege:

  • allow only the tools and paths required by the task;
  • deny access to secrets and production credentials;
  • isolate shell commands and network destinations where practical;
  • review commands that upload, deploy, delete or mutate external state;
  • use deterministic hooks for rules that must not depend on model judgment;
  • never treat a successful build as a security review.

Permission is part of the experiment

A result produced with broad filesystem, network and deployment authority has a different risk profile from the same result produced in an isolated worktree or disposable container. Record the execution boundary along with the verification evidence.

Rule 7: Correct early; distinguish checkpoints from version control

Claude Code's current interface allows Esc to interrupt an action and Esc twice or /rewind to open the rewind menu. A checkpoint can restore conversation state, file edits or both, and can summarise part of the conversation.

The boundary matters: checkpoints track edits made through Claude's file-editing tools. Changes produced by shell commands or external processes are not necessarily captured. Checkpoint retention is also finite. Consequently, checkpoints are useful for local experimentation but are not a substitute for Git, backups or a clean worktree.

Before a risky experiment:

  1. inspect git status and separate unrelated changes;
  2. record or commit a known-good state where appropriate;
  3. define the rollback target;
  4. stop and redirect as soon as the agent violates scope;
  5. re-check the working tree after any rewind.

Rule 8: Delegate bounded work, not responsibility

Subagents have isolated contexts, configurable tools and independent permissions. They can prevent a high-volume investigation from filling the main conversation and can provide a fresh review. They also make additional model requests, consume usage limits and may lack conversational context that was not included in their prompt.

Use a subagent when the task is independently answerable and its output can be evaluated: locating an implementation path, comparing a diff with a written specification or reviewing for a named vulnerability class. Avoid delegation when the subtask depends on tacit product decisions, tightly coupled edits or continuous negotiation with the main task.

A useful delegation contract states:

  • the question to answer;
  • the files or evidence it may inspect;
  • the tools it may use;
  • the required output format;
  • what it must not change;
  • how the main agent will verify the result.

Fresh-context review can reduce commitment to the author's approach, but it is not automatically independent in the scientific sense: the reviewer may share the same model family, prompts or blind spots. Human review remains necessary where the consequence justifies it.

Rule 9: Automate only a measured, bounded workflow

Non-interactive mode supports commands such as claude -p and structured output formats for scripts and CI. Parallel sessions can be isolated with Git worktrees so their edits do not collide. These features scale both useful work and failure.

Before automation, make the single-run protocol stable:

ControlQuestion
Input pinningIs the prompt, repository revision and configuration recorded?
AuthorityAre allowed tools, paths, network access and credentials minimal?
TerminationAre turn, time and cost limits explicit?
EvaluationIs success computed by tests or another observable criterion?
IsolationCan concurrent runs overwrite the same files or state?
RecoveryCan a failed run be discarded without damaging the previous state?
AuditabilityAre commands, diffs, outputs and final status retained?

Do not place an open-ended coding prompt directly in a privileged CI environment. Start with a read-only or disposable environment, validate structured output, then widen authority only when the evidence supports it.

A reproducible evaluation protocol

Productivity claims about coding agents are sensitive to task selection, repository state and verification strength. For team adoption, measure the workflow rather than relying on memorable demonstrations.

  1. Select a fixed set of representative tasks, including failures and small maintenance work.
  2. Record the repository commit, tool version, model selection, permissions and prompt.
  3. Define task-specific acceptance tests before the run.
  4. Repeat comparable tasks enough times to expose variance.
  5. Record success, human correction time, changed-file count, test regressions, elapsed time and usage cost.
  6. Inspect failed and apparently successful runs for untested behavior and scope expansion.

SWE-bench established the importance of repository-level evaluation by applying generated patches to real projects and executing issue-specific and regression tests. It does not measure every dimension of production engineering, including security, maintainability, product correctness or the cost of human supervision. Internal evaluation should therefore include those dimensions explicitly.

Failure patterns and their controls

Failure patternObservable symptomPrimary control
Scope driftUnrelated files or behavior changeFile boundary, diff review, stop early
Context pollutionRepeated contradictions or forgotten constraints/clear, focused compaction, shorter evidence
Verification theatreThe agent says “done” without reproducible outputPredeclared commands and captured results
Instruction inflationImportant rules are buried in persistent contextShort core file, scoped rules and skills
Permission inflationConvenience allowlists become broad authorityLeast privilege, sandboxing and deny rules
Unsafe parallelismSessions overwrite or depend on one anotherWorktrees, explicit ownership and integration order
Reviewer confirmationA second agent repeats the author's assumptionsIndependent criteria and adversarial test cases

The durable pattern is straightforward: constrain what the agent is asked to do, constrain what it can do, and require evidence for what it claims to have done. The specific commands will evolve. Those controls remain useful because they address the structure of agentic work rather than the personality of one model release.

References

  1. Best practices for Claude Code — Anthropic's current workflow guidance and the primary source for verification, planning, context management and automation behavior.
  2. How Claude remembers your project — current behavior of CLAUDE.md, AGENTS.md, scoped rules and auto memory.
  3. Extend Claude Code — functional boundaries among memory files, skills, hooks, MCP and subagents.
  4. Checkpointing — checkpoint creation, restore options, retention and limitations.
  5. Create custom subagents — context isolation, permissions, usage and delegation behavior.
  6. Security — permissions, sandboxing, prompt-injection considerations and user responsibility.
  7. CLI reference — authoritative command and flag reference.
  8. Liu et al. (2024), Lost in the Middle: How Language Models Use Long Contexts, Transactions of the Association for Computational Linguistics, 12, 157–173.
  9. Jimenez et al. (2024), SWE-bench: Can Language Models Resolve Real-World GitHub Issues?, ICLR 2024.