Skip to main content
vincentor

context-canary

by vincentorv0.2.0

Automated context health monitoring via canary detection

Installation guide →
1 skillhooks GitHub

Documentation

# context-canary

Claude Code 上下文健康监控插件。通过在会话中植入"金丝雀口令"并定期探测模型是否还记得,自动检测上下文窗口退化。

## 工作原理

```
SessionStart
  canary_init.sh 生成随机口令 (如 bravo-kilo-4827)
  注入到 Claude 上下文 → Claude 记住口令

每次 Claude 回复结束 (Stop hook)
  canary_check.sh 递增计数器
  每 N 次 Stop → 注入探测问题: "请报告你的口令"
  下一次 Stop → 检查 Claude 是否正确回复了口令

  healthy  → 口令完全匹配,静默
  degraded → 代号对但数字错,警告
  dead     → 完全忘记,强警告
```

### 渐进式探测

单次探测失败不会立即告警,而是自适应调整探测频率:

```
normal  (interval=5) ──失败──→ caution (interval=3)
                                  │
                               ──失败──→ alert (interval=1)
                                           │
                                        连续2次失败 → 建议 /compact
                                           │
  normal ←──恢复── caution ←──恢复──────────┘
```

每次告警会附带 context 占用估算(transcript 大小、估计 token 数)。

## 安装

### 方式一:通过 marketplace

```bash
claude plugin add context-canary@vincent-personal-plugins
```

### 方式二:本地安装

```bash
claude plugin add ./context-canary
```

### 注册 hooks(必须)

由于 Claude Code 插件级 hooks 存在已知问题([#10225](https://github.com/anthropics/claude-code/issues/10225)),需要运行 setup 脚本将 hooks 注册到用户配置:

```bash
cd context-canary
bash setup.sh
```

这会在 `~/.claude/settings.json` 中注册 `SessionStart` 和 `Stop` hooks。

卸载时运行:

```bash
bash teardown.sh
```

## 验证

安装后启动新会话,检查终端是否出现初始化消息。查看状态文件确认金丝雀已生成:

```bash
# 状态文件位于插件 cache 目录
ls ~/.claude/plugins/cache/vincent-personal-plugins/context-canary/*/hooks/.canary_sessions/
```

正常使用 5 轮对话后,插件会自动发起第一次探测。如果上下文健康,不会有任何输出;如果退化,终端会显示类似:

```
[Canary] Context degradation confirmed (check #19)
  Context: ~23k tokens (97KB transcript, 61 messages)
  Passphrase: bravo-kilo-4827
  Suggestion: run /compact to reclaim context
```

## 文件结构

```
context-canary/
├── .claude-plugin/
│   └── plugin.json           # 插件元数据
├── hooks/
│   ├── hooks.json            # 插件级 hooks 声明(待 Claude Code 修复后生效)
│   ├── canary_init.sh        # SessionStart: 生成金丝雀口令
│   ├── canary_reinject.sh    # SessionStart (resume/compact): 恢复口令
│   └── canary_check.sh       # Stop: 两阶段探测 + 渐进式告警
├── skills/
│   └── context-canary/
│       └── SKILL.md          # 教 Claude 记住和报告口令
├── setup.sh                  # 注册 hooks 到用户配置
├── teardown.sh               # 移除 hooks
└── .gitignore
```

## 状态文件

每个 session 独立存储状态(按 `session_id` 隔离),包含:

- `canary_code` / `canary_number` — 当前口令
- `check_count` — Stop 计数器
- `probe_interval` — 当前探测间隔(5/3/1)
- `alert_level` — 当前警戒级别(normal/caution/alert)
- `consecutive_failures` — 连续失败次数
- `history` — 最近 50 次探测记录(含 transcript 大小、token 估算)

旧 session 状态文件超过 7 天自动清理。

## 依赖

- `jq` — JSON 处理(macOS 可通过 `brew install jq` 安装)
- `bash` >= 4.0