---
name: context-autopilot
description: >
  Install hooks that automate Claude Code's token-saving habits so they don't depend on anyone
  remembering them: cap chat history with auto-compaction, route unrelated requests to a fresh
  subagent once context is large, and flag oversized CLAUDE.md files. Use when someone asks to
  cut Claude Code token use, stop hitting usage limits, or automate /clear and /compact.
---

# Context autopilot

A public test of 945 Claude Code runs (Kensei, github.com/kenseii1/claude-code-limits-tests,
October 2026) found that most tokens are spent re-sending context, not writing answers:

- About 87% of tokens were cache reads of the base context plus history, re-sent on every tool call.
- `/clear` before an unrelated task cut the next questions by 47–79%. `/compact` cut them by 39–60%.
- 16 KB of CLAUDE.md rules the task didn't need added 46% tokens per question. The same rules as a
  skill cost about nothing.
- Naming the file and function got 20/20 answers right, against 8/20 for vague questions.

Those are habits. This skill turns them into settings and hooks. The test measured the habits,
not these hooks. Treat the hooks' savings as expected, not measured, until you measure them.

## Install (Claude does this when the skill is invoked)

Tell the user what will change before writing anything, then:

1. **Cap history.** In `~/.claude/settings.json`, set `"autoCompactWindow": 100000` (the minimum).
   Skip this if a window is already set at the top level, under `modelSettings.<model>`, or in
   `CLAUDE_CODE_AUTO_COMPACT_WINDOW`. Leave idle compaction on (the default). Read the file and merge
   into it; never overwrite existing keys.
2. **Write the two scripts** below to `~/.claude/hooks/`.
3. **Register them** in `~/.claude/settings.json`, merged with any existing hooks:
   ```json
   {"hooks": {
     "SessionStart": [{"hooks": [{"type": "command", "command": "node ~/.claude/hooks/context-autopilot-start.mjs"}]}],
     "UserPromptSubmit": [{"hooks": [{"type": "command", "command": "node ~/.claude/hooks/context-autopilot-prompt.mjs", "timeout": 5}]}]
   }}
   ```
4. **Test** both scripts with synthetic input before calling it done:
   - `echo '{}' | node ~/.claude/hooks/context-autopilot-prompt.mjs` should print nothing.
   - Feed it a fake transcript whose last assistant line has `"usage":{"cache_read_input_tokens":90000}`.
     It should print the subagent hint.
5. **Cloud sessions** (claude.ai/code, the mobile app) start with an empty home directory. Add
   `CLAUDE_CODE_AUTO_COMPACT_WINDOW=100000` to the cloud environment's variables. For the hooks, put
   steps 2–3 in the environment's setup script, or commit them to the repo's `.claude/` folder.
   Chat-only apps (claude.ai chat, the desktop and mobile chat apps) don't run hooks.

## `context-autopilot-start.mjs` (SessionStart)

```js
#!/usr/bin/env node
// Flags oversized CLAUDE.md files and adds two standing rules. Silent on errors.
import { existsSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
let input = {};
try { input = JSON.parse(readFileSync(0, "utf8") || "{}"); } catch {}
const dir = process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();
const notes = [];
const big = ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"]
  .map((n) => [n, join(dir, n)])
  .filter(([, p]) => existsSync(p) && statSync(p).size > 8192)
  .map(([n, p]) => `${n} (${Math.round(statSync(p).size / 1024)} KB)`);
if (big.length) notes.push(`${big.join(", ")} is over 8 KB and loads into every call. Propose moving ` +
  `long backlogs, procedures and history into .claude/skills/<name>/SKILL.md with a one-line pointer.`);
notes.push("Name the exact files and functions you read when answering code questions. Never suggest " +
  "/model mid-session (each model has its own cache).");
process.stdout.write(JSON.stringify({ hookSpecificOutput: {
  hookEventName: "SessionStart", additionalContext: "Context autopilot: " + notes.join(" ") } }));
```

## `context-autopilot-prompt.mjs` (UserPromptSubmit)

```js
#!/usr/bin/env node
// Stand-in for "/clear before unrelated work": hooks can't clear a session, but a fresh
// subagent does unrelated work without re-reading the history on each tool call.
import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
const THRESHOLD = 60000;
try {
  const { transcript_path } = JSON.parse(readFileSync(0, "utf8") || "{}");
  if (!transcript_path) process.exit(0);
  const fd = openSync(transcript_path, "r");
  const size = fstatSync(fd).size, buf = Buffer.alloc(Math.min(size, 512 * 1024));
  readSync(fd, buf, 0, buf.length, size - buf.length); closeSync(fd);
  let tokens = 0;
  for (const line of buf.toString("utf8").split("\n").reverse()) {
    if (!line.includes('"usage"')) continue;
    try {
      const u = JSON.parse(line).message?.usage; if (!u) continue;
      tokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
      break;
    } catch {}
  }
  if (tokens < THRESHOLD) process.exit(0);
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit",
    additionalContext: `Context is ~${Math.round(tokens / 1000)}k tokens. If this request is unrelated ` +
      `to the work so far, do it in a general-purpose subagent (not a fork) with a self-contained brief ` +
      `and keep only its short summary here. If it builds on the current work, continue normally.` } }));
} catch {}
```

## What this skill does not do

- It doesn't change effort or model. 5.5 models already default to medium effort, which the test
  found to be the right default.
- It doesn't add subagents, short-answer styles or deny rules for token savings. The test measured
  no saving from any of them.
- It doesn't send anything anywhere. Both scripts read local files only.

Published by Justin Winter (iamjustinwinter.com/skills). Measurements: Kensei (@0xKense1).
