Patterns

Repeated problems and preferred moves for code, documentation, testing, review, agents, and source control.

Agent work

Agent steering, constraints, review, and feedback loops.

Ask What Were You Trying To Achieveask-what-were-you-trying-to-achieveRecover the original intent before judging a surprising design. Separating purpose from mechanism makes it easier to preserve useful constraints while replacing stale structure.Avoid Secret Or Private Log Contextavoid-secret-or-private-log-contextDiagnostics can outlive their request and move through systems with different access rules. Record safe identifiers and classifications at the boundary that understands data sensitivity, using explicit protected workflows for rare sensitive evidence.Bootstrap Repo Docsbootstrap-repo-docsRepositories without a documentation map make newcomers infer structure from scattered files and conventions. Add the smallest durable entry points that explain purpose, layout, commands, and where deeper guidance belongs.Budget Tokens For Feedback Loopsbudget-tokens-for-feedback-loopsLong-running agent work can exhaust context before validation, review, or handoff happens. Reserve space for feedback loops by summarizing durable state and avoiding unnecessary transcript growth.Choose Good Enough Toolschoose-good-enough-toolsTooling choices can become a distraction when the available tool is already adequate for the risk. Prefer the simplest tool that gives trustworthy feedback, upgrading only when accuracy, repeatability, or scale requires it.Close The Agent Loopclose-the-agent-loopAgent work is incomplete when it stops at edits without checking the result or explaining residual risk. Finish the loop by validating, reporting evidence, and making the next human decision clear.Code Is Memory Of Processcode-is-memory-of-processCode accumulates the history of decisions, shortcuts, and workflows that produced it. When changing it, preserve useful operational memory while removing obsolete process scars that no longer serve readers.Define Good Before Judgment-Heavy Workdefine-good-before-judgment-heavy-workWork that depends on taste or judgment drifts when success is not defined up front. Establish acceptance criteria, examples, and review dimensions before spending effort on subjective iteration.Deliver Context Just In Timedeliver-context-just-in-timeToo much context up front overloads the reader, while too little context forces rediscovery. Provide the next useful fact at the point of decision, linking outward when deeper background is optional.Distill From Blessed Artifactsdistill-from-blessed-artifactsDurable guidance should come from accepted examples, reviewed decisions, and working artifacts rather than transient preferences. Distill stable lessons from blessed sources and keep uncertain ideas marked as draft.Document System Mental Modelsdocument-system-mental-modelsSystems with implicit concepts force readers to reconstruct how parts fit together from scattered implementation details. Document the mental model that explains ownership, flow, boundaries, and vocabulary before listing procedures.Encode Nonfunctional Requirementsencode-nonfunctional-requirementsPerformance, security, accessibility, privacy, and reliability expectations are easy to lose when they live only in prose. Encode important requirements in tests, budgets, schemas, automation, or review gates where the system can keep enforcing them.Follow Local Conventionsfollow-local-conventionsInconsistent style and structure make each change feel like a new design decision. Start from nearby patterns and only diverge when the local convention cannot support the current need.Garbage Collect Agent Driftgarbage-collect-agent-driftAgent-generated notes, plans, and assumptions can outlive their usefulness and mislead later work. Periodically remove, update, or promote them so durable guidance stays current and temporary scaffolding does not become false context.Give Agents Objectives With Boundariesgive-agents-objectives-with-boundariesAgents perform better when they know both the desired outcome and the limits around scope, authority, and risk. State objectives with concrete boundaries so the agent can act autonomously without expanding the task accidentally.Grant Scoped Agent Capabilitiesgrant-scoped-agent-capabilitiesBroad tool access increases the blast radius of agent mistakes and makes review harder. Grant the smallest capabilities needed for the current task, then expand deliberately when the work proves it needs more reach.Isolate Agent Workspacesisolate-agent-workspacesShared worktrees make it easy for agent edits, generated files, or validation steps to collide with unrelated work. Use isolated workspaces when concurrent tasks or uncertain changes need clear ownership and cleanup.Keep Automations Repo Ownedkeep-automations-repo-ownedCritical checks and generation steps become fragile when they live only in personal scripts or local memory. Put repeatable automation in the repository so agents and humans can run the same workflow.Keep Secrets Out Of Contextkeep-secrets-out-of-contextSecrets and private data can leak through prompts, transcripts, logs, and generated artifacts even when the code change is harmless. Redact or replace sensitive values before they enter shared context, and use controlled channels when real secrets are required.Limit Live Contextlimit-live-contextReaders make mistakes when they must keep too many facts active to understand a change. Reduce live context by moving related facts together, naming intermediate concepts, and keeping dependencies local.Make Bad Output Mechanically Hardmake-bad-output-mechanically-hardRepeated review failures usually belong in a tool, type, schema, template, lint, or checklist instead of another reminder. Encode stable rejection criteria early, but keep escape hatches when legitimate exceptions are common.Make Plans Versioned Artifactsmake-plans-versioned-artifactsChat-only plans are difficult to review, resume, cite, or keep current once work spans sessions. Put substantial plans in the repository with goals, constraints, progress, decisions, and open questions, while keeping obvious one-step edits lightweight.Make Runtime State Agent Legiblemake-runtime-state-agent-legibleAgents can only validate behavior reliably when the relevant runtime state is observable through their tools. Expose the smallest useful signal first, such as app boot, UI inspection, logs, metrics, screenshots, traces, or generated artifacts.Manage Agent Work Not Sessionsmanage-agent-work-not-sessionsInteractive sessions do not scale when the maintainer must remember every thread, terminal, and handoff. Represent agent work as durable tasks with states, owners, validation, and review criteria so humans spend attention on priorities and judgment.Optimize For Agent Legibilityoptimize-for-agent-legibilityRepositories that are hard for agents to inspect, search, run, and validate make delegated work slower and less reliable. Prefer structures, commands, names, examples, and runtime signals that help both agents and human maintainers reason locally.Optimize For Long Term Coherenceoptimize-for-long-term-coherenceAgent-produced work can satisfy a prompt while weakening the systems future concepts, names, boundaries, and tests. Choose the smallest change that preserves long-term direction without using coherence as an excuse for speculative architecture.Practice Agent Workoutspractice-agent-workoutsHigh-risk or repeated agent workflows are unreliable when first exercised during real work. Build safe practice tasks with explicit win conditions so the workflow, skill, or runbook can improve before pressure arrives.Prefer Durable Summariesprefer-durable-summariesImportant context is costly when every reader must rediscover it from implementation details, but exhaustive narration becomes stale. Capture stable invariants, rationale, boundaries, or side effects in short summaries that survive nearby changes.Prefer In Distribution Toolsprefer-in-distribution-toolsUnusual tools, layouts, and formats consume agent attention before domain work begins. Prefer common, stable conventions when they meet the need, and document specialized choices when the domain honestly requires them.Prefer Tools Over Promptsprefer-tools-over-promptsProse instructions are weak guardrails for repeatable constraints because agents can forget or apply them too late. Use tools, tests, templates, and checks for mechanical preferences, while reserving prompts for judgment and tradeoffs.Preserve Agent Context Coherencepreserve-agent-context-coherenceMixing unrelated work pollutes the sessions attention, working-copy state, and handoff narrative. Keep each session and jj change focused on one purpose, splitting work when ownership, validation, or review decisions diverge.Preserve Intent Over Literalismpreserve-intent-over-literalismLiteral compliance can violate the users actual goal when a request touches risky, privileged, or externally visible actions. Infer the safe operating intent and stop when policy, review expectations, or irreversible consequences conflict with the words alone.Preserve Local Doc Voicepreserve-local-doc-voiceDocumentation edits can become bland or mismatched even when they are grammatically correct. Patch only what needs changing while keeping local terms, structure, density, and tone unless the existing voice blocks clarity or accessibility.Preserve Unowned Workpreserve-unowned-workShared working copies may contain edits from another person or an earlier task. Check state before editing, work around unrelated changes, and stop for direction when unowned work blocks the current change.Produce Review Packetsproduce-review-packetsReviewers lose time when a handoff contains only a diff and no acceptance evidence. Package the goal, validation, risks, and proof artifact in proportion to the review burden.Prove Security Impactprove-security-impactSecurity reports create noise when they imply exploitability without showing reachability or consequence. Prove the attacker path and impact, or clearly label the finding as an unproven hypothesis.Record Agent Operating Lessonsrecord-agent-operating-lessonsAgent work produces useful operational knowledge that is easy to lose after the task succeeds or fails. Record reusable lessons in the right durable place so future runs inherit the improved workflow instead of rediscovering it.Report Verification Honestlyreport-verification-honestlyHandoffs become risky when verification is overstated, omitted, or blurred with assumptions. Report exactly what ran, what passed or failed, what was not checked, and what risk remains.Review Proof Not Just Codereview-proof-not-just-codeCode review is weaker when it inspects the diff without checking whether the claimed behavior was proven. Ask for the smallest trustworthy evidence that the change works and that the likely failure mode was covered.Separate Discovery From Editingseparate-discovery-from-editingEditing while still discovering the system can bake early misunderstandings into the diff. Read enough to find the ownership, constraints, and likely change shape before making scoped edits.Shape Tool Output For Agentsshape-tool-output-for-agentsHuman-oriented tool output can bury the failure signal an agent needs to act. Prefer quiet summaries, structured output, and saved full logs so agents see the actionable slice first without losing debugging context.Spend Human Attention On Ambiguityspend-human-attention-on-ambiguityAgent throughput can exceed the maintainers ability to review and steer. Delegate execution and inspection, but reserve human attention for ambiguous goals, taste, architecture, risk, and the systems that make future delegation safer.Teach Agents Through Toolsteach-agents-through-toolsRepeated agent confusion often means the repo lacks a command, fixture, wrapper, or check rather than another instruction. Convert repeatable setup, inspection, validation, and remediation into tools when they will improve future runs.Turn Feedback Into Guidanceturn-feedback-into-guidanceRepeated steering signals that a preference is missing from durable repo guidance or tooling. Fix the current artifact and encode the reusable lesson at the right level when the feedback applies beyond one line.Use AGENTS.md As Mapuse-agents-md-as-mapA giant AGENTS.md grows stale and crowds out the context the agent actually needs. Keep it as a compact map to canonical guides, patterns, commands, and safety rules, with details living in owned files.Use Disk As Context Sinkuse-disk-as-context-sinkLarge pasted context is difficult to search, diff, summarize, and revisit. Put bulky or reusable context on disk so agents can pull the relevant slice while the thread stays focused on decisions and handoff.Use Narrow Agent Reviewersuse-narrow-agent-reviewersBroad review prompts often miss specific risks or return vague feedback. Add focused agent reviewers for important, repeatable concerns when narrow context will produce more useful findings than another general pass.Verify With Canaries Before Cutoververify-with-canaries-before-cutoverAutomation is risky when production cutover is the first real proof. Use a canary path, rollback plan, and human approval for operations with remote access, credentials, production data, or long-lived service impact.

Documentation and shared context

Docs as contracts, source prose, examples, summaries, and review context.

Choose Doc Pass Depthchoose-doc-pass-depthDocumentation work ranges from quick polish to structural repair, and using the wrong pass depth wastes attention. Match the edit depth to the evidence, risk, and review need before changing the document.Choose Doc Typechoose-doc-typeA documentation need can call for a guide, reference, tutorial, decision record, or checklist, and mixing those jobs makes docs harder to use. Pick the type that fits the readers task before deciding structure or tone.Commit Messages For Historycommit-messages-for-historyCommit messages become future debugging and review aids, not just publication labels. Write them to explain the reason and effect of the change, with enough context to survive outside the original conversation.Delete Redundant Commentsdelete-redundant-commentsComments that repeat obvious code add reading burden and become stale faster than the behavior they describe. Remove them or replace them with context that explains intent, invariant, risk, or non-obvious tradeoff.Document Errors Panics Safetydocument-errors-panics-safetyCallers need to know which failures are recoverable, which conditions panic, and what safety obligations an API imposes. Document those contracts at the public boundary so users can compose the API deliberately.Document Intentional Non Goalsdocument-intentional-non-goalsReaders may treat missing behavior as oversight when the absence was a deliberate scope choice. Record important non-goals where they prevent repeated debate or misuse without turning the document into a defensive catalog.Keep Docs Near Their Subjectkeep-docs-near-their-subjectDocumentation drifts when it is far from the code, policy, or workflow it explains. Let shared rationale rise to the nearest stable owner while item docs retain their local contracts, differences, edge cases, and side effects.Keep Name Currentkeep-name-currentNames that preserve old intent make readers distrust the code or documentation around them. Rename when the concept changes enough that the old name now teaches the wrong model.Label Doc Claims By Evidencelabel-doc-claims-by-evidenceDocumentation loses trust when speculation, observed behavior, policy, and verified facts look the same. Label claims by their evidence level so readers know what can be relied on and what still needs confirmation.Make Side Effects Visiblemake-side-effects-visibleCallers need to know when an operation touches persistence, networks, time, global state, caches, metrics, processes, or other external systems. Make caller-relevant effects visible in names, docs, or examples without documenting implementation noise.Prefer 100-Column Prose Wrapprefer-100-column-prose-wrapWrap Markdown prose and Markdown-bearing doc comments around 100 columns as a maintainer readability preference. The exact number is subjective, but it balances source reading, monospace density, review diffs, and common screen sizes better than 80 or 120 columns.Reconstruct Rationale Before Writingreconstruct-rationale-before-writingExplanations become plausible stories when writers infer intent from current code and consult history only to fill gaps. Reconstruct the decision from present behavior, introducing and corrective changes, tests, measurements, and discussion before drafting the durable account.Remediate Doc Driftremediate-doc-driftDocumentation drift misleads readers when behavior, workflow, or project shape has moved on. Fix the source of truth and nearby references together, choosing whether the code or the doc represents the intended contract.Run Rustdoc Quality Passrun-rustdoc-quality-passUse a bounded checklist when raising a Rust crates public documentation. The pass should teach the crate model, document public contracts, place examples where they prove real use, keep documentation layers aligned, and validate Rustdoc as code.Run Source Explanation Passrun-source-explanation-passTurn a source tree into a self-contained reading environment by recovering its mental models, fundamentals, decisions, constraints, and edge cases. Establish the system map before item detail, audit every relevant helper and path, and measure success through reader comprehension rather than comment count.Write Actionable Error Messageswrite-actionable-error-messagesAccurate error messages can still leave users, operators, callers, or support unable to act. Design failure output so the audience can find the attempted operation, affected item, known cause, impact, next step, and diagnostic handle when those facts matter.Write Docs As Contractswrite-docs-as-contractsBehavior and obligations become surprising when they are only discoverable by reading implementation details. Treat docs as part of the change surface, updating contracts and rationale alongside the code they describe.Write PR Narrativewrite-pr-narrativeA correct diff can still waste reviewer attention when it lacks purpose, risk, review order, and verification. Write the PR narrative as a guide to the decision the reviewer needs to make, scaled to the burden of the change.

Code shape and APIs

Reader-local code, Rust APIs, naming, state shape, and refactoring.

Avoid Boolean Flag Parametersavoid-boolean-flag-parametersBehavioral boolean flags make call sites depend on hidden ordering and branch semantics. Distinguish them from boolean domain data, then prefer named operations, enums, options types, or builders when the caller selects behavior.Cap Change Radiuscap-change-radiusBroad diffs increase review cost and make unrelated regressions harder to isolate. Keep the change radius aligned with the requested behavior, using separate chunks for cleanup or adjacent improvements.Chunk Statementschunk-statementsDense prose asks readers to hold too many claims at once and hides which idea needs review. Split statements into coherent chunks so each paragraph, bullet, or sentence carries one inspectable purpose.Contain Observability Policycontain-observability-policyLogging, metrics, tracing, and privacy choices become inconsistent when every call site invents its own policy. Put observability decisions at owned boundaries so lower layers expose facts without duplicating policy.Inject Time And Randomnessinject-time-and-randomnessDirect reads of clocks and random sources make behavior hard to reproduce, test, and explain. Pass time and randomness through explicit seams at the boundary where nondeterminism is chosen.Keep Async Boundaries Explicitkeep-async-boundaries-explicitHidden async work obscures cancellation, ordering, resource ownership, and failure behavior. Make task spawning, awaiting, retries, and background ownership visible at the boundary where callers need to reason about them.Keep Public Dependencies Intentionalkeep-public-dependencies-intentionalPublic dependencies shape downstream compatibility, API expectations, and maintenance cost. Add or raise them only when the public behavior needs that requirement, using lockfile updates for ordinary compatible refreshes.Keep Structure Reversiblekeep-structure-reversibleEarly structure can harden into unnecessary abstraction before the design is proven. Prefer arrangements that are easy to inline, split, merge, or rename until the underlying concept earns permanence.Log At Owned Boundarieslog-at-owned-boundariesLogs become noisy and inconsistent when every helper records the same failure from a partial viewpoint. Log where the code owns the operation and can attach useful, safe diagnostic context.Make Failures Observablemake-failures-observableErrors without diagnostic context force future readers and operators to rediscover what failed. Preserve typed errors while adding operation context, correlation, metrics, or logs at the boundary that owns the meaning.Make Invalid States Hard To Expressmake-invalid-states-hard-to-expressRepeated validation spreads invariants across callers and lets unchecked values travel too far. Move the rule into a construction boundary or precise type when that reduces downstream reasoning without adding local ceremony.Make Parameters Explicitmake-parameters-explicitHidden configuration, time, randomness, globals, or environment reads make behavior hard to reason about and test. Gather ambient data at the outer boundary, then pass typed inputs or a cohesive context to the inner operation.Make State Transitions Explicitmake-state-transitions-explicitLifecycle rules become fragile when status fields, timestamps, events, and validation checks are coordinated by hand. Give meaningful transitions a named owner that holds the preconditions, state update, event, and error behavior together.Make The Change Easy Firstmake-the-change-easy-firstSome changes are risky because the path to make or verify them is unnecessarily hard. First add the smallest harness, boundary, helper, tool, or runbook that makes the real change cheaper to understand and review.Make Validation Policy Explicitmake-validation-policy-explicitValidation rules often differ by workflow even when they touch the same field. Name the policy at the boundary with distinct constructors, modes, policy types, or parsed values once real competing rules exist.Move Declaration And Initialization Togethermove-declaration-and-initialization-togetherA value declared before it is valid makes readers track an empty slot and its future assignment. Declare values where they become meaningful, using immutable locals and narrow scopes unless evaluation order requires more care.Name Couplingname-couplingRelationships between pieces are hard to judge when the reason they change together is unnamed. Describe the change pressure first, then decide whether the coupling belongs directly, behind a clearer owner, or across an explicit boundary.Parse Dont Validateparse-dont-validateValidation that returns raw values forces callers to remember which invariants already hold. Parse uncertain input into types that carry those invariants, using constructors or standard parsing traits that honestly match the boundary.Prefer Standard Conversionsprefer-standard-conversionsProject-specific conversion names make APIs harder to predict when standard traits already describe the relationship. Use standard conversions only when their semantics are honest, and choose explicit domain methods for lossy, contextual, or surprising operations.Reader Localityreader-localityA change can reduce code size while increasing the number of jumps needed to understand one workflow. Keep related concepts near their meaning, extracting only when the new name and location reduce live context.Return Structured Errorsreturn-structured-errorsString-only errors hide the stable facts callers need for branching, retrying, logging, and support. Return structured error values with machine-readable kinds and context, then render audience-specific messages at the boundary.Separate Structure From Behaviorseparate-structure-from-behaviorDiffs that mix moves, renames, formatting, and behavior make review and rollback harder. Separate behavior-preserving structure from rule changes when each can be checked on its own.Strengthen Cohesionstrengthen-cohesionA concept becomes harder to understand when its data, rules, and behavior are scattered or bundled with unrelated concerns. Move elements that change for the same reason toward one named owner, while separating nearby code that belongs to another concept.Untangle Before Changinguntangle-before-changingBehavior changes become risky when policy, formatting, validation, persistence, and side effects are braided together. Untangle only enough structure to give the new behavior a clear owner, then keep the behavior change reviewable.Use Explaining Variableuse-explaining-variableImportant decisions disappear when nested expressions or repeated conditions expose syntax before domain meaning. Introduce a local name when it makes the next branch, call, or return read in terms of the fact the reader needs.Use Guard Clauseuse-guard-clauseThe normal path is harder to see when the rest of a routine is indented under a precondition or failure case. Exit early for boring gates so the ordinary behavior stays flat, visible, and ordered by what readers must rule out.

Boundaries, failure, and verification

Parsing, validation, errors, observability, tests, and runtime proof.

Change and review workflow

Review size, source control, sequencing, and collaboration.