Community编程与开发github.com

filesystem-context

当智能体工作需要文件支持的情境存储时使用:持久化草稿板、工具输出卸载、即时发现、跨智能体交接文件、文件系统记忆以及上下文清理策略。

filesystem-context 是什么?

该技能将文件系统作为智能体上下文的持久化层,解决上下文窗口有限但任务需要更多信息的问题。它定义了四种上下文故障模式(缺失、检索不足、检索过度、信息埋藏)并提供了相应的文件系统解决方案。支持的平台包括所有具备文件系统工具能力的AI智能体(如Claude Code、Cursor、Codex)。其核心模式包括:将工具输出卸载到文件、计划持久化、子智能体间通过文件系统通信、动态技能加载、终端和日志持久化,以及通过自修改学习用户偏好。该技能还强调了文件组织结构、令牌计量实践以及文件大小检查、目录隔离和清理策略等注意事项。

兼容平台✓Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/filesystem-context

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

基于文件系统的上下文工程

将文件系统用作智能体上下文的持久化层,因为上下文窗口有限,而任务通常需要的信息量超过单个窗口所能容纳。文件让智能体能够通过单一接口存储、检索和更新几乎无限量的上下文。

倾向于动态上下文发现——按需拉取相关上下文——而不是静态包含,因为静态上下文无论是否相关都会消耗令牌,并挤占任务特定信息的空间。

何时激活

在以下情况下激活此技能:

  • 工具输出使得上下文窗口膨胀
  • 智能体需要在长时间轨迹中持久化状态
  • 子智能体需要共享信息但无法直接传递消息
  • 任务需要的上下文超出窗口容量
  • 构建能够学习和更新自身指令的智能体
  • 实现用于中间结果的草稿板
  • 终端输出或日志需要智能体可访问

对于其他技能负责的相邻工作,不要激活此技能:

  • 跨会话语义记忆、实体追踪或时序知识图谱:memory-systems。
  • 对话摘要、压缩或持久化交接措辞:context-compression。
  • 不涉及文件存储的令牌效率策略:context-optimization。
  • 多智能体拓扑或交接协议设计:multi-agent-patterns。
  • 将内容从活动窗口逐出的模型编辑:self-managed-context。

核心概念

根据以下四种模式诊断上下文故障,因为每种模式需要不同的文件系统解决方案:

  1. 缺失上下文 — 所需信息在总可用上下文中缺失。通过将工具输出和中间结果持久化到文件中,确保不会丢失任何内容来解决。
  2. 检索不足的上下文 — 检索到的内容未能涵盖智能体所需的信息。通过将文件结构化为便于针对性检索(grep友好格式、清晰的章节标题)来解决。
  3. 检索过度的上下文 — 检索到的内容远超所需,浪费令牌并降低注意力质量。通过将批量内容卸载到文件并返回精简引用来解决。
  4. 被埋藏的上下文 — 零散信息隐藏在众多文件中。通过结合使用glob和grep进行结构化搜索以及语义搜索进行概念查询来解决。

将文件系统用作持久化层来应对所有四种模式:一次写入,持久存储,选择性检索。

详细主题

静态与动态上下文的权衡

将静态上下文(系统指令、工具定义、关键规则)视为昂贵的资源——无论是否相关,它都会在每一轮中消耗令牌。随着智能体能力的积累,静态上下文会增长并挤占动态信息。

改为使用动态上下文发现:仅包含最小的静态指针(名称、一行描述、文件路径),并在相关时使用搜索工具加载完整内容。这更节省令牌,并且通常通过减少窗口中矛盾或不相关的信息来提高响应质量。

接受权衡:动态发现要求模型识别何时需要更多上下文。当前的前沿模型处理得很好,但能力较弱的模型可能无法触发加载。如有疑问,倾向于静态包含关键的安全或正确性约束。

模式1:文件系统作为草稿板

将大量工具输出重定向到文件,而不是直接返回到上下文中,因为一次网络搜索或数据库查询可能将数千个令牌转储到消息历史中,并在整个对话中持续存在。

将输出写入草稿文件,提取精简摘要,并返回文件引用。然后智能体使用针对性检索(grep搜索模式,带行范围的读取)仅访问所需内容。

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个令牌的同时,完整保留输出以供后续参考。

模式2:计划持久化

将计划写入文件系统,因为长期任务在计划被遗忘或总结后会失去连贯性。智能体可以随时重新读取其计划,恢复对目标和进度的认知。

以结构化格式存储计划,使其既可读又可解析:

# 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

在每次回合开始或上下文刷新后重新读取计划以重新定位方向,因为这充当了“通过复述操纵注意力”的角色。

模式3:通过文件系统进行子智能体通信

通过文件系统路由子智能体的发现,而不是消息传递,因为多跳消息链会因每次跳转的总结而导致信息退化(“电话游戏”)。

让每个子智能体直接写入其自己的工作区目录。协调者直接读取这些文件,保持完整保真度:

workspace/
  agents/
    research_agent/
      findings.md
      sources.jsonl
    code_agent/
      changes.md
      test_results.txt
  coordinator/
    synthesis.md

强制每个智能体目录隔离,以防止写冲突并确保每个输出工件的清晰所有权。

模式4:动态技能加载

将技能存储为文件,并仅在静态上下文中包含技能名称和简要描述,因为将所有指令塞入系统提示会浪费令牌,并且可能因矛盾的引导而混淆模型。

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 patterns

仅在当前任务需要时加载完整的技能文件(例如 skills/database-optimization/SKILL.md)。这将 O(n) 的静态令牌成本转换为每个任务的 O(1)。

模式5:终端和日志持久化

自动将终端输出持久化到文件,并使用grep进行选择性检索,因为长期运行进程的终端输出会快速累积,并且手动复制粘贴容易出错。

terminals/
  1.txt    # Terminal session 1 output
  2.txt    # Terminal session 2 output

使用针对性的grep查询(grep -A 5 "error" terminals/1.txt)而不是加载整个终端历史记录到上下文。

模式6:通过自修改学习

让智能体将学到的偏好和模式写入自己的指令文件,以便后续会话自动加载此上下文,而不是需要手动更新系统提示。

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)

通过验证来保护此模式,因为自修改可能随时间的推移积累不正确或矛盾的指令。将其视为实验性的——定期审查持久化的偏好。

文件系统搜索技术

结合 ls/list_dir、glob、grep 和带行范围的 read_file 进行上下文发现,因为模型经过专门训练来处理文件系统遍历,这种组合在结构模式清晰时通常优于语义搜索。

  • ls / list_dir:发现目录结构
  • glob:查找匹配模式的文件(例如 **/*.py)
  • grep:搜索文件内容,返回匹配行及其上下文
  • 带范围的 read_file:读取特定部分而不加载整个文件

使用文件系统搜索进行结构和精确匹配查询,使用语义搜索进行概念查询。结合两者以获得全面的发现。

实用指南

何时使用文件系统上下文

在符合这些标准的情况下应用文件系统模式,因为它们增加了I/O开销,仅当节省令牌或需要持久化时才值得。

使用时:

  • 工具输出超过约2000个令牌
  • 任务跨越多个对话回合
  • 多个智能体需要共享状态
  • 技能或指令超出舒适的系统提示大小
  • 日志或终端输出需要选择性查询

避免时:

  • 任务在单回合内完成(开销不合理)
  • 上下文舒适地容纳在窗口中(没有问题需要解决)
  • 延迟是关键因素(文件I/O增加了可测量的延迟)
  • 模型缺乏文件系统工具能力

文件组织

为智能体可发现性组织文件,因为智能体通过列出和读取目录名称导航:

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/。不要将原始研究转储留在仓库根目录;根级别的工件难以审计且容易在没有出处的情况下引用。

令牌计量

在应用文件系统模式前后测量令牌的来源,因为不通过测量进行优化会导致徒劳的努力:

  • 跟踪静态与动态上下文的比例
  • 在卸载前后监控工具输出的大小
  • 测量实际使用动态加载上下文的频率

示例

示例1:工具输出卸载

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 demand

示例2:动态技能加载

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 relevant

示例3:聊天历史作为文件引用

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. 将大量输出写入文件;将摘要和引用返回给上下文
  2. 在结构化文件中存储计划和状态,以便重新读取
  3. 使用子智能体文件工作区代替消息链
  4. 动态加载技能,而不是将所有内容塞入系统提示
  5. 将终端和日志输出持久化为可搜索的文件
  6. 结合grep/glob与语义搜索进行全面发现
  7. 为智能体可发现性组织文件,并使用清晰的命名
  8. 测量令牌节省量以验证文件系统模式是否有效
  9. 实现草稿文件清理以防止无界增长
  10. 通过验证保护自修改模式
  11. 将原始证据保留在使用它的运行、评估和建议旁边

注意事项

  1. 草稿目录无界增长:智能体创建临时文件而不清理,最终消耗磁盘并使目录列表变得嘈杂。实施保留策略(基于时间或计数),并在会话边界运行清理。
  2. 多智能体文件访问中的竞态条件:对同一文件的并发写入会静默地损坏状态。强制每个智能体目录隔离,或使用带有智能体前缀条目的追加文件。
  3. 移动/重命名后的陈旧文件引用:智能体持有来自之前回合的路径,这些路径在重构或文件重组后不再存在。在读取缓存的路径之前始终验证文件是否存在;如果检查失败,则使用glob重新发现。
  4. Glob模式假匹配:过于宽泛的模式(例如 **/*)会将不相关的文件拉入上下文,浪费令牌并混淆模型。将glob范围限定到特定目录和扩展名。
  5. 文件大小假设:在不检查大小的情况下读取文件可能在单个工具调用中将100K+个令牌转储到上下文。在读取前检查文件大小;对大型文件使用行范围读取。
  6. 缺少文件存在检查:智能体假设文件来自之前回合,但它们可能已被删除或移动。始终通过存在检查保护读取操作,并优雅地处理文件丢失错误。
  7. 草稿板格式漂移:无结构的草稿板在多次写入后变得不可解析,因为格式约定在连续追加过程中会退化。从第一次写入开始定义并强制执行一个模式(YAML、JSON或结构化markdown)。
  8. 硬编码的绝对路径:当仓库在不同位置检出或在容器中运行时,会导致问题。使用相对于项目根的路径或动态解析路径。

集成

此技能拥有文件支持的上下文存储。

…[为翻译截断]

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

book-sft-pipeline

This skill should be used for book-to-SFT pipelines: ePub extraction, literary segmentation, author-voice dataset construction, style-transfer training, LoRA workflows, and model evaluation for voice replication.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-compression

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

memory-systems

This skill should be used for persistent semantic memory in agent systems: cross-session knowledge retention, entity tracking, temporal validity, graph or vector retrieval, memory consolidation, and memory benchmark selection. Route file-backed scratchpads to filesystem-context, handoff summaries to context-compression, and token-efficiency tactics to context-optimization.

multi-agent-patterns

This skill should be used when designing multi-agent systems that need context isolation, supervisor or swarm coordination, explicit handoffs, parallel execution, or a decision on whether multiple agents are justified.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

self-managed-context

This skill should be used when a model gets read-write control over its own live context window instead of a harness-scheduled compaction policy: the context exposed as an editable file the model rewrites with code tools, model-driven eviction and in-place updates, the harness invariants that keep self-editing safe (pinned prefix, edit gate, edit receipts, budget readouts, rollback on overflow), the prefix-cache cost of mid-context edits, and steering or training the model's own context-editing strategy. Route note content and fixed-threshold summarization to context-compression, cache-stable layout under harness control to context-optimization, file offloading to filesystem-context, and loop governance to self-improvement-loops.

tool-design

This skill should be used for the tool-interface layer of an agent system specifically: writing tool descriptions agents can route on, designing tool schemas and response formats, naming conventions, actionable error recovery messages, MCP server design, tool-set consolidation, and deciding when to add or remove an individual tool. Use this when the unit of work is a single tool or a set of tools. Route project-shape, pipeline architecture, and task-model-fit decisions to project-development; route deciding whether to introduce sub-agents to multi-agent-patterns.

相关技能