filesystem-context
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFilesystem-Based Context Engineering
基于文件系统的上下文工程
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.
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.
使用文件系统作为Agent上下文的主要溢出层,因为上下文窗口有限,而任务通常需要的信息量超过单个窗口所能容纳。文件让Agent能够通过单一界面存储、检索和更新几乎无限量的上下文。
优先采用动态上下文发现——按需拉取相关上下文——而不是静态包含,因为静态上下文无论相关与否都会消耗token,并挤占任务特定信息的空间。
When to Activate
何时激活
Activate this skill when:
- Tool outputs are bloating the context window
- Agents need to persist state across long trajectories
- Sub-agents must share information without direct message passing
- Tasks require more context than fits in the window
- Building agents that learn and update their own instructions
- Implementing scratch pads for intermediate results
- Terminal outputs or logs need to be accessible to agents
Do not activate this skill for adjacent work owned by other skills:
- Semantic cross-session memory, entity tracking, or temporal knowledge graphs: .
memory-systems - Conversation summarization, compaction, or durable handoff wording: .
context-compression - Token-efficiency tactics that do not require file-backed storage: .
context-optimization - Multi-agent topology or handoff protocol design: .
multi-agent-patterns
在以下情况下激活此skill:
- 工具输出使上下文窗口膨胀
- Agent需要在长轨迹中持久化状态
- 子Agent需要无需直接消息传递即可共享信息
- 任务需要的上下文超过窗口容量
- 构建能够学习并更新自身指令的Agent
- 实现中间结果的临时记事本
- 终端输出或日志需要被Agent访问
不要将此skill用于其他skill负责的相关工作:
- 语义跨会话记忆、实体跟踪或时间知识图谱:。
memory-systems - 对话摘要、压缩或持久化交接措辞:。
context-compression - 不需要文件支持的存储的token效率策略:。
context-optimization - 多Agent拓扑或交接协议设计:。
multi-agent-patterns
Core Concepts
核心概念
Diagnose context failures against these four modes, because each requires a different filesystem remedy:
- 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.
- 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).
- 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.
- Buried context -- niche information is hidden across many files. Fix by combining glob and grep for structural search alongside semantic search for conceptual queries.
Use the filesystem as the persistent layer that addresses all four: write once, store durably, retrieve selectively.
根据以下四种模式诊断上下文失败,因为每种模式都需要不同的文件系统补救措施:
- 缺失上下文 —— 所需信息在总可用上下文中不存在。解决方法:将工具输出和中间结果持久化到文件,确保不丢失任何内容。
- 检索不足的上下文 —— 检索到的内容无法涵盖Agent的需求。解决方法:将文件组织为便于定向检索的结构(grep友好的格式、清晰的章节标题)。
- 过度检索的上下文 —— 检索到的内容远超所需,浪费token并降低注意力质量。解决方法:将批量内容卸载到文件中,返回紧凑的引用。
- 被埋没的上下文 —— 小众信息隐藏在众多文件中。解决方法:结合glob和grep进行结构化搜索,同时使用语义搜索处理概念性查询。
使用文件系统作为解决这四种问题的持久层:写入一次、持久存储、选择性检索。
Detailed Topics
详细主题
The Static vs Dynamic Context Trade-off
静态与动态上下文的权衡
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.
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.
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.
将静态上下文(系统指令、工具定义、关键规则)视为昂贵的不动产——它每轮都消耗token,无论是否相关。随着Agent能力积累,静态上下文不断增长,挤占动态信息的空间。
改用动态上下文发现:仅包含最小的静态指针(名称、一行描述、文件路径),并在相关时使用搜索工具加载完整内容。这更节省token,通常还能通过减少窗口中矛盾或不相关的信息来提高响应质量。
接受权衡:动态发现要求模型识别自身何时需要更多上下文。当前前沿模型处理得很好,但能力较弱的模型可能无法触发加载。如有疑虑,倾向于将关键的安全或正确性约束静态包含。
Pattern 1: Filesystem as Scratch Pad
模式1:文件系统作为临时记事本
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.
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.
python
def handle_tool_output(output: str, threshold: int = 2000) -> str:
if len(output) < threshold:
return output
file_path = f"scratch/{tool_name}_{timestamp}.txt"
write_file(file_path, output)
key_summary = extract_summary(output, max_tokens=200)
return f"[Output written to {file_path}. Summary: {key_summary}]"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.
将大型工具输出重定向到文件,而不是直接返回上下文,因为一次网络搜索或数据库查询就可能向消息历史倾倒数千token,并在此处保留整个对话过程。
将输出写入临时文件,提取紧凑摘要,返回文件引用。Agent随后使用定向检索(grep模式、按行范围读取)只访问所需内容。
python
def handle_tool_output(output: str, threshold: int = 2000) -> str:
if len(output) < threshold:
return output
file_path = f"scratch/{tool_name}_{timestamp}.txt"
write_file(file_path, output)
key_summary = extract_summary(output, max_tokens=200)
return f"[Output written to {file_path}. Summary: {key_summary}]"使用grep搜索已卸载的文件,并使用带行范围的read_file检索定向章节,因为这保留了完整输出供后续引用,同时仅保留约100个token在活动上下文中。
Pattern 2: Plan Persistence
模式2:计划持久化
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.
Store plans in structured format so they are both human-readable and machine-parseable:
yaml
undefined将计划写入文件系统,因为长期任务在计划脱离注意力或被摘要化后容易失去连贯性。Agent可以在任何时点重新阅读计划,恢复对目标和进度的感知。
以结构化格式存储计划,使其既可读又可机解析:
yaml
undefinedscratch/current_plan.yaml
scratch/current_plan.yaml
objective: "Refactor authentication module"
status: in_progress
steps:
- id: 1 description: "Audit current auth endpoints" status: completed
- id: 2 description: "Design new token validation flow" status: in_progress
- id: 3 description: "Implement and test changes" status: pending
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."objective: "Refactor authentication module"
status: in_progress
steps:
- id: 1 description: "Audit current auth endpoints" status: completed
- id: 2 description: "Design new token validation flow" status: in_progress
- id: 3 description: "Implement and test changes" status: pending
在每轮开始时或任何上下文刷新后重新阅读计划以重新定位,因为这相当于“通过复述操纵注意力”。Pattern 3: Sub-Agent Communication via Filesystem
模式3:通过文件系统进行子Agent通信
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").
Have each sub-agent write directly to its own workspace directory. The coordinator reads these files directly, preserving full fidelity:
workspace/
agents/
research_agent/
findings.md
sources.jsonl
code_agent/
changes.md
test_results.txt
coordinator/
synthesis.mdEnforce per-agent directory isolation to prevent write conflicts and maintain clear ownership of each output artifact.
将子Agent的发现通过文件系统传递,而不是通过消息传递,因为多跳消息链会因每一跳的摘要而退化信息(“传话游戏”)。
让每个子Agent直接写入自己的工作目录。协调者直接读取这些文件,保持完整保真度:
workspace/
agents/
research_agent/
findings.md
sources.jsonl
code_agent/
changes.md
test_results.txt
coordinator/
synthesis.md强制每个Agent的目录隔离,以防止写入冲突并保持每个输出工件的明确所有权。
Pattern 4: Dynamic Skill Loading
模式4:动态Skill加载
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.
Available skills (load with read_file when relevant):
- database-optimization: Query tuning and indexing strategies
- api-design: REST/GraphQL best practices
- testing-strategies: Unit, integration, and e2e testing patternsLoad the full skill file (e.g., ) only when the current task requires it. This converts O(n) static token cost into O(1) per task.
skills/database-optimization/SKILL.md将skill存储为文件,并在静态上下文中仅包含skill名称和简短描述,因为将所有指令塞入系统提示词会浪费token,并可能用矛盾的指导混淆模型。
可用skills(相关时使用read_file加载):
- database-optimization: Query tuning and indexing strategies
- api-design: REST/GraphQL best practices
- testing-strategies: Unit, integration, and e2e testing patterns仅当当前任务需要时加载完整skill文件(例如 )。这将静态token成本从O(n)转换为每个任务的O(1)。
skills/database-optimization/SKILL.mdPattern 5: Terminal and Log Persistence
模式5:终端和日志持久化
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.
terminals/
1.txt # Terminal session 1 output
2.txt # Terminal session 2 outputQuery with targeted grep () instead of loading entire terminal histories into context.
grep -A 5 "error" terminals/1.txt将终端输出自动持久化到文件,并使用grep进行选择性检索,因为长时间运行进程的终端输出会快速积累,手动复制粘贴容易出错。
terminals/
1.txt # Terminal session 1 output
2.txt # Terminal session 2 output使用定向grep进行查询(),而不是将整个终端历史加载到上下文中。
grep -A 5 "error" terminals/1.txtPattern 6: Learning Through Self-Modification
模式6:通过自我修改学习
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.
python
def remember_preference(key: str, value: str):
preferences_file = "agent/user_preferences.yaml"
prefs = load_yaml(preferences_file)
prefs[key] = value
write_yaml(preferences_file, prefs)Guard this pattern with validation because self-modification can accumulate incorrect or contradictory instructions over time. Treat it as experimental -- review persisted preferences periodically.
让Agent将学到的偏好和模式写入自身的指令文件,以便后续会话自动加载此上下文,而不是手动更新系统提示词。
python
def remember_preference(key: str, value: str):
preferences_file = "agent/user_preferences.yaml"
prefs = load_yaml(preferences_file)
prefs[key] = value
write_yaml(preferences_file, prefs)用验证保护此模式,因为自我修改会随时间积累错误或矛盾的指令。应将其视为实验性——定期审查持久化的偏好。
Filesystem Search Techniques
文件系统搜索技术
Combine /, , , and 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.
lslist_dirglobgrepread_file- /
ls: Discover directory structurelist_dir - : Find files matching patterns (e.g.,
glob)**/*.py - : Search file contents, returns matching lines with context
grep - with ranges: Read specific sections without loading entire files
read_file
Use filesystem search for structural and exact-match queries, and semantic search for conceptual queries. Combine both for comprehensive discovery.
将 /、、 和带行范围的 组合用于上下文发现,因为模型专门针对文件系统遍历进行了训练,对于结构模式清晰的技术内容,这种组合常常优于语义搜索。
lslist_dirglobgrepread_file- /
ls:发现目录结构list_dir - :查找匹配模式的文件(例如
glob)**/*.py - :搜索文件内容,返回匹配行及上下文
grep - 加范围:读取特定章节而不加载整个文件
read_file
对于结构性和精确匹配查询使用文件系统搜索,对于概念性查询使用语义搜索。结合两者进行全面的发现。
Practical Guidance
实践指导
When to Use Filesystem Context
何时使用文件系统上下文
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:
Use when:
- Tool outputs exceed ~2000 tokens
- Tasks span multiple conversation turns
- Multiple agents need shared state
- Skills or instructions exceed comfortable system prompt size
- Logs or terminal output need selective querying
Avoid when:
- Tasks complete in single turns (overhead not justified)
- Context fits comfortably in window (no problem to solve)
- Latency is critical (file I/O adds measurable delay)
- Model lacks filesystem tool capabilities
当情况符合以下标准时应用文件系统模式,因为它们会增加I/O开销,只有token节省或持久化需求才能证明其合理性:
使用场景:
- 工具输出超过约2000个token
- 任务跨越多个对话轮次
- 多个Agent需要共享状态
- skill或指令超出舒适的系统提示词大小
- 日志或终端输出需要选择性查询
避免场景:
- 任务在单轮内完成(开销不合理)
- 上下文可以舒适地放入窗口(没有问题需要解决)
- 延迟至关重要(文件I/O增加可测量的延迟)
- 模型缺乏文件系统工具能力
File Organization
文件组织
Structure files for agent discoverability, because agents navigate by listing and reading directory names:
project/
scratch/ # Temporary working files
tool_outputs/ # Large tool results
plans/ # Active plans and checklists
memory/ # Persistent learned information
preferences.yaml # User preferences
patterns.md # Learned patterns
skills/ # Loadable skill definitions
agents/ # Sub-agent workspacesUse consistent naming conventions and include timestamps or IDs in scratch files for disambiguation.
For autonomous research loops, store raw retrieved evidence under the run that consumed it, for example . Do not leave raw research dumps in the repository root; root-level artifacts become hard to audit and easy to cite without provenance.
researcher/runs/<run-id>/sources/evidence/raw/为了Agent的可发现性组织文件,因为Agent通过列出和读取目录名称来导航:
project/
scratch/ # Temporary working files
tool_outputs/ # Large tool results
plans/ # Active plans and checklists
memory/ # Persistent learned information
preferences.yaml # User preferences
patterns.md # Learned patterns
skills/ # Loadable skill definitions
agents/ # Sub-agent workspaces使用一致的命名约定,并在临时文件中加入时间戳或ID以消除歧义。
对于自主研究循环,将原始检索到的证据存储在其消耗的运行目录下,例如 。不要将原始研究转储留在仓库根目录;根级工件变得难以审计,并且容易在没有来源的情况下引用。
researcher/runs/<run-id>/sources/evidence/raw/Token Accounting
Token核算
Measure where tokens originate before and after applying filesystem patterns, because optimizing without measurement leads to wasted effort:
- Track static vs dynamic context ratio
- Monitor tool output sizes before and after offloading
- Measure how often dynamically-loaded context is actually used
在应用文件系统模式前后测量token来源,因为未测量就优化会导致浪费精力:
- 跟踪静态与动态上下文的比率
- 监控卸载前后工具输出的大小
- 测量动态加载的上下文实际被使用的频率
Examples
示例
Example 1: Tool Output Offloading
Input: Web search returns 8000 tokens
Before: 8000 tokens added to message history
After:
- Write to scratch/search_results_001.txt
- Return: "[Results in scratch/search_results_001.txt. Key finding: API rate limit is 1000 req/min]"
- Agent greps file when needing specific details
Result: ~100 tokens in context, 8000 tokens accessible on demandExample 2: Dynamic Skill Loading
Input: User asks about database indexing
Static context: "database-optimization: Query tuning and indexing"
Agent action: read_file("skills/database-optimization/SKILL.md")
Result: Full skill loaded only when relevantExample 3: Chat History as File Reference
Trigger: Context window limit reached, summarization required
Action:
1. Write full history to history/session_001.txt
2. Generate summary for new context window
3. Include reference: "Full history in history/session_001.txt"
Result: Agent can search history file to recover details lost in summarization示例1:工具输出卸载
输入:网络搜索返回8000 token
之前:8000 token添加到消息历史
之后:
- 写入 scratch/search_results_001.txt
- 返回:"[Results in scratch/search_results_001.txt. Key finding: API rate limit is 1000 req/min]"
- Agent在需要具体细节时grep该文件
结果:上下文中约100 token,8000 token可按需访问示例2:动态Skill加载
输入:用户询问数据库索引
静态上下文:"database-optimization: Query tuning and indexing"
Agent操作:read_file("skills/database-optimization/SKILL.md")
结果:仅在与任务相关时才加载完整skill示例3:聊天历史作为文件引用
触发条件:达到上下文窗口限制,需要摘要
操作:
1. 将完整历史写入 history/session_001.txt
2. 为新上下文窗口生成摘要
3. 包含引用:"Full history in history/session_001.txt"
结果:Agent可以搜索历史文件以恢复摘要中丢失的细节Guidelines
指南
- Write large outputs to files; return summaries and references to context
- Store plans and state in structured files for re-reading
- Use sub-agent file workspaces instead of message chains
- Load skills dynamically rather than stuffing all into system prompt
- Persist terminal and log output as searchable files
- Combine grep/glob with semantic search for comprehensive discovery
- Organize files for agent discoverability with clear naming
- Measure token savings to validate filesystem patterns are effective
- Implement cleanup for scratch files to prevent unbounded growth
- Guard self-modification patterns with validation
- Keep raw evidence next to the run, evaluation, and proposal that used it
- 将大型输出写入文件;向上下文返回摘要和引用
- 将计划和状态存储在结构化文件中以便重新阅读
- 使用子Agent文件工作区而非消息链
- 动态加载skill,而不是将所有内容塞入系统提示词
- 将终端和日志输出持久化为可搜索的文件
- 结合grep/glob与语义搜索进行全面的发现
- 为Agent的可发现性组织文件,使用清晰的命名
- 测量token节省以验证文件系统模式有效
- 实现临时文件的清理,防止无限增长
- 用验证保护自我修改模式
- 将原始证据保留在使用它的运行、评估和提案旁边
Gotchas
注意事项
- 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.
- 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.
- 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.
- 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.
**/* - 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.
- 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.
- 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.
- 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.
- 临时目录无限增长:Agent创建临时文件而不清理,最终消耗磁盘并使目录列表杂乱。实施保留策略(基于时间或数量),并在会话边界执行清理。
- 多Agent文件访问中的竞争条件:并发写入同一文件会静默损坏状态。强制每个Agent目录隔离,或使用带Agent前缀条目的追加式文件。
- 移动/重命名后的过时文件引用:Agent持有先前轮次的路径,在重构或文件重组后可能不存在。在读取缓存路径前始终验证文件是否存在;若检查失败,使用glob重新发现。
- glob模式误匹配:过于宽泛的模式(例如 )会将无关文件拉入上下文,浪费token并混淆模型。将glob限定到特定目录和扩展名。
**/* - 文件大小假设:不检查大小就读取文件可能在一次工具调用中向上下文倾泻100K+ token。读取前检查文件大小;对于大文件使用行范围读取。
- 缺少文件存在性检查:Agent假设先前轮次的文件仍然存在,但它们可能已被删除或移动。始终用存在性检查保护读取,并优雅处理文件缺失错误。
- 临时记事本格式漂移:非结构化的临时记事本在多次写入后变得无法解析,因为格式约定会在连续追加中逐步退化。从第一次写入起就定义并强制schema(YAML、JSON或结构化markdown)。
- 硬编码的绝对路径:在仓库被检出到不同位置或在容器中运行时失效。使用相对项目根目录的路径或动态解析路径。
Integration
集成
This skill owns file-backed context storage and retrieval. Adjacent skills own semantic memory, summarization, and topology:
- : filesystem offloading is one implementation of observation masking when full outputs remain retrievable.
context-optimization - : use when file-backed notes are no longer enough and semantic, entity, or temporal retrieval is required.
memory-systems - : sub-agent file workspaces enable context isolation and direct handoff.
multi-agent-patterns - : file references can anchor summaries and preserve details omitted from compressed context.
context-compression - : tools should return file references for large outputs and expose safe read/search operations.
tool-design
此skill拥有文件支持的上下文存储和检索。相邻skill拥有语义记忆、摘要和拓扑:
- :文件系统卸载是观察屏蔽的一种实现,当完整输出仍可检索时。
context-optimization - :当文件支持的笔记不再足够,需要语义、实体或时间检索时使用。
memory-systems - :子Agent文件工作区实现上下文隔离和直接交接。
multi-agent-patterns - :文件引用可以锚定摘要并保留压缩上下文中遗漏的细节。
context-compression - :工具应为大型输出返回文件引用,并提供安全的读/搜索操作。
tool-design
References
参考
Internal reference:
- Implementation Patterns - Read when: implementing scratch pad, plan persistence, or tool output offloading and need concrete code beyond the inline examples
Related skills in this collection:
- context-optimization - Read when: applying token reduction techniques alongside filesystem offloading
- memory-systems - Read when: building persistent storage that outlasts a single session
- multi-agent-patterns - Read when: designing agent coordination with shared file workspaces
External resources:
- LangChain Deep Agents — Read when: implementing filesystem-based context patterns in LangChain/LangGraph pipelines
- Cursor context discovery — Read when: studying how production IDEs implement dynamic context loading
- Anthropic Agent Skills specification — Read when: building skills that leverage filesystem progressive disclosure
内部参考:
- 实现模式 - 何时阅读:实现临时记事本、计划持久化或工具输出卸载,并需要超出内联示例的具体代码时
本集合中的相关skills:
- context-optimization - 何时阅读:在文件系统卸载基础上应用token缩减技术时
- memory-systems - 何时阅读:构建可跨会话持久存在的存储时
- multi-agent-patterns - 何时阅读:设计使用共享文件工作区的Agent协调时
外部资源:
- LangChain Deep Agents — 何时阅读:在LangChain/LangGraph管道中实现基于文件系统的上下文模式时
- Cursor context discovery — 何时阅读:研究生产IDE如何实现动态上下文加载时
- Anthropic Agent Skills规范 — 何时阅读:构建利用文件系统渐进式披露的skills时
Skill Metadata
Skill元数据
Created: 2026-01-07
Last Updated: 2026-05-15
Author: Agent Skills for Context Engineering Contributors
Version: 1.2.0
创建日期:2026-01-07
最后更新:2026-05-15
作者:Agent Skills for Context Engineering Contributors
版本:1.2.0