1
---
2
name: filesystem-context
3
description: "This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt."
4
---
5
6
# Filesystem-Based Context Engineering
7
8
Use the filesystem as the primary overflow layer for agent context because context windows are limited while tasks often require more information than fits in a single window. Files let agents store, retrieve, and update an effectively unlimited amount of context through a single interface.
9
10
Prefer dynamic context discovery -- pulling relevant context on demand -- over static inclusion, because static context consumes tokens regardless of relevance and crowds out space for task-specific information.
11
12
## When to Activate
13
14
Activate this skill when:
15
- Tool outputs are bloating the context window
16
- Agents need to persist state across long trajectories
17
- Sub-agents must share information without direct message passing
18
- Tasks require more context than fits in the window
19
- Building agents that learn and update their own instructions
20
- Implementing scratch pads for intermediate results
21
- Terminal outputs or logs need to be accessible to agents
22
23
Do not activate this skill for adjacent work owned by other skills:
24
- Semantic cross-session memory, entity tracking, or temporal knowledge graphs: `memory-systems`.
25
- Conversation summarization, compaction, or durable handoff wording: `context-compression`.
26
- Token-efficiency tactics that do not require file-backed storage: `context-optimization`.
27
- Multi-agent topology or handoff protocol design: `multi-agent-patterns`.
28
- Model edits that evict content from the live window itself: `self-managed-context`.
29
30
## Core Concepts
31
32
Diagnose context failures against these four modes, because each requires a different filesystem remedy:
33
34
1. **Missing context** -- needed information is absent from the total available context. Fix by persisting tool outputs and intermediate results to files so nothing is lost.
35
2. **Under-retrieved context** -- retrieved content fails to encapsulate what the agent needs. Fix by structuring files for targeted retrieval (grep-friendly formats, clear section headers).
36
3. **Over-retrieved context** -- retrieved content far exceeds what is needed, wasting tokens and degrading attention. Fix by offloading bulk content to files and returning compact references.
37
4. **Buried context** -- niche information is hidden across many files. Fix by combining glob and grep for structural search alongside semantic search for conceptual queries.
38
39
Use the filesystem as the persistent layer that addresses all four: write once, store durably, retrieve selectively.
40
41
## Detailed Topics
42
43
### The Static vs Dynamic Context Trade-off
44
45
Treat static context (system instructions, tool definitions, critical rules) as expensive real estate -- it consumes tokens on every turn regardless of relevance. As agents accumulate capabilities, static context grows and crowds out dynamic information.
46
47
Use dynamic context discovery instead: include only minimal static pointers (names, one-line descriptions, file paths) and load full content with search tools when relevant. This is more token-efficient and often improves response quality by reducing contradictory or irrelevant information in the window.
48
49
Accept the trade-off: dynamic discovery requires the model to recognize when it needs more context. Current frontier models handle this well, but less capable models may fail to trigger loads. When in doubt, err toward including critical safety or correctness constraints statically.
50
51
### Pattern 1: Filesystem as Scratch Pad
52
53
Redirect large tool outputs to files instead of returning them directly to context, because a single web search or database query can dump thousands of tokens into message history where they persist for the entire conversation.
54
55
Write the output to a scratch file, extract a compact summary, and return a file reference. The agent then uses targeted retrieval (grep for patterns, read with line ranges) to access only what it needs.
56
57
```python
58
def handle_tool_output(output: str, threshold: int = 2000) -> str:
59
if len(output) < threshold:
60
return output
61
62
file_path = f"scratch/{tool_name}_{timestamp}.txt"
63
write_file(file_path, output)
64
65
key_summary = extract_summary(output, max_tokens=200)
66
return f"[Output written to {file_path}. Summary: {key_summary}]"
67
```
68
69
Use grep to search the offloaded file and read_file with line ranges to retrieve targeted sections, because this preserves full output for later reference while keeping only ~100 tokens in the active context.
70
71
### Pattern 2: Plan Persistence
72
73
Write plans to the filesystem because long-horizon tasks lose coherence when plans fall out of attention or get summarized away. The agent re-reads its plan at any point, restoring awareness of the objective and progress.
74
75
Store plans in structured format so they are both human-readable and machine-parseable:
76
```yaml
77
# scratch/current_plan.yaml
78
objective: "Refactor authentication module"
79
status: in_progress
80
steps:
81
- id: 1
82
description: "Audit current auth endpoints"
83
status: completed
84
- id: 2
85
description: "Design new token validation flow"
86
status: in_progress
87
- id: 3
88
description: "Implement and test changes"
89
status: pending
90
```
91
92
Re-read the plan at the start of each turn or after any context refresh to re-orient, because this acts as "manipulating attention through recitation."
93
94
### Pattern 3: Sub-Agent Communication via Filesystem
95
96
Route sub-agent findings through the filesystem instead of message passing, because multi-hop message chains degrade information through summarization at each hop ("game of telephone").
97
98
Have each sub-agent write directly to its own workspace directory. The coordinator reads these files directly, preserving full fidelity:
99
```
100
workspace/
101
agents/
102
research_agent/
103
findings.md
104
sources.jsonl
105
code_agent/
106
changes.md
107
test_results.txt
108
coordinator/
109
synthesis.md
110
```
111
112
Enforce per-agent directory isolation to prevent write conflicts and maintain clear ownership of each output artifact.
113
114
### Pattern 4: Dynamic Skill Loading
115
116
Store skills as files and include only skill names with brief descriptions in static context, because stuffing all instructions into the system prompt wastes tokens and can confuse the model with contradictory guidance.
117
118
```
119
Available skills (load with read_file when relevant):
120
- database-optimization: Query tuning and indexing strategies
121
- api-design: REST/GraphQL best practices
122
- testing-strategies: Unit, integration, and e2e testing patterns
123
```
124
125
Load the full skill file (e.g., `skills/database-optimization/SKILL.md`) only when the current task requires it. This converts O(n) static token cost into O(1) per task.
126
127
### Pattern 5: Terminal and Log Persistence
128
129
Persist terminal output to files automatically and use grep for selective retrieval, because terminal output from long-running processes accumulates rapidly and manual copy-paste is error-prone.
130
131
```
132
terminals/
133
1.txt # Terminal session 1 output
134
2.txt # Terminal session 2 output
135
```
136
137
Query with targeted grep (`grep -A 5 "error" terminals/1.txt`) instead of loading entire terminal histories into context.
138
139
### Pattern 6: Learning Through Self-Modification
140
141
Have agents write learned preferences and patterns to their own instruction files so subsequent sessions load this context automatically, instead of requiring manual system prompt updates.
142
143
```python
144
def remember_preference(key: str, value: str):
145
preferences_file = "agent/user_preferences.yaml"
146
prefs = load_yaml(preferences_file)
147
prefs[key] = value
148
write_yaml(preferences_file, prefs)
149
```
150
151
Guard this pattern with validation because self-modification can accumulate incorrect or contradictory instructions over time. Treat it as experimental -- review persisted preferences periodically.
152
153
### Filesystem Search Techniques
154
155
Combine `ls`/`list_dir`, `glob`, `grep`, and `read_file` with line ranges for context discovery, because models are specifically trained on filesystem traversal and this combination often outperforms semantic search for technical content where structural patterns are clear.
156
157
- `ls` / `list_dir`: Discover directory structure
158
- `glob`: Find files matching patterns (e.g., `**/*.py`)
159
- `grep`: Search file contents, returns matching lines with context
160
- `read_file` with ranges: Read specific sections without loading entire files
161
162
Use filesystem search for structural and exact-match queries, and semantic search for conceptual queries. Combine both for comprehensive discovery.
163
164
## Practical Guidance
165
166
### When to Use Filesystem Context
167
168
Apply filesystem patterns when the situation matches these criteria, because they add I/O overhead that is only justified by token savings or persistence needs:
169
170
**Use when:**
171
- Tool outputs exceed ~2000 tokens
172
- Tasks span multiple conversation turns
173
- Multiple agents need shared state
174
- Skills or instructions exceed comfortable system prompt size
175
- Logs or terminal output need selective querying
176
177
**Avoid when:**
178
- Tasks complete in single turns (overhead not justified)
179
- Context fits comfortably in window (no problem to solve)
180
- Latency is critical (file I/O adds measurable delay)
181
- Model lacks filesystem tool capabilities
182
183
### File Organization
184
185
Structure files for agent discoverability, because agents navigate by listing and reading directory names:
186
```
187
project/
188
scratch/ # Temporary working files
189
tool_outputs/ # Large tool results
190
plans/ # Active plans and checklists
191
memory/ # Persistent learned information
192
preferences.yaml # User preferences
193
patterns.md # Learned patterns
194
skills/ # Loadable skill definitions
195
agents/ # Sub-agent workspaces
196
```
197
198
Use consistent naming conventions and include timestamps or IDs in scratch files for disambiguation.
199
200
For autonomous research loops, store raw retrieved evidence under the run that consumed it, for example `researcher/runs/<run-id>/sources/evidence/raw/`. Do not leave raw research dumps in the repository root; root-level artifacts become hard to audit and easy to cite without provenance.
201
202
### Token Accounting
203
204
Measure where tokens originate before and after applying filesystem patterns, because optimizing without measurement leads to wasted effort:
205
- Track static vs dynamic context ratio
206
- Monitor tool output sizes before and after offloading
207
- Measure how often dynamically-loaded context is actually used
208
209
## Examples
210
211
**Example 1: Tool Output Offloading**
212
```
213
Input: Web search returns 8000 tokens
214
Before: 8000 tokens added to message history
215
After:
216
- Write to scratch/search_results_001.txt
217
- Return: "[Results in scratch/search_results_001.txt. Key finding: API rate limit is 1000 req/min]"
218
- Agent greps file when needing specific details
219
Result: ~100 tokens in context, 8000 tokens accessible on demand
220
```
221
222
**Example 2: Dynamic Skill Loading**
223
```
224
Input: User asks about database indexing
225
Static context: "database-optimization: Query tuning and indexing"
226
Agent action: read_file("skills/database-optimization/SKILL.md")
227
Result: Full skill loaded only when relevant
228
```
229
230
**Example 3: Chat History as File Reference**
231
```
232
Trigger: Context window limit reached, summarization required
233
Action:
234
1. Write full history to history/session_001.txt
235
2. Generate summary for new context window
236
3. Include reference: "Full history in history/session_001.txt"
237
Result: Agent can search history file to recover details lost in summarization
238
```
239
240
## Guidelines
241
242
1. Write large outputs to files; return summaries and references to context
243
2. Store plans and state in structured files for re-reading
244
3. Use sub-agent file workspaces instead of message chains
245
4. Load skills dynamically rather than stuffing all into system prompt
246
5. Persist terminal and log output as searchable files
247
6. Combine grep/glob with semantic search for comprehensive discovery
248
7. Organize files for agent discoverability with clear naming
249
8. Measure token savings to validate filesystem patterns are effective
250
9. Implement cleanup for scratch files to prevent unbounded growth
251
10. Guard self-modification patterns with validation
252
11. Keep raw evidence next to the run, evaluation, and proposal that used it
253
254
## Gotchas
255
256
1. **Scratch directory unbounded growth**: Agents create temp files without cleanup, eventually consuming disk and making directory listings noisy. Implement a retention policy (age-based or count-based) and run cleanup at session boundaries.
257
2. **Race conditions in multi-agent file access**: Concurrent writes to the same file corrupt state silently. Enforce per-agent directory isolation or use append-only files with agent-prefixed entries.
258
3. **Stale file references after moves/renames**: Agents hold paths from prior turns that no longer exist after refactors or file reorganization. Always verify file existence before reading a cached path; re-discover with glob if the check fails.
259
4. **Glob pattern false matches**: Overly broad patterns (e.g., `**/*`) pull irrelevant files into context, wasting tokens and confusing the model. Scope globs to specific directories and extensions.
260
5. **File size assumptions**: Reading a file without checking size can dump 100K+ tokens into context in a single tool call. Check file size before reading; use line-range reads for large files.
261
6. **Missing file existence checks**: Agents assume files exist from prior turns, but they may have been deleted or moved. Always guard reads with existence checks and handle missing-file errors gracefully.
262
7. **Scratch pad format drift**: Unstructured scratch pads become unparseable after many writes because format conventions erode over successive appends. Define and enforce a schema (YAML, JSON, or structured markdown) from the first write.
263
8. **Hardcoded absolute paths**: Break when repositories are checked out at different locations or when running in containers. Use relative paths from the project root or resolve paths dynamically.
264
265
## Integration
266
267
This skill owns file-backed context storage and retrieval. Adjacent skills own semantic memory, summarization, and topology:
268
269
- `context-optimization`: filesystem offloading is one implementation of observation masking when full outputs remain retrievable.
270
- `memory-systems`: use when file-backed notes are no longer enough and semantic, entity, or temporal retrieval is required.
271
- `multi-agent-patterns`: sub-agent file workspaces enable context isolation and direct handoff.
272
- `context-compression`: file references can anchor summaries and preserve details omitted from compressed context.
273
- `tool-design`: tools should return file references for large outputs and expose safe read/search operations.
274
- `self-managed-context`: offloading leaves the original in the live window; evicting it requires the model to edit its own context.
275
276
## References
277
278
Internal reference:
279
- [Implementation Patterns](./references/implementation-patterns.md) - Read when: implementing scratch pad, plan persistence, or tool output offloading and need concrete code beyond the inline examples
280
281
Related skills in this collection:
282
- context-optimization - Read when: applying token reduction techniques alongside filesystem offloading
283
- memory-systems - Read when: building persistent storage that outlasts a single session
284
- multi-agent-patterns - Read when: designing agent coordination with shared file workspaces
285
286
External resources:
287
- LangChain Deep Agents — Read when: implementing filesystem-based context patterns in LangChain/LangGraph pipelines
288
- Cursor context discovery — Read when: studying how production IDEs implement dynamic context loading
289
- Anthropic Agent Skills specification — Read when: building skills that leverage filesystem progressive disclosure
290
291
---
292
293
## Skill Metadata
294
295
**Created**: 2026-01-07
296
**Last Updated**: 2026-05-15
297
**Author**: Agent Skills for Context Engineering Contributors
298
**Version**: 1.2.0
299