token-optimizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Token Optimizer: See Where Your Context Window Goes. Get It Back.

Token Optimizer:追踪你的上下文窗口消耗,赢回可用空间。

Token optimization specialist. Audits a Claude Code setup, identifies context window waste, implements fixes, and measures savings.
Target: 5-15% context recovery through config cleanup (more for heavier setups), up to 25%+ with autocompact management. Plus behavioral optimizations that compound across every session.

令牌优化专家。审核Claude Code配置,识别上下文窗口浪费,实施修复方案并量化节省效果。
目标:通过配置清理恢复5-15%的上下文空间(复杂配置可恢复更多),自动压缩管理最高可恢复25%以上空间。此外,行为优化可在每次会话中持续发挥作用。

Phase 0: Initialize

阶段0:初始化

  1. Resolve measure.py path (works for both skill and plugin installs):
bash
MEASURE_PY=""
for f in "$HOME/.claude/skills/token-optimizer/scripts/measure.py" \
         "$HOME/.claude/plugins/cache"/*/token-optimizer/*/skills/token-optimizer/scripts/measure.py; do
  [ -f "$f" ] && MEASURE_PY="$f" && break
done
[ -z "$MEASURE_PY" ] && { echo "[Error] measure.py not found. Is Token Optimizer installed?"; exit 1; }
echo "Using: $MEASURE_PY"
Use
$MEASURE_PY
for all subsequent measure.py calls in this session.
  1. Detect context window size: Check if
    TOKEN_OPTIMIZER_CONTEXT_SIZE
    env var is already set. If not:
    • Check for
      ANTHROPIC_API_KEY
      env var (indicates API usage, possibly 1M context)
    • If API key found, ask the user: "You appear to be using the API. Do you have 1M token context (e.g. Opus)? If so I'll calibrate for 1M instead of 200K."
    • If they confirm 1M,
      export TOKEN_OPTIMIZER_CONTEXT_SIZE=1000000
      for this session
    • If no API key or they say no, default is 200K (no action needed) Keep this quick, one question max. Don't belabor it.
  2. Quick pre-check (detect minimal setups): Run
    python3 $MEASURE_PY report
    . If estimated controllable tokens < 1,000 and no CLAUDE.md exists, short-circuit:
    [Token Optimizer] Your setup is already minimal (~X tokens overhead).
    Focus on behavioral changes instead: /compact at 70%, /clear between topics,
    default agents to haiku, batch requests.
  3. Backup everything first (before touching anything):
bash
BACKUP_DIR="$HOME/.claude/_backups/token-optimizer-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"
cp ~/.claude/CLAUDE.md "$BACKUP_DIR/" 2>/dev/null || true
cp ~/.claude/settings.json "$BACKUP_DIR/" 2>/dev/null || true
cp -r ~/.claude/commands "$BACKUP_DIR/" 2>/dev/null || true
  1. 确定measure.py路径(适用于skill和plugin两种安装方式):
bash
MEASURE_PY=""
for f in "$HOME/.claude/skills/token-optimizer/scripts/measure.py" \
         "$HOME/.claude/plugins/cache"/*/token-optimizer/*/skills/token-optimizer/scripts/measure.py; do
  [ -f "$f" ] && MEASURE_PY="$f" && break
done
[ -z "$MEASURE_PY" ] && { echo "[Error] measure.py not found. Is Token Optimizer installed?"; exit 1; }
echo "Using: $MEASURE_PY"
在本次会话中,所有后续调用measure.py时均使用
$MEASURE_PY
  1. 检测上下文窗口大小: 检查是否已设置
    TOKEN_OPTIMIZER_CONTEXT_SIZE
    环境变量。如果未设置:
    • 检查是否存在
      ANTHROPIC_API_KEY
      环境变量(表明使用API,可能拥有1M上下文)
    • 如果找到API密钥,询问用户:“你似乎正在使用API。你是否拥有1M令牌上下文(例如Opus模型)?如果是,我将针对1M而非200K进行校准。”
    • 如果用户确认是1M,在本次会话中执行
      export TOKEN_OPTIMIZER_CONTEXT_SIZE=1000000
    • 如果没有API密钥或用户否认,默认使用200K(无需操作) 此步骤需快速完成,最多只问一个问题,不要拖沓。
  2. 快速预检查(检测极简配置): 运行
    python3 $MEASURE_PY report
    。 如果预估可控令牌数少于1000且不存在CLAUDE.md,则直接跳过后续步骤:
    [Token Optimizer] 你的配置已处于极简状态(约X令牌开销)。
    建议关注行为优化:在70%上下文占比时使用/compact命令,切换主题时使用/clear命令,默认使用Haiku模型,批量发送请求。
  3. 先备份所有内容(在修改任何内容之前):
bash
BACKUP_DIR="$HOME/.claude/_backups/token-optimizer-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"
cp ~/.claude/CLAUDE.md "$BACKUP_DIR/" 2>/dev/null || true
cp ~/.claude/settings.json "$BACKUP_DIR/" 2>/dev/null || true
cp -r ~/.claude/commands "$BACKUP_DIR/" 2>/dev/null || true

Back up all project MEMORY.md files

备份所有项目的MEMORY.md文件

for memfile in ~/.claude/projects/*/memory/MEMORY.md; do if [ -f "$memfile" ]; then projname=$(basename "$(dirname "$(dirname "$memfile")")") cp "$memfile" "$BACKUP_DIR/MEMORY-${projname}.md" 2>/dev/null || true fi done
for memfile in ~/.claude/projects/*/memory/MEMORY.md; do if [ -f "$memfile" ]; then projname=$(basename "$(dirname "$(dirname "$memfile")")") cp "$memfile" "$BACKUP_DIR/MEMORY-${projname}.md" 2>/dev/null || true fi done

Verify backup is non-empty

验证备份非空

if [ -z "$(ls -A "$BACKUP_DIR" 2>/dev/null)" ]; then echo "[Warning] Backup directory is empty. No files were backed up." echo "This may mean you have a fresh setup (nothing to back up) or a permissions issue." fi

4. **Create coordination folder**:
```bash
COORD_PATH=$(mktemp -d /tmp/token-optimizer-XXXXXXXXXX)
[ -d "$COORD_PATH" ] || { echo "[Error] Failed to create coordination folder. Check /tmp permissions."; exit 1; }
mkdir -p "$COORD_PATH"/{audit,analysis,plan,verification}
  1. Check SessionEnd hook (first-time setup, skips silently if already installed):
bash
python3 $MEASURE_PY check-hook
  • If exit 0: hook is already installed (includes plugin auto-install), skip entirely and proceed to Phase 1.
  • If exit 1 (manual/script install users only): explain and offer to install:
[Token Optimizer] Want to track your token usage over time?

Right now, the optimizer can audit your setup. But to track *trends* (which
skills you actually use, how your context fills up day to day, model costs),
it needs to save a small log after each Claude Code session.

What this does:
- When you close a Claude Code session, it automatically saves usage stats
- Takes ~2 seconds, runs silently in the background, then stops
- All data stays on your machine (stored in ~/.claude/_backups/token-optimizer/)
- Powers the Trends and Health tabs in your dashboard

Without this, the dashboard only shows a snapshot from right now.
With it, you get a living history that updates every session.

Remove anytime by running: python3 measure.py setup-hook --uninstall
Or manually: delete the SessionEnd entry from ~/.claude/settings.json
Ask user:
  1. Install it (run
    measure.py setup-hook --dry-run
    first to show the diff, then confirm and run
    measure.py setup-hook
    )
  2. Show me the JSON first (run
    measure.py setup-hook --dry-run
    and stop)
  3. Skip for now
If skipped, note it and continue. The audit still works without it, but the Trends tab will only have data from manual
measure.py collect
runs.
  1. Offer the bookmarkable dashboard URL (macOS and Windows. Linux lands in a future release; skip silently there.):
    Run BOTH probes in one pass, then branch on the combination:
bash
python3 "$MEASURE_PY" daemon-status
python3 "$MEASURE_PY" daemon-consent --get
daemon-status
prints one of
DAEMON_RUNNING
(our daemon, identity verified),
DAEMON_FOREIGN
(port 24842 bound by something else), or
DAEMON_NOT_RUNNING
.
daemon-consent --get
prints a JSON object — either
{}
(never prompted) or
{"prompted": true, "consent": true|false, ...}
.
Decide using this 2×2 truth table:
Daemon \ Consentunrecorded (
{}
)
consent: true
consent: false
DAEMON_RUNNING
skip; lead with URL next time output mentions the dashboardskip; URL worksthe user declined but the daemon is still running — offer
setup-daemon --uninstall
once
DAEMON_FOREIGN
prompt, but warn port 24842 is already bound by a foreign service (
netstat -ano | findstr :24842
on Windows,
lsof -i :24842
on Mac)
note conflict, suggest uninstalling our daemon's prior instance or freeing the portskip silently
DAEMON_NOT_RUNNING
first-time install prompt (below)offer to reinstall (
measure.py setup-daemon
) — launchd / Task Scheduler lost it
skip silently
First-time install prompt copy:
[Token Optimizer] Want a bookmarkable dashboard URL?

URL:  http://localhost:24842/token-optimizer
File: ~/.claude/_backups/token-optimizer/dashboard.html  (always works)

The URL stays bookmarked and auto-updates after every session.
The file is the fallback — same content, just harder to reach.

What installing the URL does:
- Runs a tiny web server on your machine (~2MB memory)
- Starts automatically at login, restarts if it ever stops
- Only reachable from this machine (localhost), not the network
- Serves just this one dashboard file, nothing else

Remove anytime: python3 measure.py setup-daemon --uninstall
Ask user:
  1. Install it (default — write consent FIRST so we never end up with a running daemon the user said no to, then install: run
    measure.py daemon-consent --set yes
    , then
    measure.py setup-daemon
    )
  2. Skip (run
    measure.py daemon-consent --set no
    )
On Linux or BSD: skip silently. Mention once that the
file://
URL still works and the systemd
--user
daemon ships in a future release.
  1. Check Smart Compaction hooks (v2.0, first-time setup, skips silently if already installed; plugin users get these automatically):
bash
python3 $MEASURE_PY setup-smart-compact --status
  • If all 4 hooks installed (includes plugin auto-install): skip entirely.
  • If partially or not installed (manual/script install users only): explain and offer to install:
[Token Optimizer] New in v2.0: Smart Compaction

Auto-compaction destroys working memory. Smart Compaction captures your
session state (decisions, modified files, errors, agent state) BEFORE
compaction fires, then restores it afterward.

What this does:
- Before compaction: saves a structured checkpoint of your session state
- After compaction: injects recovered context so you don't lose your place
- On session end: captures state for potential pickup in next session
- All checkpoints stored locally (~/.claude/token-optimizer/checkpoints/)

Remove anytime: python3 measure.py setup-smart-compact --uninstall
Ask user:
  1. Install it (run
    measure.py setup-smart-compact --dry-run
    first, then confirm and run
    measure.py setup-smart-compact
    )
  2. Show me the JSON first (run
    measure.py setup-smart-compact --dry-run
    and stop)
  3. Skip for now
If skipped, note it and continue. The audit still works without it.
Output:
[Token Optimizer Initialized] Backup: $BACKUP_DIR | Coordination: $COORD_PATH

if [ -z "$(ls -A "$BACKUP_DIR" 2>/dev/null)" ]; then echo "[Warning] 备份目录为空,未备份任何文件。" echo "这可能意味着你是全新配置(无内容可备份),或存在权限问题。" fi

4. **创建协调文件夹**:
```bash
COORD_PATH=$(mktemp -d /tmp/token-optimizer-XXXXXXXXXX)
[ -d "$COORD_PATH" ] || { echo "[Error] 无法创建协调文件夹,请检查/tmp权限。"; exit 1; }
mkdir -p "$COORD_PATH"/{audit,analysis,plan,verification}
  1. 检查SessionEnd钩子(首次设置,若已安装则自动跳过):
bash
python3 $MEASURE_PY check-hook
  • 如果返回0:钩子已安装(包括插件自动安装),直接跳过此步骤进入阶段1。
  • 如果返回1(仅手动/脚本安装用户):说明情况并提供安装选项:
[Token Optimizer] 是否要跟踪你的令牌使用趋势?

当前优化器仅能审核你的配置。但要跟踪*趋势*(实际使用的skill、上下文每日填充情况、模型成本),
它需要在每次Claude Code会话结束后保存一份小型日志。

具体功能:
- 当你关闭Claude Code会话时,自动保存使用统计数据
- 耗时约2秒,在后台静默运行,完成后自动停止
- 所有数据存储在本地(路径:~/.claude/_backups/token-optimizer/)
- 为仪表盘的趋势和健康标签页提供数据支持

不安装此钩子的话,仪表盘仅显示当前的快照数据。
安装后,你将获得每次会话更新的动态历史数据。

随时可通过以下命令移除:python3 measure.py setup-hook --uninstall
或手动移除:从~/.claude/settings.json中删除SessionEnd条目
询问用户:
  1. 安装(先运行
    measure.py setup-hook --dry-run
    展示差异,确认后运行
    measure.py setup-hook
  2. 先显示JSON内容(运行
    measure.py setup-hook --dry-run
    后停止)
  3. 暂时跳过
如果用户选择跳过,记录该情况并继续。即使没有此钩子,审核仍可正常进行,但趋势标签页仅会显示手动运行
measure.py collect
获取的数据。
  1. 提供可收藏的仪表盘URL(支持macOS和Windows,Linux版本将在后续发布,此处自动跳过):
    一次性运行以下两个探测命令,根据结果分支处理:
bash
python3 "$MEASURE_PY" daemon-status
python3 "$MEASURE_PY" daemon-consent --get
daemon-status
会输出以下结果之一:
DAEMON_RUNNING
(我们的守护进程,身份已验证)、
DAEMON_FOREIGN
(端口24842被其他服务占用)或
DAEMON_NOT_RUNNING
daemon-consent --get
会输出一个JSON对象 —— 要么是
{}
(从未提示过),要么是
{"prompted": true, "consent": true|false, ...}
根据以下2×2真值表进行决策:
守护进程状态 \ 同意状态未记录 (
{}
)
consent: true
consent: false
DAEMON_RUNNING
跳过;下次提到仪表盘时直接给出URL跳过;URL可正常使用用户已拒绝但守护进程仍在运行 —— 提供一次
setup-daemon --uninstall
选项
DAEMON_FOREIGN
提示,但警告端口24842已被外部服务占用(Windows使用
netstat -ano | findstr :24842
,Mac使用
lsof -i :24842
查看)
提示冲突,建议卸载之前的守护进程实例或释放端口自动跳过
DAEMON_NOT_RUNNING
首次安装提示(如下)提供重新安装选项(
measure.py setup-daemon
)—— launchd/任务计划程序已丢失该进程
自动跳过
首次安装提示内容:
[Token Optimizer] 是否需要可收藏的仪表盘URL?

URL地址:http://localhost:24842/token-optimizer
本地文件:~/.claude/_backups/token-optimizer/dashboard.html (始终可用)

该URL可添加至收藏夹,并在每次会话后自动更新。
本地文件是备用方案 —— 内容相同,但访问不便。

安装URL的作用:
- 在你的机器上运行一个小型Web服务器(约占用2MB内存)
- 登录时自动启动,进程崩溃后自动重启
- 仅本地可访问(localhost),不对外网开放
- 仅提供该仪表盘文件服务,无其他功能

随时可通过以下命令移除:python3 measure.py setup-daemon --uninstall
询问用户:
  1. 安装(默认选项 —— 先记录同意状态,避免出现用户拒绝但守护进程仍运行的情况,然后执行:
    measure.py daemon-consent --set yes
    ,再运行
    measure.py setup-daemon
  2. 跳过(运行
    measure.py daemon-consent --set no
对于Linux或BSD系统:自动跳过。仅提及一次
file://
URL仍可使用,systemd
--user
守护进程将在后续版本中推出。
  1. 检查Smart Compaction钩子(v2.0版本,首次设置,若已安装则自动跳过;插件用户会自动获得这些钩子):
bash
python3 $MEASURE_PY setup-smart-compact --status
  • 如果4个钩子均已安装(包括插件自动安装):直接跳过。
  • 如果部分或未安装(仅手动/脚本安装用户):说明情况并提供安装选项:
[Token Optimizer] v2.0新功能:Smart Compaction

自动压缩会破坏工作内存。Smart Compaction会在压缩触发前捕获你的会话状态(决策、修改的文件、错误、Agent状态),然后在压缩后恢复该状态。

具体功能:
- 压缩前:将会话状态保存为结构化检查点
- 压缩后:注入恢复的上下文,避免工作进度丢失
- 会话结束时:捕获状态以便下次会话继续使用
- 所有检查点存储在本地(路径:~/.claude/token-optimizer/checkpoints/)

随时可通过以下命令移除:python3 measure.py setup-smart-compact --uninstall
询问用户:
  1. 安装(先运行
    measure.py setup-smart-compact --dry-run
    展示差异,确认后运行
    measure.py setup-smart-compact
  2. 先显示JSON内容(运行
    measure.py setup-smart-compact --dry-run
    后停止)
  3. 暂时跳过
如果用户选择跳过,记录该情况并继续。即使没有此钩子,审核仍可正常进行。
输出:
[Token Optimizer Initialized] Backup: $BACKUP_DIR | Coordination: $COORD_PATH

Phase 1: Quick Audit (Parallel Agents)

阶段1:快速审核(并行Agent)

Read
references/agent-prompts.md
for all prompt templates.
Dispatch 6 agents in parallel (single message, multiple Task calls):
Model assignment: CLAUDE.md, MEMORY.md, Skills, MCP auditors use
model="sonnet"
(judgment calls). Commands use
model="haiku"
(data gathering). Settings & Advanced uses
model="sonnet"
(judgment on rules, settings, @imports).
AgentOutput FileTask
CLAUDE.md Auditor
audit/claudemd.md
Size, duplication, tiered content, cache structure
MEMORY.md Auditor
audit/memorymd.md
Size, overlap with CLAUDE.md
Skills Auditor
audit/skills.md
Count, frontmatter overhead, duplicates
MCP Auditor
audit/mcp.md
Deferred tools, broken/unused servers
Commands Auditor
audit/commands.md
Count, menu overhead
Settings & Advanced
audit/advanced.md
Hooks, rules, settings, @imports, file exclusion, caching, monitoring
Pass
COORD_PATH
to each agent. Wait for all to complete.
Validation: Before proceeding to Phase 2, verify all 6 audit files exist:
bash
for f in claudemd.md memorymd.md skills.md mcp.md commands.md advanced.md; do
  [ -f "$COORD_PATH/audit/$f" ] || echo "MISSING: $f"
done
If any are missing, note it and proceed with available data. Do NOT re-dispatch failed agents.

阅读
references/agent-prompts.md
获取所有提示模板。
并行调度6个Agent(单条消息,多个任务调用):
模型分配:CLAUDE.md、MEMORY.md、Skills、MCP审核员使用
model="sonnet"
(需要判断)。Commands审核员使用
model="haiku"
(数据收集)。Settings & Advanced审核员使用
model="sonnet"
(规则、设置、@imports的判断)。
Agent输出文件任务
CLAUDE.md审核员
audit/claudemd.md
大小、重复内容、分层内容、缓存结构
MEMORY.md审核员
audit/memorymd.md
大小、与CLAUDE.md的重叠内容
Skills审核员
audit/skills.md
数量、前置元数据开销、重复项
MCP审核员
audit/mcp.md
延迟工具、损坏/未使用的服务器
Commands审核员
audit/commands.md
数量、菜单开销
设置与高级审核员
audit/advanced.md
钩子、规则、设置、@imports、文件排除、缓存、监控
COORD_PATH
传递给每个Agent,等待所有任务完成。
验证:进入阶段2之前,验证所有6个审核文件是否存在:
bash
for f in claudemd.md memorymd.md skills.md mcp.md commands.md advanced.md; do
  [ -f "$COORD_PATH/audit/$f" ] || echo "MISSING: $f"
done
如果有文件缺失,记录情况并使用现有数据继续。不要重新调度失败的Agent。

Phase 2: Analysis (Synthesis Agent)

阶段2:分析(综合Agent)

Read the Synthesis Agent prompt from
references/agent-prompts.md
.
Dispatch with
model="opus"
(fallback:
model="sonnet"
if Opus unavailable). It reads all audit files and writes a prioritized plan to
{COORD_PATH}/analysis/optimization-plan.md
.
Validation: After the synthesis agent completes, verify output exists:
bash
[ -s "$COORD_PATH/analysis/optimization-plan.md" ] || echo "[Warning] Synthesis output missing or empty. Presenting raw audit files instead."
If missing, present the individual
audit/*.md
files directly to the user. Do not proceed to Phase 4 without user review of either the synthesis or the raw findings.

references/agent-prompts.md
中读取综合Agent的提示。
使用
model="opus"
调度(如果Opus不可用, fallback为
model="sonnet"
)。它会读取所有审核文件,并将优先级计划写入
{COORD_PATH}/analysis/optimization-plan.md
验证:综合Agent完成后,验证输出是否存在:
bash
[ -s "$COORD_PATH/analysis/optimization-plan.md" ] || echo "[Warning] 综合输出缺失或为空,将直接展示原始审核文件。"
如果输出缺失,直接向用户展示单个
audit/*.md
文件。未经用户查看综合结果或原始发现,不要进入阶段4。

Phase 3: Present Findings

阶段3:展示结果

Read the optimization plan and present. For the MODEL ROUTING line, also read
{COORD_PATH}/audit/advanced.md
to extract the "Has routing instructions" and "Usage Pattern" data if not present in the optimization plan.
[Token Optimizer Results]

CURRENT STATE
Your per-message overhead: ~X tokens
Context used before first message: ~X%

QUICK WINS (do these today)
- [Action 1]: Save ~X tokens/msg (~Y%)
- [Action 2]: Save ~X tokens/msg (~Y%)

MODEL ROUTING
[Has instructions: Yes/No] | [Token distribution: X% Opus, Y% Sonnet, Z% Haiku or "Not measured yet"]

FULL OPTIMIZATION POTENTIAL
If all implemented: ~X tokens/msg saved (~Y% reduction)

Ready to implement? I can:
1. Auto-fix safe changes (consolidate CLAUDE.md, archive skills)
2. Generate permissions.deny rules (if missing)
3. Create optimized CLAUDE.md template
4. Show MCP servers to consider disabling

⚠️ Some optimizations have side effects:
- Deny rules block file access for ALL tools (may break MCP servers that read databases)
- Archiving skills breaks anything that @imports them
- Disabling MCP servers breaks skills that use their tools
I'll check for dependencies and warn you before each change.

What should we tackle first?
Then generate the interactive dashboard:
bash
python3 $MEASURE_PY dashboard --coord-path $COORD_PATH
This generates an interactive HTML dashboard and opens it in the default browser. The dashboard shows all findings, a token donut chart, and an optimization checklist. The user can browse categories, toggle optimizations, and click "Copy Prompt" to paste selected items back into Claude Code.
Tell the user: "Dashboard opened in your browser. Browse findings by category, check the optimizations you want, click Copy Prompt and paste back here. Or just tell me directly what to tackle."
Also mention the persistent dashboard. Check if the daemon is actually running first:
bash
python3 "$MEASURE_PY" daemon-status 2>/dev/null || echo "DAEMON_NOT_RUNNING"
If DAEMON_RUNNING:
Your persistent dashboard (auto-updated every session):
  URL:    http://localhost:24842/token-optimizer
  File:   ~/.claude/_backups/token-optimizer/dashboard.html
If DAEMON_NOT_RUNNING:
Your persistent dashboard (auto-updated every session):
  File:   ~/.claude/_backups/token-optimizer/dashboard.html
Then, only on macOS, suggest: "Want a bookmarkable URL instead? Run:
python3 $MEASURE_PY setup-daemon
" Do NOT mention
localhost:24842
if the daemon is not running. Users will try the URL and get a connection error.
For headless/remote servers, the user can run
python3 $MEASURE_PY dashboard --coord-path $COORD_PATH --serve
separately in a terminal to serve over HTTP. Never use
--serve
from within the SKILL.md orchestrator (it blocks with
serve_forever
).
Wait for user decision before proceeding.

阅读优化计划并展示。对于MODEL ROUTING部分,如果优化计划中未包含相关数据,需读取
{COORD_PATH}/audit/advanced.md
提取"Has routing instructions"和"Usage Pattern"数据。
[Token Optimizer 结果]

当前状态
每条消息的开销:约X令牌
首次消息前已使用的上下文:约X%

快速优化方案(今日即可实施)
- [操作1]:每条消息节省约X令牌(约Y%)
- [操作2]:每条消息节省约X令牌(约Y%)

模型路由
[是否有路由指令:是/否] | [令牌分布:X% Opus,Y% Sonnet,Z% Haiku 或 "尚未统计"]

完整优化潜力
如果全部实施:每条消息可节省约X令牌(约Y%的减少)

是否准备实施?我可以:
1. 自动修复安全变更(合并CLAUDE.md、归档skill)
2. 生成permissions.deny规则(如果缺失)
3. 创建优化后的CLAUDE.md模板
4. 展示可考虑禁用的MCP服务器

⚠️ 部分优化存在副作用:
- Deny规则会阻止所有工具的文件访问(可能破坏读取数据库的MCP服务器)
- 归档skill会破坏所有@import该skill的功能
- 禁用MCP服务器会破坏依赖这些服务器的skill
我会在每次变更前检查依赖关系并发出警告。

优先处理哪项?
然后生成交互式仪表盘:
bash
python3 $MEASURE_PY dashboard --coord-path $COORD_PATH
这会生成一个交互式HTML仪表盘并在默认浏览器中打开。仪表盘展示所有发现、令牌环形图和优化清单。用户可按类别浏览、切换优化项,点击“复制提示”将选中项粘贴回Claude Code。
告知用户:“仪表盘已在你的浏览器中打开。按类别浏览发现,勾选你想要的优化项,点击复制提示并粘贴到此处。或者直接告诉我优先处理哪项。”
同时提及持久化仪表盘。首先检查守护进程是否真的在运行
bash
python3 "$MEASURE_PY" daemon-status 2>/dev/null || echo "DAEMON_NOT_RUNNING"
如果DAEMON_RUNNING:
你的持久化仪表盘(每次会话后自动更新):
  URL地址:http://localhost:24842/token-optimizer
  本地文件:~/.claude/_backups/token-optimizer/dashboard.html
如果DAEMON_NOT_RUNNING:
你的持久化仪表盘(每次会话后自动更新):
  本地文件:~/.claude/_backups/token-optimizer/dashboard.html
然后,仅针对macOS用户建议:“想要可收藏的URL?运行:
python3 $MEASURE_PY setup-daemon
” 如果守护进程未运行,不要提及
localhost:24842
,否则用户访问会遇到连接错误。
对于无GUI/远程服务器,用户可在终端单独运行
python3 $MEASURE_PY dashboard --coord-path $COORD_PATH --serve
通过HTTP提供服务。不要在SKILL.md编排器中使用
--serve
(会因
serve_forever
阻塞)。
等待用户决策后再继续。

Phase 4: Implementation

阶段4:实施

Read
references/implementation-playbook.md
for detailed steps.
Available actions: 4A (CLAUDE.md), 4B (MEMORY.md), 4C (Skills), 4D (File Exclusion), 4E (MCP), 4F (Hooks), 4G (Cache Structure), 4H (Rules Cleanup), 4I (Settings Tuning), 4J (Skill Description Tightening), 4K (Compact Instructions Setup), 4L (Model Routing Setup), 4M (Smart Compaction Setup), 4N (Context Quality Check), 4O (Version-Aware Optimizations), 4P (Smart Model Routing Instructions).
Templates in
examples/
. Always backup before changes. Present diffs for approval.
references/implementation-playbook.md
中读取详细步骤。
可用操作:4A(CLAUDE.md)、4B(MEMORY.md)、4C(Skills)、4D(文件排除)、4E(MCP)、4F(钩子)、4G(缓存结构)、4H(规则清理)、4I(设置调优)、4J(Skill描述精简)、4K(压缩指令设置)、4L(模型路由设置)、4M(Smart Compaction设置)、4N(上下文质量检查)、4O(版本感知优化)、4P(智能模型路由指令)。
示例模板位于
examples/
。变更前始终先备份,展示差异供用户批准。

4M: Smart Compaction Setup

4M:Smart Compaction设置

Protects session state across compaction events. Three components:
  1. Install hooks (PreCompact + SessionStart + Stop + SessionEnd):
bash
undefined
保护压缩事件中的会话状态。包含三个组件:
  1. 安装钩子(PreCompact + SessionStart + Stop + SessionEnd):
bash
undefined

Preview what will change

预览将要变更的内容

python3 $MEASURE_PY setup-smart-compact --dry-run
python3 $MEASURE_PY setup-smart-compact --dry-run

Install all hooks

安装所有钩子

python3 $MEASURE_PY setup-smart-compact
python3 $MEASURE_PY setup-smart-compact

Check current status

检查当前状态

python3 $MEASURE_PY setup-smart-compact --status

Show the user the dry-run diff first. Explain:
- **PreCompact**: Captures decisions, modified files, errors, agent state to a checkpoint file before compaction runs
- **SessionStart** (matcher: compact): Injects recovered context after compaction completes
- **Stop**: Captures checkpoint when session ends normally
- **SessionEnd**: Captures checkpoint on /clear or session death

All hooks call `measure.py` directly (pure Python, no shell scripts). Composes safely with any existing hooks the user already has.

2. **Generate Compact Instructions** (project-specific compaction guidance):
```bash
python3 $MEASURE_PY compact-instructions
This analyzes the user's CLAUDE.md, recent sessions, and project structure to generate tailored instructions that tell Claude what to prioritize during compaction. The user adds these to their project-level
.claude/settings.json
under
compactInstructions
.
  1. Verify installation:
bash
python3 $MEASURE_PY setup-smart-compact --status
Should show all 4 hooks as installed. Test by running
/compact
manually and checking that a checkpoint file appears in
~/.claude/token-optimizer/checkpoints/
.
Configurable via environment variables:
  • TOKEN_OPTIMIZER_CHECKPOINT_FILES
    : Max checkpoint files kept (default: 10)
  • TOKEN_OPTIMIZER_CHECKPOINT_TTL
    : Seconds before checkpoint expires for restore (default: 300)
  • TOKEN_OPTIMIZER_CHECKPOINT_RETENTION_DAYS
    : Days to keep old checkpoints (default: 7)
  • TOKEN_OPTIMIZER_RELEVANCE_THRESHOLD
    : Keyword overlap for new-session restore (default: 0.3)
python3 $MEASURE_PY setup-smart-compact --status

先向用户展示dry-run差异,解释:
- **PreCompact**:在压缩运行前将决策、修改的文件、错误、Agent状态捕获到检查点文件
- **SessionStart**(匹配器:compact):压缩完成后注入恢复的上下文
- **Stop**:会话正常结束时捕获检查点
- **SessionEnd**:在/clear或会话异常终止时捕获检查点

所有钩子直接调用`measure.py`(纯Python,无shell脚本),可与用户已有的任何钩子安全共存。

2. **生成压缩指令**(项目特定的压缩指南):
```bash
python3 $MEASURE_PY compact-instructions
这会分析用户的CLAUDE.md、最近会话和项目结构,生成定制化指令,告知Claude压缩时应优先保留哪些内容。用户需将这些指令添加到项目级
.claude/settings.json
compactInstructions
字段中。
  1. 验证安装
bash
python3 $MEASURE_PY setup-smart-compact --status
应显示所有4个钩子已安装。手动运行/compact命令进行测试,检查
~/.claude/token-optimizer/checkpoints/
中是否生成检查点文件。
可通过环境变量配置:
  • TOKEN_OPTIMIZER_CHECKPOINT_FILES
    :保留的最大检查点文件数(默认:10)
  • TOKEN_OPTIMIZER_CHECKPOINT_TTL
    :检查点可用于恢复的过期时间(秒,默认:300)
  • TOKEN_OPTIMIZER_CHECKPOINT_RETENTION_DAYS
    :旧检查点的保留天数(默认:7)
  • TOKEN_OPTIMIZER_RELEVANCE_THRESHOLD
    :新会话恢复时的关键词重叠阈值(默认:0.3)

4N: Context Quality Check

4N:上下文质量检查

Analyzes current session for content quality (not just quantity):
bash
python3 $MEASURE_PY quality current
Shows a composite score (0-100) based on:
  • Stale reads (25%): Files read then later edited (re-read would be fresher)
  • Bloated results (25%): Large tool outputs never referenced again
  • Duplicates (15%): Repeated system reminders or injected content
  • Compaction depth (15%): Number of compactions (each = information loss)
  • Decision density (10%): Ratio of substantive exchanges to overhead
  • Agent efficiency (10%): Dispatch cost vs useful result size
Score ranges:
  • 85-100: Excellent, clean session
  • 70-84: Good, some bloat, smart compaction would help
  • 50-69: Degraded, significant waste,
    /compact
    with checkpoint recommended
  • <50: Critical, heavy rot, consider
    /clear
    with checkpoint
Present the score and top issues. Recommend specific actions based on the findings.
分析当前会话的内容质量(不仅是数量):
bash
python3 $MEASURE_PY quality current
基于以下维度展示综合得分(0-100):
  • 过时读取(25%):读取后被编辑的文件(重新读取会更新内容)
  • 冗余结果(25%):从未被再次引用的大型工具输出
  • 重复内容(15%):重复的系统提醒或注入内容
  • 压缩深度(15%):压缩次数(每次压缩都会丢失信息)
  • 决策密度(10%):实质性交互与开销的比例
  • Agent效率(10%):调度成本与有用结果大小的比例
得分范围:
  • 85-100:优秀,会话干净整洁
  • 70-84:良好,存在一些冗余,Smart Compaction会有所帮助
  • 50-69:较差,存在大量浪费,建议使用带检查点的/compact命令
  • <50:严重,上下文严重冗余,建议使用带检查点的/clear命令
展示得分和主要问题,基于发现结果推荐具体操作。

4P: Smart Model Routing Instructions

4P:智能模型路由指令

Injects a managed model routing block into the project's CLAUDE.md based on actual usage patterns from the last 30 days.
bash
undefined
基于过去30天的实际使用模式,将托管模型路由块注入项目的CLAUDE.md中。
bash
undefined

Preview what would be injected

预览将要注入的内容

python3 $MEASURE_PY inject-routing --dry-run
python3 $MEASURE_PY inject-routing --dry-run

Inject (user must approve the diff first)

注入(用户必须先批准差异)

python3 $MEASURE_PY inject-routing

The block is inserted between `<!-- TOKEN_OPTIMIZER:MODEL_ROUTING -->` markers. It includes:
- Current model usage percentages (Opus/Sonnet/Haiku split)
- Task-to-model routing recommendations
- Warnings if usage is heavily skewed (e.g., >70% Opus)

The block has a 48h TTL: if not refreshed within 48 hours, it auto-removes to prevent stale routing advice.

**Always show the user the dry-run diff and get approval before injecting.**

Optional: inject a passive coaching block with session-level insights:
```bash
python3 $MEASURE_PY setup-coach-injection        # Inject COACH block
python3 $MEASURE_PY setup-coach-injection --uninstall  # Remove it

python3 $MEASURE_PY inject-routing

该块会插入到`<!-- TOKEN_OPTIMIZER:MODEL_ROUTING -->`标记之间。包含:
- 当前模型使用百分比(Opus/Sonnet/Haiku占比)
- 任务到模型的路由建议
- 使用严重倾斜时的警告(例如>70%使用Opus)

该块有48小时TTL:如果48小时内未刷新,会自动移除以避免过时的路由建议。

**注入前始终向用户展示dry-run差异并获得批准。**

可选:注入包含会话级洞察的被动指导块:
```bash
python3 $MEASURE_PY setup-coach-injection        # 注入COACH块
python3 $MEASURE_PY setup-coach-injection --uninstall  # 移除COACH块

Measurement Tool: Additional Commands

测量工具:额外命令

Beyond the core
report
/
snapshot
/
compare
/
dashboard
commands, the measurement tool includes:
  • measure.py dashboard
    : Generates a standalone persistent dashboard at
    ~/.claude/_backups/token-optimizer/dashboard.html
    with Trends and Health tabs. Auto-regenerated by the SessionEnd hook.
  • measure.py setup-daemon
    : Installs a macOS launchd daemon serving the dashboard at
    http://localhost:24842/token-optimizer
    . Starts on login, restarts on crash. Remove with
    --uninstall
    .
  • measure.py trends [--days N] [--json]
    : Scans all JSONL session logs across projects. Shows which skills you actually use, subagent patterns, model mix, and cross-references against installed skills to surface unused ones. Default: last 30 days.
  • measure.py health
    : Detects running Claude Code sessions, checks their version against installed, flags stale/zombie processes, and shows automated Claude-related processes.
  • Both
    trends
    and
    health
    data appear as interactive tabs in the dashboard (standalone or full audit).
除核心的
report
/
snapshot
/
compare
/
dashboard
命令外,测量工具还包括:
  • measure.py dashboard
    :在
    ~/.claude/_backups/token-optimizer/dashboard.html
    生成独立的持久化仪表盘,包含趋势和健康标签页。由SessionEnd钩子自动重新生成。
  • measure.py setup-daemon
    :安装macOS launchd守护进程,在
    http://localhost:24842/token-optimizer
    提供仪表盘服务。登录时启动,崩溃后重启。使用
    --uninstall
    移除。
  • measure.py trends [--days N] [--json]
    :扫描所有项目的JSONL会话日志。展示实际使用的skill、子Agent模式、模型组合,并与已安装的skill交叉引用以找出未使用的skill。默认:最近30天。
  • measure.py health
    :检测运行中的Claude Code会话,检查版本是否匹配,标记过时/僵尸进程,并展示自动化的Claude相关进程。
  • trends
    health
    数据会作为交互式标签页显示在仪表盘中(独立或完整审核模式)。

v2.0 Commands

v2.0新增命令

  • measure.py quality [session-id|current]
    : Analyzes session content quality. Scores stale reads, bloated results, duplicates, compaction depth, decision density, agent efficiency. Returns composite 0-100 score with actionable breakdown.
  • measure.py setup-smart-compact [--dry-run] [--status] [--uninstall]
    : Installs/manages the Smart Compaction hook system (PreCompact capture + SessionStart restore + Stop/SessionEnd checkpoints). Use
    --dry-run
    to preview,
    --status
    to check,
    --uninstall
    to remove.
  • measure.py compact-capture
    : Called by PreCompact/Stop/SessionEnd hooks. Parses JSONL transcript, extracts decisions/files/errors/agent state, writes checkpoint to
    ~/.claude/token-optimizer/checkpoints/
    . Not intended for direct user invocation.
  • measure.py compact-restore
    : Called by SessionStart hook (matcher: compact). Reads most recent checkpoint and injects recovered context. Not intended for direct user invocation.
  • measure.py compact-instructions [--json]
    : Generates project-specific Compact Instructions based on CLAUDE.md and session patterns. Output is text the user adds to their
    .claude/settings.json
    compactInstructions field.
  • measure.py list-checkpoints [--cwd PATH] [--max-age MINUTES]
    : Lists session checkpoints with age, trigger type, and quality scores. Useful for debugging the smart compact system.

  • measure.py quality [session-id|current]
    :分析会话内容质量。对过时读取、冗余结果、重复内容、压缩深度、决策密度、Agent效率进行评分。返回0-100的综合得分及可操作的细分项。
  • measure.py setup-smart-compact [--dry-run] [--status] [--uninstall]
    :安装/管理Smart Compaction钩子系统(PreCompact捕获 + SessionStart恢复 + Stop/SessionEnd检查点)。使用
    --dry-run
    预览,
    --status
    检查状态,
    --uninstall
    移除。
  • measure.py compact-capture
    :由PreCompact/Stop/SessionEnd钩子调用。解析JSONL转录文件,提取决策/文件/错误/Agent状态,将检查点写入
    ~/.claude/token-optimizer/checkpoints/
    。不建议用户直接调用。
  • measure.py compact-restore
    :由SessionStart钩子调用(匹配器:compact)。读取最新的检查点并注入恢复的上下文。不建议用户直接调用。
  • measure.py compact-instructions [--json]
    :基于CLAUDE.md和会话模式生成项目特定的压缩指令。输出内容需由用户添加到
    .claude/settings.json
    的compactInstructions字段中。
  • measure.py list-checkpoints [--cwd PATH] [--max-age MINUTES]
    :列出会话检查点,包含时长、触发类型和质量得分。用于调试Smart Compaction系统。

Phase 5: Verification

阶段5:验证

Read the Verification Agent prompt from
references/agent-prompts.md
.
Dispatch with
model="haiku"
. It re-measures everything and calculates savings.
Present results:
[Optimization Complete]

SAVINGS ACHIEVED
- CLAUDE.md: -X tokens/msg
- MEMORY.md: -Y tokens/msg
- Skills: -Z tokens/msg
- Total: -W tokens/msg (V% reduction)

NEXT STEPS (Behavioral, ordered by ROI)
1. Default subagents to Haiku (60x cheaper than Opus, see Model Routing)
2. Use /compact at 50-70% context (quality degrades past 70%)
3. Use /clear between unrelated topics
4. Use Plan Mode (Shift+Tab x2) before complex tasks
5. Batch related requests into one message
6. Run /context periodically to check fill level
7. Run `measure.py trends` periodically to review usage patterns

references/agent-prompts.md
中读取验证Agent的提示。
使用
model="haiku"
调度。它会重新测量所有内容并计算节省效果。
展示结果:
[优化完成]

已实现的节省
- CLAUDE.md:每条消息减少X令牌
- MEMORY.md:每条消息减少Y令牌
- Skills:每条消息减少Z令牌
- 总计:每条消息减少W令牌(减少V%)

后续步骤(行为优化,按投资回报率排序)
1. 默认子Agent使用Haiku模型(比Opus便宜60倍,详见模型路由)
2. 在上下文占比50-70%时使用/compact命令(超过70%后质量会下降)
3. 切换无关主题时使用/clear命令
4. 处理复杂任务前使用计划模式(按两次Shift+Tab)
5. 将相关请求批量发送为一条消息
6. 定期运行/context命令检查上下文填充水平
7. 定期运行`measure.py trends`查看使用模式

Reference Files

参考文件

PhaseRead
Phase 1-2
references/agent-prompts.md
,
references/token-flow-architecture.md
Phase 3
references/optimization-checklist.md
Phase 4
references/implementation-playbook.md
,
examples/
Phase 5
references/agent-prompts.md

阶段需读取的文件
阶段1-2
references/agent-prompts.md
,
references/token-flow-architecture.md
阶段3
references/optimization-checklist.md
阶段4
references/implementation-playbook.md
,
examples/
阶段5
references/agent-prompts.md

Model Selection

模型选择

TaskModelFallbackWhy
CLAUDE.md, MEMORY.md, Skills, MCP auditors
sonnet
haiku
Judgment: content structure, semantic duplicates
Commands auditor
haiku
-Data gathering: counting, presence checks
Settings & Advanced auditor
sonnet
haiku
Judgment: rules quality, settings tradeoffs, @imports analysis
Synthesis (Phase 2)
opus
sonnet
Cross-cutting prioritization across all findings
OrchestratorDefault-Coordination only
Verification (Phase 5)
haiku
-Re-measurement

任务使用模型备选模型原因
CLAUDE.md、MEMORY.md、Skills、MCP审核员
sonnet
haiku
需要判断:内容结构、语义重复项
Commands审核员
haiku
-数据收集:计数、存在性检查
设置与高级审核员
sonnet
haiku
需要判断:规则质量、设置权衡、@imports分析
综合分析(阶段2)
opus
sonnet
跨领域的所有发现优先级排序
编排器默认模型-仅用于协调
验证(阶段5)
haiku
-重新测量

Error Handling

错误处理

  • Agent timeout/failure: If an audit agent fails, note the gap and continue. Do not retry. The synthesis agent handles missing files gracefully.
  • Model unavailable: Fall back one tier: opus -> sonnet -> haiku. Log which model was actually used.
  • No CLAUDE.md found: Report 0 tokens, skip to skills audit.
  • No skills directory: Report 0 tokens, note as "fresh setup."
  • measure.py not found: Fall back to manual estimation (line count x 15 for prose, x 8 for YAML).
  • Coordination folder write failure: Abort and report the error. Do not proceed without audit storage.
  • Backup write failure: If
    ls "$BACKUP_DIR"
    shows 0 files after Phase 0 backup, warn user and ask whether to proceed without backup. Do not silently continue.
  • mktemp failure: If
    COORD_PATH
    directory does not exist after creation, print error and abort. Check /tmp permissions.
  • Synthesis agent failure: If
    analysis/optimization-plan.md
    is missing or empty after Phase 2, present raw audit files to user instead. Do not proceed to Phase 4 blindly.
  • Verification agent failure: If Phase 5 agent fails, fall back to running
    measure.py snapshot after
    +
    measure.py compare
    directly in the shell.
  • Snapshot file corrupt: If
    compare
    fails with a JSON error, re-run
    measure.py snapshot [label]
    to regenerate the corrupt file.
  • Stale snapshot warning: If the "before" snapshot is >24h old when running
    compare
    , a warning is printed. Consider re-taking it for accurate results.

  • Agent超时/失败:如果审核Agent失败,记录缺失项并继续。不要重试。综合Agent会优雅处理缺失文件。
  • 模型不可用:降级使用:opus -> sonnet -> haiku。记录实际使用的模型。
  • 未找到CLAUDE.md:报告0令牌,跳过至skill审核。
  • 无skills目录:报告0令牌,标记为“全新配置”。
  • 未找到measure.py: fallback到手动估算(散文按行数×15,YAML按行数×8)。
  • 协调文件夹写入失败:终止并报告错误。没有审核存储则无法继续。
  • 备份写入失败:如果阶段0备份后
    ls "$BACKUP_DIR"
    显示0文件,警告用户并询问是否在无备份的情况下继续。不要静默继续。
  • mktemp失败:如果
    COORD_PATH
    目录创建后不存在,打印错误并终止。检查/tmp权限。
  • 综合Agent失败:如果阶段2后
    analysis/optimization-plan.md
    缺失或为空,直接向用户展示原始审核文件。不要盲目进入阶段4。
  • 验证Agent失败:如果阶段5 Agent失败,fallback到直接在shell中运行
    measure.py snapshot after
    +
    measure.py compare
  • 快照文件损坏:如果
    compare
    因JSON错误失败,重新运行
    measure.py snapshot [label]
    生成新的快照文件。
  • 快照过时警告:如果运行
    compare
    时“before”快照已超过24小时,打印警告。考虑重新拍摄以获得准确结果。

Restoring Backups

恢复备份

If something goes wrong, restore from the backup created in Phase 0:
bash
undefined
如果出现问题,从阶段0创建的备份中恢复:
bash
undefined

Find your most recent backup

查找最新的备份

ls -ltd ~/.claude/_backups/token-optimizer-* | head -5
ls -ltd ~/.claude/_backups/token-optimizer-* | head -5

Restore specific files (replace TIMESTAMP with your backup folder name)

恢复特定文件(将TIMESTAMP替换为你的备份文件夹名称)

BACKUP="$HOME/.claude/_backups/token-optimizer-TIMESTAMP" cp "$BACKUP/CLAUDE.md" ~/.claude/CLAUDE.md cp "$BACKUP/settings.json" ~/.claude/settings.json cp -r "$BACKUP/commands" ~/.claude/commands
BACKUP="$HOME/.claude/_backups/token-optimizer-TIMESTAMP" cp "$BACKUP/CLAUDE.md" ~/.claude/CLAUDE.md cp "$BACKUP/settings.json" ~/.claude/settings.json cp -r "$BACKUP/commands" ~/.claude/commands

MEMORY.md files have the project name in the filename

MEMORY.md文件名包含项目名称

for f in "$BACKUP"/MEMORY-.md; do [ -f "$f" ] || continue projname="${f##/MEMORY-}"; projname="${projname%.md}"

Guard against path traversal in crafted backup filenames

case "$projname" in .. | / ) echo "[Warning] Skipping suspicious backup: $f"; continue ;; esac [ -d "$HOME/.claude/projects/${projname}/memory" ] || continue cp "$f" "$HOME/.claude/projects/${projname}/memory/MEMORY.md" done

Backups are never automatically deleted. They accumulate in `~/.claude/_backups/`.

---
for f in "$BACKUP"/MEMORY-.md; do [ -f "$f" ] || continue projname="${f##/MEMORY-}"; projname="${projname%.md}"

防范备份文件名中的路径遍历攻击

case "$projname" in .. | / ) echo "[Warning] 跳过可疑备份:$f"; continue ;; esac [ -d "$HOME/.claude/projects/${projname}/memory" ] || continue cp "$f" "$HOME/.claude/projects/${projname}/memory/MEMORY.md" done

备份不会自动删除,会累积在`~/.claude/_backups/`中。

---

v3.1 Features

v3.1新功能

Efficiency Grading (S/A/B/C/D/F)

效率评级(S/A/B/C/D/F)

All quality scores now include a letter grade: S (90-100), A (80-89), B (70-79), C (55-69), D (40-54), F (0-39). Shown in status line (
ContextQ:A(82)
), dashboard badges, coach tab, and CLI output.
所有质量得分现在包含字母评级:S(90-100)、A(80-89)、B(70-79)、C(55-69)、D(40-54)、F(0-39)。显示在状态行(
ContextQ:A(82)
)、仪表盘徽章、指导标签页和CLI输出中。

Git-Aware Context Suggestions

Git感知上下文建议

New command:
python3 $MEASURE_PY git-context [--json]
Analyzes git diff/status to suggest which files should be in context: modified files, test companions, co-changed files (from last 50 commits), and import chains.
新增命令:
python3 $MEASURE_PY git-context [--json]
分析git diff/status,建议哪些文件应纳入上下文:修改的文件、测试配套文件、共同变更的文件(最近50次提交)和导入链。

PreToolUse Read-Cache

PreToolUse读取缓存

Detects redundant file reads and optionally blocks them with structural digests.
Default ON (warn mode). Opt out:
TOKEN_OPTIMIZER_READ_CACHE=0
or config
{"read_cache_enabled": false}
. Modes:
TOKEN_OPTIMIZER_READ_CACHE_MODE=warn
(default, suggests) or
=block
(prevents re-read). Decisions log: Per-session files in
~/.claude/token-optimizer/read-cache/decisions/
Stats:
python3 $MEASURE_PY read-cache-stats --session SESSION_ID
Clear:
python3 $MEASURE_PY read-cache-clear
检测冗余文件读取,可选择通过结构摘要阻止重复读取。
默认开启(警告模式)。可通过
TOKEN_OPTIMIZER_READ_CACHE=0
或配置
{"read_cache_enabled": false}
关闭。 模式
TOKEN_OPTIMIZER_READ_CACHE_MODE=warn
(默认,仅提示)或
=block
(阻止重复读取)。 决策日志:每个会话的日志文件存储在
~/.claude/token-optimizer/read-cache/decisions/
统计数据
python3 $MEASURE_PY read-cache-stats --session SESSION_ID
清空缓存
python3 $MEASURE_PY read-cache-clear

.contextignore

.contextignore

Create
.contextignore
in project root or
~/.claude/.contextignore
(global) to block files from being read. Uses gitignore-style glob patterns (fnmatch). Hard-blocks regardless of read-cache mode.

在项目根目录或
~/.claude/.contextignore
(全局)创建
.contextignore
文件,阻止文件被读取。使用gitignore风格的glob模式(fnmatch)。无论读取缓存模式如何,都会强制阻止。

Core Rules

核心规则

  • Quantify everything (X tokens, Y%)
  • Create backups before any changes (
    ~/.claude/_backups/
    )
  • Ask user before implementing
  • Never delete files, always archive
  • Check dependencies before archiving (skills, MCP servers, deny rules can break other tools)
  • Warn about side effects: deny rules block ALL tools, MCP removal breaks dependent skills, skill archival breaks @imports
  • Prefer project-level deny rules over global (easier to debug, less blast radius)
  • Use appropriate models (with fallbacks) for each task
  • Show before/after diffs
  • Frame savings as context budget (% of context window), not dollar amounts
  • 所有内容量化(X令牌,Y%)
  • 变更前创建备份(存储在
    ~/.claude/_backups/
  • 实施前询问用户
  • 从不删除文件,始终归档
  • 归档前检查依赖关系(skill、MCP服务器、deny规则可能破坏其他工具)
  • 警告副作用:deny规则阻止所有工具,移除MCP服务器会破坏依赖的skill,归档skill会破坏@import
  • 优先使用项目级deny规则而非全局规则(更易调试,影响范围更小)
  • 为每个任务使用合适的模型(含备选)
  • 展示变更前后的差异
  • 节省效果以上下文预算(上下文窗口的百分比)而非金额呈现