Context Mode 上下文优化主引擎 (19.7k stars)

Model: qwen-max | ¥0.15/call
工程方法论GPT-4.1工程实践上下文优化主引擎19.7k

上下文优化主引擎 (19.7k stars):mksglu/context-mode: context-mode,适用于工程实践、代码质量与开发流程优化。

Calls: 1

Skill Documentation

Context Mode 上下文优化主引擎 (19.7k stars)

摘要

上下文优化主引擎 (19.7k stars):mksglu/context-mode: context-mode,适用于工程实践、代码质量与开发流程优化。

> 来源: mksglu/context-mode (19.7k stars) — Claude Code 上下文窗口优化

> 原文件: skills/context-mode/SKILL.md

> 模型推荐: gpt-4.1 (工具/查询类)

这个 skill 是干嘛的

mksglu 在 19.7k stars 的 context-mode 仓库里整理的"上下文窗口优化"工具集 — 通过 sandbox 输出压缩(98% reduction)、会话记忆持久化、17 平台路由,让 Claude 在长对话中保持高效。

michael 强调"skill 要有相应的指导功能,指导用户使用",所以加了下面两节让 Agent 和用户对接。

---

🤖 Agent 使用说明

1. 用户提到"上下文 / context / 长会话 / 记忆"时触发

2. skill 会按"压缩 → 持久化 → 检索"流程跑

3. 涉及外部存储前 ask user 确认

4. 完工后让 Agent 跑自检

👤 用户需要做什么?

1. 告诉 Agent 你要管理什么对话(长会话 / 项目 / 知识库)

2. 如果需要外部存储 / API key,按提示提供

3. 全程 Agent 自动化,你只需回答授权类问题

---

原 skill 内容(mksglu/context-mode/skills/context-mode/SKILL.md,截断到 12k chars)

---

name: context-mode

description: |

Use context-mode tools (ctx_execute, ctx_execute_file) instead of Bash/cat when processing

large outputs. Triggers: "analyze logs", "summarize output", "process data",

"parse JSON", "filter results", "extract errors", "check build output",

"analyze dependencies", "process API response", "large file analysis",

"page snapshot", "browser snapshot", "DOM structure", "inspect page",

"accessibility tree", "Playwright snapshot",

"run tests", "test output", "coverage report", "git log", "recent commits",

"diff between branches", "list containers", "pod status", "disk usage",

"fetch docs", "API reference", "index documentation",

"call API", "check response", "query results",

"find TODOs", "count lines", "codebase statistics", "security audit",

"outdated packages", "dependency tree", "cloud resources", "CI/CD output".

Also triggers on ANY MCP tool output that may exceed 20 lines.

Subagent routing is handled automatically via PreToolUse hook.

---

Context Mode: Default for All Large Output

MANDATORY RULE

<context_mode_logic>

<mandatory_rule>

Default to context-mode for ALL commands. Only use Bash for guaranteed-small-output operations.

</mandatory_rule>

</context_mode_logic>

Bash whitelist (safe to run directly):

**Everything else → `ctx_execute` or `ctx_execute_file`.** Any command that reads, queries, fetches, lists, logs, tests, builds, diffs, inspects, or calls an external service. This includes ALL CLIs (gh, aws, kubectl, docker, terraform, wrangler, fly, heroku, gcloud, etc.) — there are thousands and we cannot list them all.

**When uncertain, use context-mode.** Every KB of unnecessary context reduces the quality and speed of the entire session.

Decision Tree

About to run a command / read a file / call an API?
│
├── Command is on the Bash whitelist (file mutations, git writes, navigation, echo)?
│   └── Use Bash
│
├── Output MIGHT be large or you're UNSURE?
│   └── Use context-mode ctx_execute or ctx_execute_file
│
├── Fetching web documentation or HTML page?
│   └── Use ctx_fetch_and_index → ctx_search
│
├── Using Playwright (navigate, snapshot, console, network)?
│   └── ALWAYS use filename parameter to save to file, then:
│       browser_snapshot(filename) → ctx_index(path) or ctx_execute_file(path)
│       browser_console_messages(filename) → ctx_execute_file(path)
│       browser_network_requests(filename) → ctx_execute_file(path)
│       ⚠ browser_navigate returns a snapshot automatically — ignore it,
│         use browser_snapshot(filename) for any inspection.
│       ⚠ Playwright MCP uses a SINGLE browser instance — NOT parallel-safe.
│         For parallel browser ops, use agent-browser via execute instead.
│
├── Using agent-browser (parallel-safe browser automation)?
│   └── Run via execute (shell) — each call gets its own subprocess:
│       execute("agent-browser open example.com && agent-browser snapshot -i -c")
│       ✓ Supports sessions for isolated browser instances
│       ✓ Safe for parallel subagent execution
│       ✓ Lightweight accessibility tree with ref-based interaction
│
├── Processing output from another MCP tool (Context7, GitHub API, etc.)?
│   ├── Output already in context from a previous tool call?
│   │   └── Use it directly. Do NOT re-index with ctx_index(content: ...).
│   ├── Need to search the output multiple times?
│   │   └── Save to file via ctx_execute, then ctx_index(path) → ctx_search
│   └── One-shot extraction?
│       └── Save to file via ctx_execute, then ctx_execute_file(path)
│
└── Reading a file to analyze/summarize (not edit)?
    └── Use ctx_execute_file (file loads into FILE_CONTENT, not context)

When to Use Each Tool

| Situation | Tool | Example |

|-----------|------|---------|

| Hit an API endpoint | `ctx_execute` | `fetch('http://localhost:3000/api/orders')` |

| Run CLI that returns data | `ctx_execute` | `gh pr list`, `aws s3 ls`, `kubectl get pods` |

| Run tests | `ctx_execute` | `npm test`, `pytest`, `go test ./...` |

| Git operations | `ctx_execute` | `git log --oneline -50`, `git diff HEAD~5` |

| Docker/K8s inspection | `ctx_execute` | `docker stats --no-stream`, `kubectl describe pod` |

| Read a log file | `ctx_execute_file` | Parse access.log, error.log, build output |

| Read a data file | `ctx_execute_file` | Analyze CSV, JSON, YAML, XML |

| Read source code to analyze | `ctx_execute_file` | Count functions, find patterns, extract metrics |

| Fetch web docs | `ctx_fetch_and_index` | Index React/Next.js/Zod docs, then search |

| Playwright snapshot | `browser_snapshot(filename)` → `ctx_index(path)` → `ctx_search` | Save to file, index server-side, query |

| Playwright snapshot (one-shot) | `browser_snapshot(filename)` → `ctx_execute_file(path)` | Save to file, extract in sandbox |

| Playwright console/network | `browser_*(filename)` → `ctx_execute_file(path)` | Save to file, analyze in sandbox |

| MCP output (already in context) | Use directly | Don't re-index — it's already loaded |

| MCP output (need multi-query) | `ctx_execute` to save → `ctx_index(path)` → `ctx_search` | Save to file first, index server-side |

| Wipe indexed KB content | `ctx_purge(confirm: true)` | Permanently deletes all indexed content |

Automatic Triggers

Use context-mode for ANY of these, without being asked:

Language Selection

| Situation | Language | Why |

|-----------|----------|-----|

| HTTP/API calls, JSON | `javascript` | Native fetch, JSON.parse, async/await |

| Data analysis, CSV, stats | `python` | csv, statistics, collections, re |

| Shell commands with pipes | `shell` | grep, awk, jq, native tools |

| File pattern matching | `shell` | find, wc, sort, uniq |

Search Query Strategy

External Documentation

Critical Rules

1. **Always console.log/print your findings.** stdout is all that enters context. No output = wasted call.

2. **Write analysis code, not just data dumps.** Don't `console.log(JSON.stringify(data))` — analyze first, print findings.

3. **Be specific in output.** Print bug details with IDs, line numbers, exact values — not just counts.

4. **For files you need to EDIT**: Use the normal Read tool. context-mode is for analysis, not editing.

5. **For Bash whitelist commands only**: Use Bash for file mutations, git writes, navigation, process control, package install, and echo. Everything else goes through context-mode.

6. **Never use `ctx_index(content: large_data)`.** Use `ctx_index(path: ...)` to read files server-side. The `content` parameter sends data through context as a tool parameter — use it only for small inline text.

7. **Always use `filename` parameter** on Playwright tools (`browser_snapshot`, `browser_console_messages`, `browser_network_requests`). Without it, the full output enters context.

8. **Don't re-index data already in context.** If an MCP tool returned data in a previous response, it's already loaded — use it directly or save to file first.

Sandboxed Data Workflow

<sandboxed_data_workflow>

<critical_rule>

When using tools that support saving to a file: ALWAYS use the 'filename' parameter.

NEVER return large raw datasets directly to context.

</critical_rule>

<workflow>

LargeDataTool(filename: "path") → mcp__context-mode__ctx_index(path: "path") → ctx_search()

</workflow>

</sandboxed_data_workflow>

This is the universal pattern for context preservation regardless of

the source tool (Playwright, GitHub API, AWS CLI, etc.).

Examples

Debug an API endpoint

const resp = await fetch('http://localhost:3000/api/orders');
const { orders } = await resp.json();

const bugs = [];
const negQty = orders.filter(o => o.quantity < 0);
if (negQty.length) bugs.push(`Negative qty: ${negQty.map(o => o.id).join(', ')}`);

const nullFields = orders.filter(o => !o.product || !o.customer);
if (nullFields.length) bugs.push(`Null fields: ${nullFields.map(o => o.id).join(', ')}`);

console.log(`${orders.length} orders, ${bugs.length} bugs found:`);
bugs.forEach(b => console.log(`- ${b}`));

Analyze test output

npm test 2>&1
echo "EXIT=$?"

Check GitHub PRs

gh pr list --json number,title,state,reviewDecision --jq '.[] | "\(.number) [\(.state)] \(.title) — \(.reviewDecision // "no review")"'

Read and analyze a large file

# FILE_CONTENT is pre-loaded by ctx_execute_file
import json
data = json.loads(FILE_CONTENT)
print(f"Records: {len(data)}")
# ... analyze and print findings

Browser & Playwright Integration

**When a task involves Playwright snapshots, screenshots, or page inspection, ALWAYS route through file → sandbox.**

Playwright `browser_snapshot` returns 10K–135K tokens of accessibility tree data. Calling it without `filename` dumps all of that into context. Passing the output to `ctx_index(content: ...)` sends it into context a SECOND time as a parameter. Both are wrong.

**The key insight**: `browser_snapshot` has a `filename` parameter that saves to file instead of returning to context. `ctx_index` has a `path` parameter that reads files server-side. `ctx_execute_file` processes files in a sandbox. **None of these touch context.**

Workflow A: Snapshot → File → Index → Search (multiple queries)

Step 1: browser_snapshot(filename: "/tmp/playwright-snapshot.md")
        → saves to file, returns ~50B confirmation (NOT 135K tokens)

Step 2: ctx_index(path: "/tmp/playwright-snapshot.md", source: "Playwright snapshot")
        → reads file SERVER-SIDE, indexes into FTS5, returns ~80B confirmation

Step 3: ctx_search(queries: ["login form email password"], source: "Playwright")
        → returns only matching chunks (~300B)

**Total context: ~430B** instead of 270K tokens. Real 99% savings.

Workflow B: Snapshot → File → Execute File (one-shot extraction)

Step 1: browser_snapshot

## 常见问题(FAQ)

## 使用「上下文优化主引擎 (19.7」这个 skill 能解决什么问题?
本 skill 专注于上下文优化主引擎 (19.7,mksglu/context-mode: context-mode。它将相关流程标准化,帮助用户更快拿到可靠结果,减少重复手工操作。

## 什么情况下适合使用「上下文优化主引擎 (19.7」?
当你需要在上下文优化主引擎 (19.7k stars)相关工作中获得稳定、可复用的产出时最适合——无论是单次任务还是纳入日常工作流,都能直接调用。

## 使用「上下文优化主引擎 (19.7」前需要准备什么?
需要一个具体的项目或任务上下文,最好带有代码仓库或需求文档。