Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

context-engine上下文引擎

Agent Skill

context-engine 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,440

周安装

60

GitHub Stars

103

下载量

480
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:context-engine(上下文引擎)
来源仓库:https://github.com/borghei/claude-skills
仓库路径:skills/context-engine
安装命令:
npx skills add https://github.com/borghei/claude-skills --skill context-engine
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/borghei/claude-skills --skill context-engine

简介

context-engine 提供生产级 AI 代理上下文管理模式,涵盖知识摄入与记忆检索。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中优化 token 使用与实现跨会话持久记忆。
  • 支持项目知识图谱构建与 RAG 增强生成,提升大代码库下的推理准确性。
  • 安装命令:npx skills add https://github.com/borghei/claude-skills --skill context-engine。
  • 使用前需确认权限范围、维护状态及是否会触发文件读写或网络访问操作。

SKILL.md

Context Engine - AI Agent Context Management

Tier: POWERFUL Category: Engineering Tags: context management, AI agents, memory systems, RAG, token optimization, knowledge graphs

Overview

Context Engine provides production-grade patterns for managing what AI agents know, remember, and retrieve. It covers the full lifecycle: ingestion of project knowledge, optimal packing of context windows, persistent memory across sessions, and retrieval-augmented generation for large codebases. The difference between a useful agent and a hallucinating one is context management.

Core Capabilities

1. Context Window Architecture

Every AI agent operates within a finite context window. Mismanaging it is the #1 cause of degraded agent performance.

Token Budget Allocation Framework

SegmentBudget %PurposePriority
System Instructions5-10%Agent identity, rules, constraintsFixed (always loaded)
Task Context20-30%Current task description, requirementsHigh (per-request)
Relevant Code25-40%Source files, dependencies, typesDynamic (retrieved)
Conversation History10-20%Prior turns, decisions madeSliding window
Tool Results5-15%Command output, search resultsEphemeral
Reserved Buffer5-10%Output generation headroomProtected

Context Packing Strategies

Greedy Relevance Packing

1. Score all candidate context by relevance to current task
2. Sort by score descending
3. Pack until budget exhausted
4. Always reserve output buffer
  • Pros: Simple, fast, works well for focused tasks
  • Cons: Misses cross-cutting context, no diversity

Tiered Loading

Tier 0 (always loaded): System prompt, project rules, active file
Tier 1 (task-specific):  Related files, type definitions, tests
Tier 2 (on-demand):      Documentation, examples, history
Tier 3 (retrieved):      Search results, RAG chunks
  • Pros: Predictable, debuggable, respects fixed costs
  • Cons: Requires upfront tier classification

Adaptive Compression

1. Load full context for first pass
2. Identify low-signal sections (boilerplate, repetitive code)
3. Summarize or truncate low-signal sections
4. Re-pack with compressed context
5. Preserve high-signal sections verbatim
  • Pros: Maximizes information density
  • Cons: Risk of losing important details in compression

2. Memory Architecture

Three-Layer Memory Model

┌─────────────────────────────────────────────────┐
│  Layer 1: Working Memory (Context Window)        │
│  Scope: Current conversation/task                │
│  Lifetime: Single session                        │
│  Storage: In-context tokens                      │
│  Update: Every turn                              │
├─────────────────────────────────────────────────┤
│  Layer 2: Session Memory (Persistent Store)      │
│  Scope: Project-level learnings                  │
│  Lifetime: Across sessions                       │
│  Storage: MEMORY.md, .claude/rules/, CLAUDE.md   │
│  Update: End of session or on discovery          │
├─────────────────────────────────────────────────┤
│  Layer 3: Knowledge Base (Indexed Corpus)        │
│  Scope: Full codebase + documentation            │
│  Lifetime: Persistent, versioned                 │
│  Storage: Vector store, graph DB, file index     │
│  Update: On commit / scheduled reindex           │
└─────────────────────────────────────────────────┘

Memory Promotion Protocol

Knowledge flows upward through layers based on recurrence and value:

SignalActionExample
Pattern seen 1xWorking memory only"This file uses tabs"
Pattern seen 2-3xCandidate for session memory"Project uses pnpm everywhere"
Pattern confirmed across sessionsPromote to CLAUDE.md/rules"Always use pnpm, never npm"
Pattern is domain knowledgeAdd to knowledge base"Auth flow uses JWT + refresh tokens"

Staleness Detection

Context has a shelf life. Stale context causes hallucinations.

Freshness Score = f(last_verified, change_frequency, confidence)

Fresh   (< 7 days, file unchanged):  Use directly
Aging   (7-30 days, file changed):   Re-verify before using
Stale   (> 30 days):                 Flag, re-retrieve, or discard
Unknown (never verified):            Treat as low-confidence

3. Retrieval Strategies for Code

File-Level Retrieval

Best for: navigating to the right file when the agent knows what it needs.

Query: "authentication middleware"
Strategy:
  1. Filename pattern match: *auth*, *middleware*
  2. Import graph: files that import auth modules
  3. Symbol search: exported functions matching auth*
  4. Content search: files containing auth-related patterns
  5. Rank by: recency of edit + import centrality + name match

Chunk-Level Retrieval (RAG for Code)

Best for: finding specific implementations within large files.

Chunking Strategy for Source Code:

  • Chunk by function/class boundaries (never mid-function)
  • Include the function signature + docstring + body as one chunk
  • Attach metadata: file path, language, exports, imports
  • Overlap: include 2 lines above/below for context
  • Max chunk size: 200 lines (larger functions get sub-chunked by logical block)

Embedding Considerations:

  • Code-specific embeddings (CodeBERT, StarCoder embeddings) outperform general text embeddings by 15-30% on code retrieval tasks
  • Hybrid search (keyword + semantic) outperforms either alone
  • Index function signatures separately for fast symbol lookup

Dependency-Aware Retrieval

When retrieving a function, also retrieve:

  1. Its type definitions (interfaces, types it uses)
  2. Its direct dependencies (imported functions it calls)
  3. Its tests (to understand expected behavior)
  4. Its callers (to understand usage context)

This "context neighborhood" approach prevents the agent from seeing a function in isolation.

4. Knowledge Graph Construction

Codebase Graph Schema

Nodes:
  - File (path, language, size, last_modified)
  - Function (name, signature, docstring, complexity)
  - Class (name, methods, properties, inheritance)
  - Module (name, exports, dependencies)
  - Test (name, covers, assertions)
  - Config (type, values, affects)

Edges:
  - IMPORTS (File → File)
  - CALLS (Function → Function)
  - IMPLEMENTS (Class → Interface)
  - TESTS (Test → Function)
  - CONFIGURES (Config → Module)
  - DEPENDS_ON (Module → Module)

Graph Queries for Context

Agent QuestionGraph QueryContext Retrieved
"How does auth work?"Subgraph around auth module, 2 hopsAuth files + dependencies + tests
"What breaks if I change X?"Reverse dependency traversal from XAll callers + their tests
"What's the API surface?"All exported functions from API modulesRoute handlers + types + middleware
"How is this tested?"TEST edges from target functionTest files + fixtures + mocks

5. Context Window Optimization Patterns

Pattern: Sliding Window with Anchors

For long conversations, maintain fixed "anchor" messages while sliding recent history.

[System Prompt]           ← Fixed anchor (never evicted)
[Task Definition]         ← Fixed anchor
[Key Decision #1]         ← Pinned (user marked as important)
[Key Decision #2]         ← Pinned
...
[Turn N-4]                ← Sliding window starts here
[Turn N-3]
[Turn N-2]
[Turn N-1]
[Current Turn]
[Output Buffer]           ← Reserved

Pattern: Progressive Summarization

When conversation exceeds budget:

  1. Summarize oldest turns into a "conversation summary" block
  2. Keep the summary as a single anchor message
  3. Update summary every N turns
  4. Always keep: first system message, task definition, last 5 turns

Pattern: Selective Tool Result Caching

Tool outputs (file reads, search results, command output) consume the most tokens.

Strategy:
  - Cache tool results keyed by (tool, args, file_hash)
  - On re-request: serve from cache (0 new tokens)
  - On file change: invalidate cache for that file
  - Always truncate: command output > 200 lines → first 50 + last 50
  - Never cache: error output (always show in full)

6. Multi-Agent Context Sharing

When multiple agents collaborate, context synchronization becomes critical.

Shared Context Bus

┌──────────┐     ┌──────────────────┐     ┌──────────┐
│ Agent A   │────▶│  Shared Context   │◀────│ Agent B   │
│ (Planner) │     │  - Task state     │     │ (Coder)   │
└──────────┘     │  - Decisions log  │     └──────────┘
                  │  - File changes   │
┌──────────┐     │  - Constraints    │     ┌──────────┐
│ Agent C   │────▶│  - Artifacts      │◀────│ Agent D   │
│ (Reviewer)│     └──────────────────┘     │ (Tester)  │
└──────────┘                               └──────────┘

Context Handoff Protocol

When Agent A passes work to Agent B:

  1. State Summary: What was done, decisions made, current state
  2. Relevant Artifacts: Files created/modified, with paths
  3. Constraints: What must not be changed, invariants
  4. Open Questions: Unresolved decisions that need Agent B's input
  5. Next Steps: Explicit instructions for what Agent B should do

Anti-pattern: Passing the entire conversation history. Always summarize.

Workflows

Workflow 1: Bootstrap Agent Context for a New Codebase

Step 1: Index the codebase
  - Build file tree with metadata (language, size, last modified)
  - Extract all exports, imports, and dependency edges
  - Identify entry points (main files, route handlers, CLI commands)

Step 2: Construct initial knowledge graph
  - Map module dependencies
  - Identify architectural layers (API, service, data, config)
  - Detect frameworks and conventions (naming, structure, patterns)

Step 3: Generate project summary
  - One paragraph: what this project does
  - Architecture diagram (text-based)
  - Key directories and their roles
  - Critical files (config, entry points, shared types)

Step 4: Configure context tiers
  - Tier 0: Project summary, CLAUDE.md, active file
  - Tier 1: Related files within same module
  - Tier 2: Cross-module dependencies
  - Tier 3: Documentation and examples

Workflow 2: Optimize Context for a Specific Task

Step 1: Parse task requirements
  - Extract entities (files, functions, features mentioned)
  - Identify task type (bug fix, feature, refactor, review)

Step 2: Retrieve relevant context
  - File-level: files matching entities
  - Dependency-level: imports/exports of matched files
  - Test-level: tests covering matched code
  - History-level: recent changes to matched files

Step 3: Budget allocation
  - Calculate total tokens available
  - Allocate per tier (see Token Budget Framework)
  - Pack context with greedy relevance

Step 4: Verify coverage
  - Check: all mentioned files included?
  - Check: type definitions for used types included?
  - Check: test examples for expected behavior included?
  - If gaps: retrieve missing context from lower tiers

Workflow 3: Session Memory Management

Step 1: During session - capture learnings
  - New patterns discovered: log to working memory
  - Corrections received: mark as high-confidence learning
  - Errors encountered: log with resolution

Step 2: End of session - evaluate learnings
  - Which learnings are project-specific vs session-specific?
  - Which patterns recurred during this session?
  - Which corrections should become rules?

Step 3: Promote valuable learnings
  - Recurring patterns → CLAUDE.md or .claude/rules/
  - Project conventions → project documentation
  - Error resolutions → knowledge base

Step 4: Prune stale memory
  - Remove learnings about deleted files
  - Update learnings contradicted by new information
  - Archive session-specific context

Anti-Patterns

Anti-PatternProblemBetter Approach
Dumping entire files into contextWastes tokens on irrelevant codeRetrieve specific functions/sections
No output buffer reservationAgent output gets truncatedAlways reserve 10-15% for output
Static context loadingSame context regardless of taskDynamic retrieval based on task type
No staleness trackingUsing outdated informationTimestamp and verify before using
Full conversation replayOlder turns crowd out relevant codeSliding window with summarization
Ignoring import graphMissing type definitions, broken understandingAlways include direct dependencies

Evaluation Metrics

MetricDescriptionTarget
Context Relevance% of loaded context actually used in response> 70%
Retrieval Precision% of retrieved items that are relevant> 80%
Token Utilization% of context budget used productively> 85%
Staleness Rate% of context items that are outdated< 5%
Cache Hit Rate% of tool results served from cache> 40%
Handoff Completeness% of required context passed between agents100%

Integration Points

SkillIntegration
rag-architectUse RAG Architect for vector store design; Context Engine for retrieval strategy
agent-designerAgent Designer defines agent roles; Context Engine manages what each agent knows
self-improving-agentSelf-Improving Agent promotes learnings; Context Engine decides when/how to load them
observability-designerMonitor context utilization metrics alongside agent performance

References

  • references/context-window-strategies.md - Detailed packing algorithms and benchmarks
  • references/code-retrieval-patterns.md - RAG for code: chunking, embedding, and ranking strategies
  • references/memory-architecture-guide.md - Multi-layer memory system design patterns

Troubleshooting

ProblemCauseSolution
Agent responses ignore relevant filesContext retrieval missing import graph traversalEnable dependency-aware retrieval; always include direct imports and type definitions alongside target files
Output truncated mid-responseNo output buffer reserved in token budgetReserve 10-15% of context window for generation; reduce Tier 2/3 content first
Stale context causing hallucinationsMemory layer not tracking file modification timestampsImplement staleness detection with freshness scores; invalidate cache entries when source files change
RAG retrieval returns irrelevant chunksChunking splits functions mid-body or ignores code structureSwitch to AST-aware chunking at function/class boundaries; attach file path and export metadata to each chunk
Context window exceeded on large tasksGreedy packing loads too many full filesUse adaptive compression: summarize boilerplate, load only signatures for low-priority files, keep high-signal code verbatim
Multi-agent handoff loses critical stateRaw conversation history passed instead of structured summaryFollow the Context Handoff Protocol: pass state summary, artifacts, constraints, open questions, and next steps
Knowledge graph queries return empty resultsGraph not rebuilt after major refactors or branch switchesSchedule reindexing on commit hooks or branch checkout; validate node counts after rebuild

Success Criteria

  • Context Relevance above 70%: At least 70% of tokens loaded into the context window are directly referenced or used in the agent's response.
  • Retrieval Precision above 80%: More than 80% of retrieved code chunks or files are relevant to the current task, measured by human evaluation or downstream task success.
  • Token Utilization above 85%: Productive token usage (system instructions + task-relevant code + active conversation) exceeds 85% of the allocated budget, with less than 15% wasted on redundant or low-signal content.
  • Staleness Rate below 5%: Fewer than 5% of context items are outdated (file changed since last retrieval without re-verification), validated by comparing loaded content hashes against current file state.
  • Cache Hit Rate above 40%: At least 40% of repeated tool invocations (file reads, searches) are served from cache, reducing redundant token consumption and latency.
  • Handoff Completeness at 100%: Every multi-agent context handoff includes all five protocol elements (state summary, artifacts, constraints, open questions, next steps) with zero information gaps.
  • Session Memory Promotion Accuracy above 90%: Learnings promoted to persistent memory (CLAUDE.md, rules files) are validated as still accurate within 30 days, with fewer than 10% requiring correction or rollback.

Scope & Limitations

This skill covers:

  • Context window token budget planning, allocation strategies, and packing algorithms for AI coding agents.
  • Multi-layer memory architecture design (working memory, session memory, knowledge base) with promotion and staleness protocols.
  • Code-specific retrieval strategies including file-level, chunk-level, and dependency-aware retrieval for RAG pipelines.
  • Knowledge graph construction from codebases and graph-based context queries for agent workflows.

This skill does NOT cover:

  • Vector store infrastructure setup, embedding model selection, or database deployment — see rag-architect for vector store design and embedding strategies.
  • Agent role definition, personality design, or multi-agent orchestration logic — see agent-designer for agent architecture and agent-workflow-designer for orchestration patterns.
  • Runtime observability, metrics dashboards, or alerting for agent systems — see observability-designer for monitoring and instrumentation.
  • Prompt engineering techniques, chain-of-thought design, or instruction tuning — see prompt-engineer-toolkit for prompt construction patterns.

Integration Points

SkillIntegrationData Flow
rag-architectContext Engine defines retrieval strategies; RAG Architect implements the vector store and embedding pipelineRetrieval queries flow from Context Engine to RAG Architect's indexed store; ranked results flow back as context chunks
agent-designerAgent Designer defines agent roles and capabilities; Context Engine manages per-agent context budgets and memory layersAgent specifications define context requirements; Context Engine returns tailored context windows per agent role
self-improving-agentSelf-Improving Agent identifies recurring patterns and corrections; Context Engine decides when to promote learnings to persistent memoryCandidate learnings flow from Self-Improving Agent; promotion decisions and memory updates flow back through Context Engine's staleness and promotion protocols
observability-designerObservability Designer instruments context utilization metrics (relevance, staleness, cache hits); Context Engine exposes metric endpointsRaw metric events flow from Context Engine; Observability Designer aggregates into dashboards and alerts
agent-workflow-designerAgent Workflow Designer defines multi-agent handoff sequences; Context Engine implements the shared context bus and handoff protocolWorkflow definitions specify which agents share context; Context Engine manages the context bus, serialization, and handoff payloads
codebase-onboardingCodebase Onboarding generates project summaries and architecture maps; Context Engine consumes these as Tier 0 bootstrap contextOnboarding artifacts (project summary, directory map, entry points) feed into Context Engine's initial knowledge graph and context tiers

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.13%
按下载量换算178

Claude

28.13%
按下载量换算135

Cursor

17.88%
按下载量换算86

Gemini CLI

9.11%
按下载量换算44

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills