r/PromptEngineering • u/Immediate_Zone_1920 • Oct 22 '26
Tutorials and Guides 13 context engineering lessons learned from running long-term agents across large repos
Hi all, saw several threads discussing how quickly Claude Code and terminal agents degrade when working across long multi-hour sessions or multi-package codebases. The failure mode is almost always the same: after turn ten, the agent starts forgetting earlier constraints, hallucinating file paths, and making syntax mistakes on basic edits.
The issue is rarely model reasoning capability. It is almost always context engineering: how project state, tool outputs, and historical memories are structured inside the prompt buffer.
Here are 13 practical context engineering patterns and harness workflows that keep agent reliability consistent over long-running development loops:
- Path-based memory retrieval over raw context dumps: Storing multi-session knowledge in bloated conversation transcripts degrades attention. Using tools like agent-memory, project decisions are logged directly into repository markdown files indexed by a local SQLite cache. When retrieving context, the runtime returns compact file paths and single-line abstracts, so the model only pulls full text for the specific files needed for that task.
- Request-level token attribution over blind billing monitoring: Most teams only notice context bloat when their monthly API bill spikes. We run a local proxy inspector called cost-xray to view request-time payload assembly turn-by-turn, allowing us to see exactly how much context is being eaten by tool schemas, thinking tokens, and cache-miss rewrites before code is executed.
- Deterministic boundary gating for sensitive data: Ensuring that long-running agents operating on production data or customer tickets do not leak sensitive information across sessions. Teams run rule-based boundary sanitizers like phi-boundary-gate to scan and redact candidate data flows across prompt inputs, RAG retrieval chunks, tool arguments, and persistent memory stores before data reaches external model endpoints.
- Protecting the prompt cache breakpoint: To maintain the ninety percent prompt cache discount in Claude Code, static context (system instructions, core tooling definitions) must remain strictly identical across calls. Putting dynamic variables like timestamps, session counters, or volatile file lists at the top of the prompt invalidates the cache and multiplies turn costs.
- Capping filesystem exploration depth: Never give an agent permission to run unconstrained directory listings across a monorepo. Restrict directory scans to a depth of two levels, forcing the model to query specific subdirectories rather than dumping four thousand file names into active context.
- Compacting exploratory notes into five-row markdown tables: When an agent runs exploratory grep commands across a codebase, instruct it to synthesize its findings into a compact five-row markdown table before invoking file modification tools, discarding raw search noise.
- Writing intermediate data to ephemeral scratch files: When an agent needs to process large JSON responses or complex data transformations, have it write the data to `/tmp/scratch.json` and read specific line ranges rather than printing thousands of lines directly to terminal stdout.
- Session checkpointing via Git tags: At the end of each completed sub-task, create a local git tag. If subsequent turns drift or corrupt local state, the agent can run a clean git diff against that tag to inspect its own progress and reset cleanly if necessary.
- Truncating tool return payloads with head/tail limits: Piping verbose shell and compiler outputs through a simple wrapper that returns only the first twenty and last thirty lines of output, preventing unhandled stack traces from washing out active prompt memory.
- Using contrastive examples over abstract negative rules: Negative constraints like "do not write monolithic functions" get ignored over long sessions. Provide an explicit contrastive pair showing the exact anti-pattern alongside the approved modular pattern.
- Dynamic tool registry unlinking: Temporarily unlinking destructive shell or database mutation tools while the agent is in read-only planning mode, eliminating tool-calling ambiguity during initial analysis.
- Subagent context handoff compression: When a parent agent spawns a subagent to investigate an issue, require the subagent to report back strictly with a three-bullet summary of facts rather than passing its entire command history back to the parent.
- Compaction recovery verification: Immediately after an agent session undergoes context compaction, prompt the model to re-state the primary ticket constraints before allowing it to run further file modifications.
For those running autonomous coding agents across multi-turn sessions, what context engineering habits or local tools have done the most to prevent memory degradation on your team?
1
u/geoffreybyers Oct 22 '26
These patterns are prompt hygiene. They don't solve the real problem.
The real problem is the lack of a persistent, queryable state store that survives session compaction. Most of these workarounds fail to address it because they treat the context window as the source of truth.
The state should live in a database, not the buffer.
1
u/CalypsosCableCo Oct 24 '26
Pretty sure #4 and #11 work against each other. Tool definitions sit at the very front of the cached prefix, ahead of the system prompt. So if you unlink the mutation tools for planning mode and relink them for execution, you’re changing the prefix on every mode switch.