
Context Mode
- 942 installs
- 19.6k repo stars
- Updated August 4, 2026
- mksglu/claude-context-mode
This is a copy of context-mode by mksglu - installs and ranking accrue to the original listing.
context-mode is a Claude agent skill that routes large tool outputs through context-aware subagents via ctx_execute and ctx_execute_file for developers who need log, test, API, and browser snapshot analysis without flood
About
context-mode replaces direct Bash and cat usage with ctx_execute and ctx_execute_file when processing bulky artifacts such as build logs, JSON API responses, test output, coverage reports, git diffs, Playwright page snapshots, accessibility trees, pod status, and documentation indexes. Trigger phrases include analyze logs, parse JSON, extract errors, run tests, browser snapshot, and call API. Developers reach for context-mode whenever agent tasks risk stuffing megabytes of terminal or DOM output into the primary context window. The skill is operational plumbing for long-running agent workflows rather than a domain-specific analyzer.
- Mandatory default to context-mode for ALL commands
- Triggers on any MCP tool output exceeding 20 lines
- Automatically routes via PreToolUse hook for analyze logs, summarize output, parse JSON, test output, git log, security
- Preserves Bash only for guaranteed-small-output file mutations and git writes
- Handles browser snapshots, DOM structure, coverage reports, dependency trees and cloud resource queries without context
Context Mode by the numbers
- 942 all-time installs (skills.sh)
- +28 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Security screen: HIGH risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mksglu/claude-context-mode --skill context-modeAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 942 |
|---|---|
| repo stars | ★ 19.6k |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 4, 2026 |
| Repository | mksglu/claude-context-mode ↗ |
How do you analyze large agent tool output without context overflow?
Automatically route large tool outputs through context-aware subagents instead of flooding the main LLM context.
Who is it for?
Developers running agent sessions over large logs, test output, git diffs, API payloads, or browser snapshots who need context-safe processing.
Skip if: Small one-line command output or workflows without ctx_execute tooling available in the environment.
When should I use this skill?
The user analyzes logs, test output, JSON API responses, git diffs, browser snapshots, or any large tool output in an agent session.
What you get
Summarized or filtered subagent results from ctx_execute and ctx_execute_file without main-context bloat.
- Condensed log summaries
- Filtered error extracts
- Parsed JSON or snapshot insights
Files
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):
- File mutations:
mkdir,mv,cp,rm,touch,chmod - Git writes:
git add,git commit,git push,git checkout,git branch,git merge - Navigation:
cd,pwd,which - Process control:
kill,pkill - Package management:
npm install,npm publish,pip install - Simple output:
echo,printf
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:
- API debugging: "hit this endpoint", "call the API", "check the response", "find the bug in the response"
- Log analysis: "check the logs", "what errors", "read access.log", "debug the 500s"
- Test runs: "run the tests", "check if tests pass", "test suite output"
- Git history: "show recent commits", "git log", "what changed", "diff between branches"
- Data inspection: "look at the CSV", "parse the JSON", "analyze the config"
- Infrastructure: "list containers", "check pods", "S3 buckets", "show running services"
- Dependency audit: "check dependencies", "outdated packages", "security audit"
- Build output: "build the project", "check for warnings", "compile errors"
- Code metrics: "count lines", "find TODOs", "function count", "analyze codebase"
- Web docs lookup: "look up the docs", "check the API reference", "find examples"
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
- BM25 uses OR semantics — results matching more terms rank higher automatically
- Use 2-4 specific technical terms per query
- Always use `source` parameter when multiple docs are indexed to avoid cross-source contamination
- Partial match works:
source: "Node"matches"Node.js v22 CHANGELOG" - Always use `queries` array — batch ALL search questions in ONE call:
ctx_search(queries: ["transform pipe", "refine superRefine", "coerce codec"], source: "Zod")- NEVER make multiple separate ctx_search() calls — put all queries in one array
External Documentation
- Always use `ctx_fetch_and_index` for external docs — NEVER
catorctx_executewith local paths for packages you don't own - For GitHub-hosted projects, use the raw URL:
https://raw.githubusercontent.com/org/repo/main/CHANGELOG.md - After indexing, use the
sourceparameter in search to scope results to that specific document
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 findingsBrowser & 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(filename: "/tmp/playwright-snapshot.md")
→ saves to file, returns ~50B confirmation
Step 2: ctx_execute_file(path: "/tmp/playwright-snapshot.md", language: "javascript", code: "
const links = [...FILE_CONTENT.matchAll(/- link \"([^\"]+)\"/g)].map(m => m[1]);
const buttons = [...FILE_CONTENT.matchAll(/- button \"([^\"]+)\"/g)].map(m => m[1]);
const inputs = [...FILE_CONTENT.matchAll(/- textbox|- checkbox|- radio/g)];
console.log('Links:', links.length, '| Buttons:', buttons.length, '| Inputs:', inputs.length);
console.log('Navigation:', links.slice(0, 10).join(', '));
")
→ processes in sandbox, returns ~200B summaryTotal context: ~250B instead of 135K tokens.
Workflow C: Console & Network (save to file if large)
browser_console_messages(level: "error", filename: "/tmp/console.md")
→ ctx_execute_file(path: "/tmp/console.md", ...) or ctx_index(path: "/tmp/console.md", ...)
browser_network_requests(includeStatic: false, filename: "/tmp/network.md")
→ ctx_execute_file(path: "/tmp/network.md", ...) or ctx_index(path: "/tmp/network.md", ...)CRITICAL: Why filename + path is mandatory
| Approach | Context cost | Correct? |
|---|---|---|
browser_snapshot() → raw into context | 135K tokens | NO |
browser_snapshot() → ctx_index(content: raw) | 270K tokens (doubled!) | NO |
browser_snapshot(filename) → ctx_index(path) → ctx_search | ~430B | YES |
browser_snapshot(filename) → ctx_execute_file(path) | ~250B | YES |
Key Rule
ALWAYS use `filename` parameter when calling `browser_snapshot`, `browser_console_messages`, or `browser_network_requests`.
Then process viactx_index(path: ...)orctx_execute_file(path: ...)— neverctx_index(content: ...).
>
Data flow: Playwright → file → server-side read → context. Never: Playwright → context → ctx_index(content) → context again.
Subagent Usage
Subagents automatically receive context-mode tool routing via a PreToolUse hook. You do NOT need to manually add tool names to subagent prompts — the hook injects them. Just write natural task descriptions.
Anti-Patterns
- Using
curl http://api/endpointvia Bash → 50KB floods context. Usectx_executewith fetch instead. - Using
cat large-file.jsonvia Bash → entire file in context. Usectx_execute_fileinstead. - Using
gh pr listvia Bash → raw JSON in context. Usectx_executewith--jqfilter instead. - Piping Bash output through
| head -20→ you lose the rest. Usectx_executeto analyze ALL data and print summary. - Narrowing
ctx_executeoutput upstream of capture →ctx_executecaptures,ctx_searchfilters; merging the layers drops data that the index never sees. Seereferences/anti-patterns.md§8. - Running
npm testvia Bash → full test output in context. Usectx_executeto capture and summarize. - Calling
browser_snapshot()WITHOUTfilenameparameter → 135K tokens flood context. Always usebrowser_snapshot(filename: "/tmp/snap.md"). - Calling
browser_console_messages()orbrowser_network_requests()WITHOUTfilename→ entire output floods context. Always use thefilenameparameter. - Passing ANY large data to
ctx_index(content: ...)→ data enters context as a parameter. Always usectx_index(path: ...)to read server-side. Thecontentparameter should only be used for small inline text you're composing yourself. - Calling an MCP tool (Context7
query-docs, GitHub API, etc.) then passing the response toctx_index(content: response)→ doubles context usage. The response is already in context — use it directly or save to file first. - Ignoring
browser_navigateauto-snapshot → navigation response includes a full page snapshot. Don't rely on it for inspection — callbrowser_snapshot(filename)separately. - Expecting
ctx_statsto reset or wipe anything →ctx_statsis read-only (shows stats only). Usectx_purge(confirm: true)to permanently delete all indexed content.
Reference Files
- JavaScript/TypeScript Patterns
- Python Patterns
- Shell Patterns
- Anti-Patterns & Common Mistakes
Anti-Patterns: Common Mistakes with execute / execute_file
Avoid these pitfalls when using context-mode tools.
---
1. Using execute for Small Outputs (< 20 Lines)
Problem: execute adds overhead (LLM summarization call). For small outputs, Bash is faster and cheaper.
BAD — wasteful use of execute:
Tool: execute
code: "echo $(node --version)"
language: shell
GOOD — just use Bash:
Tool: Bash
command: node --versionRule: If the output fits comfortably in your context window (under ~20 lines), use Bash directly. Reserve execute for outputs that would bloat context or need intelligent summarization.
More examples of "just use Bash":
git status— usually 5-10 linesls -la— directory listingcat .env.example— small config filepwd,whoami,which nodewc -l src/index.ts— single line output
---
2. Forgetting to Print Output
Problem: execute captures stdout. If your code doesn't print anything, the summary will be empty or meaningless.
// BAD — no output:
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const deps = Object.keys(data.dependencies);
// Nothing printed! The LLM sees empty stdout.
// GOOD — explicit output:
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const deps = Object.keys(data.dependencies);
console.log(`Dependencies (${deps.length}):`);
deps.forEach(d => console.log(` ${d}: ${data.dependencies[d]}`));# BAD — computes but never prints:
with open('data.json') as f:
data = json.load(f)
result = [x for x in data if x['status'] == 'error']
# result is lost — never printed
# GOOD — always print results:
with open('data.json') as f:
data = json.load(f)
result = [x for x in data if x['status'] == 'error']
print(f"Found {len(result)} errors:")
for r in result:
print(f" {r['id']}: {r['message']}")Rule: Every execute script must end with print/console.log of the results you want summarized.
---
3. Using Bash When JS/Python Would Be Cleaner
Problem: Complex data processing in Bash quickly becomes unreadable and error-prone.
# BAD — parsing JSON in Bash is fragile:
cat data.json | python3 -c "
import sys, json
data = json.load(sys.stdin)
for item in data:
if item['status'] == 'error':
print(item['id'], item['message'])
"
# If you're already using Python inline, just use language: python// GOOD — use the right language for the job:
// language: javascript
const data = require('./data.json');
data.filter(x => x.status === 'error')
.forEach(x => console.log(`${x.id}: ${x.message}`));Rule: If your Bash script contains inline Python/Node or complex jq/awk chains, switch to language: python or language: javascript instead.
Signs you should switch from shell:
- Using
python3 -cornode -einside the shell script - More than 3 pipes chained together
- Using
jqfor complex JSON transformations - Nested loops in Bash
- String manipulation beyond simple
cut/sed
---
4. Loading Entire Files into Context Then Processing
Problem: Reading a 10,000-line file with Read tool, then asking about it, wastes your entire context window. Use execute to process the file and return only the summary.
BAD workflow:
1. Read tool: read 'server.log' (10,000 lines loaded into context)
2. "Find all errors in this log"
→ 10,000 lines consumed context for a question that needs ~20 lines of output
GOOD workflow:
1. execute with language: python
code: |
with open('server.log') as f:
errors = [l for l in f if 'ERROR' in l]
print(f"Total errors: {len(errors)}")
for e in errors[-20:]:
print(e.strip())
summary_prompt: "Categorize errors and report frequency"
→ Only the summary enters contextBAD workflow:
1. Read tool: read 'package-lock.json' (20,000 lines)
2. "What version of lodash is installed?"
GOOD workflow:
1. execute with language: javascript
code: |
const lock = require('./package-lock.json');
const find = (deps, name) => {
if (deps[name]) return deps[name].version;
for (const [, dep] of Object.entries(deps)) {
if (dep.dependencies) {
const v = find(dep.dependencies, name);
if (v) return v;
}
}
};
console.log(`lodash: ${find(lock.dependencies, 'lodash') || 'not found'}`);
summary_prompt: "Report the installed version of lodash"Rule: If a file is over 200 lines and you only need specific data from it, use execute to extract what you need rather than reading the whole file into context.
---
5. Not Using JSON.stringify for Structured Output
Problem: Printing objects without serialization gives [object Object] in JavaScript.
// BAD — prints [object Object]:
const pkg = require('./package.json');
console.log(pkg.dependencies);
// Output: [object Object]
// GOOD — serialize properly:
const pkg = require('./package.json');
console.log(JSON.stringify(pkg.dependencies, null, 2));
// Output: { "react": "^18.2.0", "next": "^14.0.0", ... }// BAD — loses structure in arrays:
const items = [{name: 'a', value: 1}, {name: 'b', value: 2}];
console.log(items);
// May print unhelpfully
// GOOD — format as table:
const items = [{name: 'a', value: 1}, {name: 'b', value: 2}];
console.log('Name | Value');
console.log('------|------');
items.forEach(i => console.log(`${i.name.padEnd(5)} | ${i.value}`));
// Or use JSON.stringify:
console.log(JSON.stringify(items, null, 2));Rule: Always use JSON.stringify(data, null, 2) for objects/arrays in JavaScript, or format as a readable table. In Python, use json.dumps(data, indent=2) or pprint.pprint(data).
---
6. Timeout Too Short for Network Operations
Problem: Default timeout may be too short for API calls, builds, or test suites.
BAD — will timeout on API calls:
Tool: execute
code: |
const resp = await fetch('https://api.slow-service.com/data');
console.log(await resp.json());
language: javascript
timeout_ms: 5000 ← API may take 10+ seconds
GOOD — generous timeout for network:
Tool: execute
code: |
const resp = await fetch('https://api.slow-service.com/data');
console.log(JSON.stringify(await resp.json(), null, 2));
language: javascript
timeout_ms: 30000 ← 30 seconds for network callsRecommended timeouts:
| Operation | timeout_ms |
|---|---|
| File reading/parsing | 5000 - 10000 |
| Local computation | 10000 |
| Single API request | 15000 - 30000 |
| Paginated API calls | 30000 - 60000 |
| npm install / build | 120000 |
| Full test suite | 120000 - 300000 |
Rule: Always consider what your script does and set timeout_ms accordingly. Network calls and builds need significantly more time than file operations.
---
7. Not Using summary_prompt Effectively
Problem: Without a good summary_prompt, the LLM summarization may focus on irrelevant details.
BAD — vague or missing summary_prompt:
summary_prompt: "Summarize this"
→ May focus on the wrong aspects
GOOD — specific and actionable:
summary_prompt: "Report the count of failing tests, list each failure with its file path and error message, and identify any patterns in the failures"Tips for effective summary_prompt:
- Be specific about what data points you need
- Ask for counts and metrics, not just descriptions
- Request actionable insights ("suggest fixes", "identify patterns")
- Mention the format you want ("list as bullet points", "group by category")
---
8. ctx_execute Captures, ctx_search Filters — Don't Merge the Layers
ctx_execute and ctx_search are two layers, not one. ctx_execute exists to capture full output into the index. ctx_search exists to filter what was captured. When you narrow the output inside ctx_execute — at the shell layer, in script logic, anywhere upstream of capture — the dropped lines never reach the index. ctx_search cannot recover what was never written. You've spent the capture budget and lost the data you'd want to query later, for no context-window benefit: large stdout is already auto-indexed, not returned inline.
The mental model:
┌──────────────────────┐ ┌──────────────────────┐
│ ctx_execute │ ───▶ │ ctx_search │
│ (capture layer) │ │ (filter layer) │
│ │ │ │
│ produces full │ │ queries the │
│ output into index │ │ captured index │
└──────────────────────┘ └──────────────────────┘
▲ ▲
│ │
Job: capture Job: narrow
Do NOT narrow here. Do all narrowing here.Rule: Treat ctx_execute's output as write-once to the index. Run the command in full and let it index. Do every narrowing step downstream, via ctx_search. If you find yourself trimming inside ctx_execute, you are doing the filter layer's job in the capture layer — stop and move the narrowing to a ctx_search call.
Why the layer separation matters: the index is what survives across calls and across sessions. Anything you discard before the index is gone permanently from this session's queryable surface. Anything you keep is queryable, repeatedly, with different questions, at zero re-execution cost.
---
Summary Checklist
Before using execute, verify:
- [ ] Output will be > 20 lines (otherwise use Bash)
- [ ] Script prints all results to stdout
- [ ] Objects are serialized with JSON.stringify / json.dumps
- [ ] Timeout matches the operation type
- [ ] Language matches the task (JS for JSON/API, Python for data, Shell for pipes)
- [ ] summary_prompt is specific and actionable
- [ ] Not loading a file into context that could be processed inside execute
JavaScript / TypeScript Patterns for execute
Practical patterns for using execute with language: javascript. All examples assume Node.js runtime with native fetch (Node 18+).
---
API Response Processing
Fetch and summarize a REST API
// execute: Analyze API health endpoint
const resp = await fetch('https://api.example.com/health');
const data = await resp.json();
console.log('=== Service Health ===');
console.log(`Status: ${data.status}`);
console.log(`Uptime: ${data.uptime}`);
console.log(`Timestamp: ${data.timestamp}`);
if (data.services) {
console.log('\n=== Service Components ===');
for (const [name, info] of Object.entries(data.services)) {
console.log(` ${name}: ${info.status} (latency: ${info.latency_ms}ms)`);
}
}
if (data.errors && data.errors.length > 0) {
console.log('\n=== Recent Errors ===');
data.errors.slice(0, 10).forEach(e => {
console.log(` [${e.timestamp}] ${e.code}: ${e.message}`);
});
}summary_prompt: "Report overall health, list any degraded services, and highlight errors"
Paginated API collection
// execute: Fetch all open issues from GitHub API
const owner = 'org';
const repo = 'project';
let page = 1;
let allIssues = [];
while (true) {
const resp = await fetch(
`https://api.github.com/repos/${owner}/${repo}/issues?state=open&per_page=100&page=${page}`,
{ headers: { 'Accept': 'application/vnd.github.v3+json' } }
);
const issues = await resp.json();
if (issues.length === 0) break;
allIssues.push(...issues);
page++;
}
console.log(`Total open issues: ${allIssues.length}\n`);
// Group by labels
const byLabel = {};
allIssues.forEach(issue => {
issue.labels.forEach(label => {
byLabel[label.name] = (byLabel[label.name] || 0) + 1;
});
});
console.log('=== Issues by Label ===');
Object.entries(byLabel)
.sort((a, b) => b[1] - a[1])
.forEach(([label, count]) => console.log(` ${label}: ${count}`));
// Oldest issues
console.log('\n=== 10 Oldest Issues ===');
allIssues
.sort((a, b) => new Date(a.created_at) - new Date(b.created_at))
.slice(0, 10)
.forEach(i => console.log(` #${i.number} (${i.created_at.slice(0,10)}): ${i.title}`));summary_prompt: "Summarize issue distribution by label, highlight stale issues, suggest priorities"
timeout_ms: 30000
---
JSON Data Analysis
Analyze a large JSON config file
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'));
console.log('=== TSConfig Analysis ===');
console.log(`Target: ${data.compilerOptions?.target}`);
console.log(`Module: ${data.compilerOptions?.module}`);
console.log(`Strict: ${data.compilerOptions?.strict}`);
console.log(`Paths aliases: ${Object.keys(data.compilerOptions?.paths || {}).length}`);
if (data.compilerOptions?.paths) {
console.log('\n=== Path Aliases ===');
for (const [alias, targets] of Object.entries(data.compilerOptions.paths)) {
console.log(` ${alias} -> ${targets.join(', ')}`);
}
}
if (data.include) console.log(`\nInclude: ${data.include.join(', ')}`);
if (data.exclude) console.log(`Exclude: ${data.exclude.join(', ')}`);
if (data.references) {
console.log(`\nProject References: ${data.references.length}`);
data.references.forEach(r => console.log(` ${r.path}`));
}summary_prompt: "Report compiler strictness, module system, and any unusual configuration"
Diff two JSON files
const fs = require('fs');
const a = JSON.parse(fs.readFileSync('config.prod.json', 'utf8'));
const b = JSON.parse(fs.readFileSync('config.staging.json', 'utf8'));
function diffObjects(obj1, obj2, path = '') {
const allKeys = new Set([...Object.keys(obj1 || {}), ...Object.keys(obj2 || {})]);
for (const key of allKeys) {
const fullPath = path ? `${path}.${key}` : key;
if (!(key in (obj1 || {}))) {
console.log(`+ ${fullPath}: ${JSON.stringify(obj2[key])}`);
} else if (!(key in (obj2 || {}))) {
console.log(`- ${fullPath}: ${JSON.stringify(obj1[key])}`);
} else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
diffObjects(obj1[key], obj2[key], fullPath);
} else if (JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
console.log(`~ ${fullPath}: ${JSON.stringify(obj1[key])} -> ${JSON.stringify(obj2[key])}`);
}
}
}
console.log('=== Config Diff: prod vs staging ===');
diffObjects(a, b);summary_prompt: "List all configuration differences between prod and staging environments"
---
Package.json / Lock File Analysis
Dependency audit
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const deps = Object.entries(pkg.dependencies || {});
const devDeps = Object.entries(pkg.devDependencies || {});
console.log(`Package: ${pkg.name}@${pkg.version}`);
console.log(`Dependencies: ${deps.length}`);
console.log(`DevDependencies: ${devDeps.length}`);
// Find non-pinned versions
console.log('\n=== Non-Pinned Dependencies ===');
[...deps, ...devDeps].forEach(([name, version]) => {
if (version.startsWith('^') || version.startsWith('~') || version === '*') {
console.log(` ${name}: ${version}`);
}
});
// Find duplicated categories
console.log('\n=== Scripts ===');
Object.entries(pkg.scripts || {}).forEach(([name, cmd]) => {
console.log(` ${name}: ${cmd}`);
});
// Workspace detection
if (pkg.workspaces) {
console.log('\n=== Monorepo Workspaces ===');
const ws = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages || [];
ws.forEach(w => console.log(` ${w}`));
}summary_prompt: "Report dependency health: unpinned versions, total count, any security concerns from package names"
Lock file drift detection
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
let lockExists = { npm: false, yarn: false, pnpm: false };
try { fs.accessSync('package-lock.json'); lockExists.npm = true; } catch {}
try { fs.accessSync('yarn.lock'); lockExists.yarn = true; } catch {}
try { fs.accessSync('pnpm-lock.yaml'); lockExists.pnpm = true; } catch {}
console.log('=== Lock File Status ===');
Object.entries(lockExists).forEach(([mgr, exists]) => {
console.log(` ${mgr}: ${exists ? 'PRESENT' : 'missing'}`);
});
const activeLocks = Object.entries(lockExists).filter(([, v]) => v);
if (activeLocks.length > 1) {
console.log('\nWARNING: Multiple lock files detected! This causes inconsistent installs.');
}
if (activeLocks.length === 0) {
console.log('\nWARNING: No lock file found! Dependencies are not reproducible.');
}
// Check engines
if (pkg.engines) {
console.log('\n=== Required Engines ===');
Object.entries(pkg.engines).forEach(([e, v]) => console.log(` ${e}: ${v}`));
}summary_prompt: "Report lock file health and any warnings about package management"
---
File Content Parsing
Parse and summarize a large markdown file
const fs = require('fs');
const content = fs.readFileSync('CHANGELOG.md', 'utf8');
const lines = content.split('\n');
const sections = [];
let currentSection = null;
for (const line of lines) {
if (line.startsWith('## ')) {
if (currentSection) sections.push(currentSection);
currentSection = { title: line.replace('## ', ''), items: 0, breaking: 0 };
} else if (currentSection && line.startsWith('- ')) {
currentSection.items++;
if (line.toLowerCase().includes('breaking') || line.toLowerCase().includes('BREAKING')) {
currentSection.breaking++;
}
}
}
if (currentSection) sections.push(currentSection);
console.log(`Total versions: ${sections.length}\n`);
console.log('=== Recent Versions ===');
sections.slice(0, 10).forEach(s => {
const warn = s.breaking > 0 ? ` [${s.breaking} BREAKING]` : '';
console.log(` ${s.title}: ${s.items} changes${warn}`);
});
const totalBreaking = sections.reduce((sum, s) => sum + s.breaking, 0);
if (totalBreaking > 0) {
console.log(`\nTotal breaking changes across all versions: ${totalBreaking}`);
}summary_prompt: "Summarize recent releases, highlight breaking changes, report release cadence"
---
Test Output Parsing
Run tests and extract failures
const { execSync } = require('child_process');
let output;
try {
output = execSync('npx jest --json 2>/dev/null', { encoding: 'utf8', maxBuffer: 50 * 1024 * 1024 });
} catch (e) {
output = e.stdout || '';
}
try {
const results = JSON.parse(output);
console.log(`=== Test Results ===`);
console.log(`Suites: ${results.numPassedTestSuites} passed, ${results.numFailedTestSuites} failed`);
console.log(`Tests: ${results.numPassedTests} passed, ${results.numFailedTests} failed`);
console.log(`Time: ${(results.testResults || []).reduce((s, t) => s + (t.endTime - t.startTime), 0)}ms`);
const failures = (results.testResults || []).filter(t => t.status === 'failed');
if (failures.length > 0) {
console.log('\n=== Failed Tests ===');
failures.forEach(suite => {
console.log(`\nSuite: ${suite.name}`);
(suite.assertionResults || [])
.filter(a => a.status === 'failed')
.forEach(a => {
console.log(` FAIL: ${a.ancestorTitles.join(' > ')} > ${a.title}`);
console.log(` ${(a.failureMessages || []).join('\n ').slice(0, 200)}`);
});
});
}
} catch {
console.log('Could not parse JSON output. Raw output:');
console.log(output.slice(0, 5000));
}summary_prompt: "Report test pass/fail counts, list each failing test with its error message"
timeout_ms: 60000
Python Patterns for execute
Practical patterns for using execute with language: python. All examples use Python standard library only (no pip installs required).
---
Data Processing with json Module
Analyze a large JSON dataset
import json
with open('data/users.json') as f:
users = json.load(f)
print(f"Total users: {len(users)}")
# Group by status
from collections import Counter
statuses = Counter(u.get('status', 'unknown') for u in users)
print("\n=== Users by Status ===")
for status, count in statuses.most_common():
print(f" {status}: {count}")
# Find anomalies
inactive_with_recent = [
u for u in users
if u.get('status') == 'inactive' and u.get('last_login', '') > '2025-01-01'
]
if inactive_with_recent:
print(f"\n=== Anomaly: {len(inactive_with_recent)} inactive users with recent logins ===")
for u in inactive_with_recent[:10]:
print(f" {u['email']} - last login: {u['last_login']}")
# Field completeness
fields = ['name', 'email', 'phone', 'address']
print("\n=== Field Completeness ===")
for field in fields:
filled = sum(1 for u in users if u.get(field))
pct = (filled / len(users)) * 100 if users else 0
print(f" {field}: {filled}/{len(users)} ({pct:.1f}%)")summary_prompt: "Report user distribution, data quality issues, and any anomalies found"
Merge and compare two JSON configs
import json
with open('config.default.json') as f:
defaults = json.load(f)
with open('config.local.json') as f:
local = json.load(f)
def compare(d1, d2, path=""):
diffs = []
all_keys = set(list(d1.keys()) + list(d2.keys()))
for key in sorted(all_keys):
full_path = f"{path}.{key}" if path else key
if key not in d1:
diffs.append(f" + {full_path} = {json.dumps(d2[key])}")
elif key not in d2:
diffs.append(f" - {full_path} = {json.dumps(d1[key])}")
elif isinstance(d1[key], dict) and isinstance(d2[key], dict):
diffs.extend(compare(d1[key], d2[key], full_path))
elif d1[key] != d2[key]:
diffs.append(f" ~ {full_path}: {json.dumps(d1[key])} -> {json.dumps(d2[key])}")
return diffs
diffs = compare(defaults, local)
print(f"Config differences: {len(diffs)}")
if diffs:
print("\n=== Changes (local overrides) ===")
for d in diffs:
print(d)
else:
print("No differences found — local matches defaults.")summary_prompt: "List all local config overrides and flag any potentially dangerous changes"
---
CSV / Log File Analysis
Analyze a CSV file
import csv
from collections import Counter, defaultdict
from datetime import datetime
with open('data/transactions.csv') as f:
reader = csv.DictReader(f)
rows = list(reader)
print(f"Total records: {len(rows)}")
print(f"Columns: {', '.join(rows[0].keys()) if rows else 'none'}")
# Summary statistics for numeric column
amounts = [float(r['amount']) for r in rows if r.get('amount')]
if amounts:
print(f"\n=== Amount Statistics ===")
print(f" Min: ${min(amounts):,.2f}")
print(f" Max: ${max(amounts):,.2f}")
print(f" Mean: ${sum(amounts)/len(amounts):,.2f}")
print(f" Median: ${sorted(amounts)[len(amounts)//2]:,.2f}")
print(f" Total: ${sum(amounts):,.2f}")
# Group by category
if 'category' in rows[0]:
by_cat = defaultdict(list)
for r in rows:
by_cat[r['category']].append(float(r.get('amount', 0)))
print("\n=== By Category ===")
for cat, vals in sorted(by_cat.items(), key=lambda x: -sum(x[1])):
print(f" {cat}: {len(vals)} txns, total ${sum(vals):,.2f}")summary_prompt: "Summarize transaction patterns, highlight outliers, report category distribution"
Parse application logs
import re
from collections import Counter
from datetime import datetime
error_pattern = re.compile(r'\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (\w+): (.+)')
levels = Counter()
errors_by_type = Counter()
hourly = Counter()
with open('app.log') as f:
for line in f:
match = error_pattern.match(line.strip())
if match:
timestamp, level, message = match.groups()
levels[level] += 1
hour = timestamp[:13]
hourly[hour] += 1
if level in ('ERROR', 'FATAL'):
# Extract error class
err_type = message.split(':')[0].strip()
errors_by_type[err_type] += 1
print("=== Log Level Distribution ===")
for level, count in levels.most_common():
print(f" {level}: {count}")
print("\n=== Top Error Types ===")
for err, count in errors_by_type.most_common(10):
print(f" {err}: {count}")
print("\n=== Hourly Activity (last 24h) ===")
for hour, count in sorted(hourly.items())[-24:]:
bar = '#' * min(count // 10, 50)
print(f" {hour}: {count:>5} {bar}")summary_prompt: "Report error rates, identify the most common failures, and note any traffic spikes"
---
Text Extraction and Summarization
Extract TODOs and FIXMEs from codebase
import os
import re
pattern = re.compile(r'(TODO|FIXME|HACK|XXX|WARN)[:\s](.+)', re.IGNORECASE)
results = []
for root, dirs, files in os.walk('src'):
# Skip node_modules and hidden dirs
dirs[:] = [d for d in dirs if not d.startswith('.') and d != 'node_modules']
for fname in files:
if fname.endswith(('.ts', '.tsx', '.js', '.jsx', '.py')):
filepath = os.path.join(root, fname)
with open(filepath) as f:
for i, line in enumerate(f, 1):
match = pattern.search(line)
if match:
results.append({
'file': filepath,
'line': i,
'type': match.group(1).upper(),
'text': match.group(2).strip()
})
from collections import Counter
by_type = Counter(r['type'] for r in results)
print(f"Total annotations found: {len(results)}\n")
print("=== By Type ===")
for t, c in by_type.most_common():
print(f" {t}: {c}")
print("\n=== All Items ===")
for r in results:
print(f" [{r['type']}] {r['file']}:{r['line']} — {r['text'][:100]}")summary_prompt: "Categorize TODOs by urgency, group by file area, suggest which to address first"
Summarize a large text/markdown file
with open('ARCHITECTURE.md') as f:
content = f.read()
lines = content.split('\n')
print(f"Total lines: {len(lines)}")
print(f"Total words: {len(content.split())}")
# Extract structure
headings = [(i+1, line) for i, line in enumerate(lines) if line.startswith('#')]
print(f"Sections: {len(headings)}\n")
print("=== Document Structure ===")
for line_num, heading in headings:
level = len(heading) - len(heading.lstrip('#'))
indent = ' ' * (level - 1)
print(f" {indent}{heading.strip()} (line {line_num})")
# Extract code blocks
import re
code_blocks = re.findall(r'```(\w+)?', content)
if code_blocks:
from collections import Counter
langs = Counter(b for b in code_blocks if b)
print(f"\n=== Code Blocks: {len(code_blocks)} total ===")
for lang, count in langs.most_common():
print(f" {lang}: {count}")
# Print first 50 lines for content preview
print("\n=== Content Preview (first 50 lines) ===")
for line in lines[:50]:
print(line)summary_prompt: "Summarize the document structure, key architectural decisions, and main components described"
---
File Comparison
Compare two source files
import difflib
with open('src/auth/login.ts') as f:
old_lines = f.readlines()
with open('src/auth/login.new.ts') as f:
new_lines = f.readlines()
diff = list(difflib.unified_diff(old_lines, new_lines, fromfile='login.ts', tofile='login.new.ts', lineterm=''))
additions = sum(1 for l in diff if l.startswith('+') and not l.startswith('+++'))
deletions = sum(1 for l in diff if l.startswith('-') and not l.startswith('---'))
print(f"Changes: +{additions} -{deletions}\n")
if diff:
print("=== Diff ===")
for line in diff:
print(line)
else:
print("Files are identical.")summary_prompt: "Describe the functional changes between the old and new versions"
Find duplicate content across files
import os
import hashlib
from collections import defaultdict
file_hashes = defaultdict(list)
for root, dirs, files in os.walk('src'):
dirs[:] = [d for d in dirs if not d.startswith('.') and d != 'node_modules']
for fname in files:
if fname.endswith(('.ts', '.tsx', '.js', '.jsx')):
filepath = os.path.join(root, fname)
with open(filepath, 'rb') as f:
content_hash = hashlib.md5(f.read()).hexdigest()
file_hashes[content_hash].append(filepath)
duplicates = {h: files for h, files in file_hashes.items() if len(files) > 1}
if duplicates:
print(f"Found {len(duplicates)} sets of duplicate files:\n")
for h, files in duplicates.items():
print(f" Hash: {h[:8]}...")
for f in files:
print(f" {f}")
print()
else:
print("No duplicate files found.")summary_prompt: "List all duplicate files and suggest which copies to remove"
Shell Patterns for execute
Practical patterns for using execute with language: shell. Best for piping, filtering, and leveraging native OS tools.
---
Build Output Filtering
Capture build errors only
npm run build 2>&1 | tee /tmp/build-output.txt
EXIT_CODE=${PIPESTATUS[0]}
echo "=== Build Result ==="
echo "Exit code: $EXIT_CODE"
if [ "$EXIT_CODE" -ne 0 ]; then
echo ""
echo "=== Errors ==="
grep -iE '(error|failed|FAIL)' /tmp/build-output.txt | head -50
echo ""
echo "=== Warnings ==="
grep -iE '(warning|warn)' /tmp/build-output.txt | head -20
else
echo "Build succeeded."
echo ""
echo "=== Warnings (if any) ==="
grep -iE '(warning|warn)' /tmp/build-output.txt | head -10
fi
echo ""
echo "=== Output Size ==="
wc -l < /tmp/build-output.txt | xargs -I{} echo "{} total lines of output"
rm -f /tmp/build-output.txtsummary_prompt: "Report build success/failure, list all errors with file paths, and count warnings"
timeout_ms: 120000
TypeScript compilation check
npx tsc --noEmit 2>&1 | tee /tmp/tsc-output.txt
EXIT_CODE=${PIPESTATUS[0]}
echo "=== TypeScript Check ==="
echo "Exit code: $EXIT_CODE"
TOTAL_ERRORS=$(grep -c 'error TS' /tmp/tsc-output.txt 2>/dev/null || echo 0)
echo "Total errors: $TOTAL_ERRORS"
if [ "$TOTAL_ERRORS" -gt 0 ]; then
echo ""
echo "=== Errors by Code ==="
grep -oP 'error TS\d+' /tmp/tsc-output.txt | sort | uniq -c | sort -rn | head -20
echo ""
echo "=== Errors by File ==="
grep 'error TS' /tmp/tsc-output.txt | cut -d'(' -f1 | sort | uniq -c | sort -rn | head -20
echo ""
echo "=== First 30 Errors ==="
grep 'error TS' /tmp/tsc-output.txt | head -30
fi
rm -f /tmp/tsc-output.txtsummary_prompt: "Report type error count, most common error codes, and most affected files"
timeout_ms: 60000
---
Test Result Summarization
Jest test summary
npx jest --verbose 2>&1 | tee /tmp/test-output.txt
EXIT_CODE=${PIPESTATUS[0]}
echo ""
echo "=== Test Summary ==="
echo "Exit code: $EXIT_CODE"
# Extract summary line
grep -E '(Tests:|Test Suites:|Snapshots:|Time:)' /tmp/test-output.txt
echo ""
echo "=== Failed Tests ==="
grep -A 2 'FAIL ' /tmp/test-output.txt | head -40
echo ""
echo "=== Slow Tests (if reported) ==="
grep -i 'slow' /tmp/test-output.txt | head -10
rm -f /tmp/test-output.txtsummary_prompt: "Report pass/fail ratio, list all failing test names with suite, note any slow tests"
timeout_ms: 120000
Pytest summary
python -m pytest --tb=short -q 2>&1 | tee /tmp/pytest-output.txt
EXIT_CODE=${PIPESTATUS[0]}
echo ""
echo "=== Pytest Summary ==="
echo "Exit code: $EXIT_CODE"
# Last 20 lines usually contain the summary
tail -20 /tmp/pytest-output.txt
echo ""
echo "=== Failures ==="
grep -E '(FAILED|ERROR)' /tmp/pytest-output.txt | head -30
rm -f /tmp/pytest-output.txtsummary_prompt: "Report test results, list all failures with file and test name"
timeout_ms: 120000
---
Log File Analysis
Filter application logs by severity
LOG_FILE="${1:-/var/log/app.log}"
echo "=== Log File: $LOG_FILE ==="
echo "Total lines: $(wc -l < "$LOG_FILE")"
echo ""
echo "=== Level Distribution ==="
grep -oE '\b(DEBUG|INFO|WARN|ERROR|FATAL)\b' "$LOG_FILE" | sort | uniq -c | sort -rn
echo ""
echo "=== Last 20 Errors ==="
grep -i 'ERROR\|FATAL' "$LOG_FILE" | tail -20
echo ""
echo "=== Error Timeline (hourly) ==="
grep -i 'ERROR' "$LOG_FILE" | grep -oE '\d{4}-\d{2}-\d{2} \d{2}' | sort | uniq -c | tail -24summary_prompt: "Report error frequency, identify patterns, and note any error spikes"
Analyze access logs
LOG_FILE="${1:-/var/log/access.log}"
echo "=== Access Log Summary ==="
echo "Total requests: $(wc -l < "$LOG_FILE")"
echo ""
echo "=== HTTP Status Codes ==="
awk '{print $9}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -10
echo ""
echo "=== Top 20 Paths ==="
awk '{print $7}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -20
echo ""
echo "=== Top 10 IPs ==="
awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -10
echo ""
echo "=== 5xx Errors ==="
awk '$9 ~ /^5/' "$LOG_FILE" | tail -20
echo ""
echo "=== Requests per Hour ==="
awk '{print $4}' "$LOG_FILE" | cut -d: -f1-2 | sort | uniq -c | tail -24summary_prompt: "Report traffic patterns, error rates, most hit endpoints, and suspicious IPs"
---
Directory Size and Structure Analysis
Project structure overview
echo "=== Directory Structure ==="
find . -maxdepth 3 -type d \
! -path '*/node_modules/*' \
! -path '*/.git/*' \
! -path '*/dist/*' \
! -path '*/.next/*' \
! -path '*/__pycache__/*' \
| sort
echo ""
echo "=== File Type Distribution ==="
find . -type f \
! -path '*/node_modules/*' \
! -path '*/.git/*' \
! -path '*/dist/*' \
| sed 's/.*\.//' | sort | uniq -c | sort -rn | head -20
echo ""
echo "=== Largest Files (top 20) ==="
find . -type f \
! -path '*/node_modules/*' \
! -path '*/.git/*' \
-exec ls -la {} \; | sort -k5 -rn | head -20 | awk '{print $5, $9}'
echo ""
echo "=== Directory Sizes ==="
du -sh */ 2>/dev/null | sort -rh | head -15summary_prompt: "Describe the project structure, identify large files that may need attention, report file type distribution"
Disk usage investigation
echo "=== Top-Level Disk Usage ==="
du -sh */ 2>/dev/null | sort -rh
echo ""
echo "=== node_modules Size ==="
if [ -d "node_modules" ]; then
du -sh node_modules
echo ""
echo "=== Largest node_modules packages ==="
du -sh node_modules/*/ 2>/dev/null | sort -rh | head -20
else
echo "No node_modules directory"
fi
echo ""
echo "=== Build Artifacts ==="
for dir in dist build .next out .cache; do
if [ -d "$dir" ]; then
echo " $dir: $(du -sh "$dir" | cut -f1)"
fi
done
echo ""
echo "=== Git Objects Size ==="
if [ -d ".git" ]; then
du -sh .git
fisummary_prompt: "Report total project size, largest contributors, and recommend cleanup targets"
---
Git Analysis
Commit activity analysis
echo "=== Recent Commits (last 30 days) ==="
git log --since="30 days ago" --oneline | wc -l | xargs -I{} echo "{} commits in last 30 days"
echo ""
echo "=== Commits by Author ==="
git shortlog -sn --since="30 days ago" | head -15
echo ""
echo "=== Most Changed Files (last 30 days) ==="
git log --since="30 days ago" --pretty=format: --name-only | sort | uniq -c | sort -rn | head -20
echo ""
echo "=== Branches ==="
echo "Local: $(git branch | wc -l | xargs)"
echo "Remote: $(git branch -r | wc -l | xargs)"
echo ""
echo "=== Stale Branches (merged, excluding main/master) ==="
git branch --merged main 2>/dev/null | grep -v 'main\|master\|\*' | head -10summary_prompt: "Report development velocity, active contributors, hotspot files, and cleanup opportunities"
Related skills
FAQ
What tools does context-mode use instead of Bash?
context-mode directs agents to ctx_execute and ctx_execute_file for large outputs instead of Bash or cat. Those tools run context-aware subagents that return condensed results to the main session.
What outputs should trigger context-mode?
context-mode applies to build logs, test and coverage output, git history, API JSON, Kubernetes pod status, documentation indexes, and Playwright or accessibility tree snapshots—any payload large enough to waste main context.
Is Context Mode safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.