ctx-surgeon 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +153 -2
- package/README.zh-CN.md +102 -0
- package/bin/ctx-surgeon.mjs +368 -0
- package/package.json +49 -4
- package/src/adapters/claude.mjs +507 -0
- package/src/adapters/codex.mjs +533 -0
- package/src/adapters/index.mjs +115 -0
- package/src/adapters/kiki.mjs +350 -0
- package/src/discovery.mjs +143 -0
- package/src/engine/analyzer.mjs +356 -0
- package/src/engine/handoff.mjs +252 -0
- package/src/engine/surgeon.mjs +332 -0
- package/src/index.mjs +9 -0
- package/src/server.mjs +520 -0
- package/src/ui/app.js +665 -0
- package/src/ui/index.html +198 -0
- package/src/ui/styles.css +963 -0
- package/src/utils/demo.mjs +437 -0
- package/src/utils/files.mjs +276 -0
- package/src/utils/redact.mjs +120 -0
- package/src/utils/tokens.mjs +121 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ctx-surgeon contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,154 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ctx-surgeon
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Local context-rot X-Ray, surgical JSONL session trimmer, and cross-agent handoff workbench for Claude Code, Codex CLI, and Kiki.**
|
|
4
|
+
|
|
5
|
+
`127.0.0.1` only · Zero API keys · Zero cloud uploads · Zero runtime npm dependencies · Pure Node.js ≥20 ESM
|
|
6
|
+
|
|
7
|
+
[中文文档](./README.zh-CN.md)
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Why ctx-surgeon?
|
|
14
|
+
|
|
15
|
+
Long agentic coding sessions degrade well before hitting the nominal context window limit. Most of the waste is invisible from the terminal:
|
|
16
|
+
|
|
17
|
+
1. **Giant Tool Outputs** — a single verbose test log, minified bundle stat, or unfiltered command dump eats 10k–40k tokens and stays pinned in every subsequent turn.
|
|
18
|
+
2. **Repeated File Reads** — the agent re-reads the exact same file 3–10 times across edits and compactions, paying the same token cost repeatedly.
|
|
19
|
+
3. **Compaction & Context Cliffs** — sudden auto-compaction boundaries or single-step spikes silently discard earlier constraints while keeping stale tool noise.
|
|
20
|
+
|
|
21
|
+
`ctx-surgeon` lets you **X-Ray any local session JSONL**, **surgically fold specific bloated tool outputs into 1-line traceable stubs inside a safe forked copy**, or **distill a secret-redacted Handoff Pack** to continue cleanly in another session or agent.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 30-Second Quick Start
|
|
26
|
+
|
|
27
|
+
Run directly from GitHub with Node.js ≥20 (no build step, zero npm dependencies):
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# 1. Launch the local visual workbench (binds strictly to 127.0.0.1)
|
|
31
|
+
npx github:xudukongju/ctx-surgeon
|
|
32
|
+
|
|
33
|
+
# Or install globally once to use the short `ctx-surgeon` command:
|
|
34
|
+
npm install -g github:xudukongju/ctx-surgeon
|
|
35
|
+
|
|
36
|
+
# 2. Scan all local Claude Code, Codex CLI, and Kiki sessions
|
|
37
|
+
ctx-surgeon scan --limit 20
|
|
38
|
+
|
|
39
|
+
# 3. X-Ray a specific session in your terminal
|
|
40
|
+
ctx-surgeon inspect ~/.claude/projects/<project>/<session-id>.jsonl
|
|
41
|
+
|
|
42
|
+
# 4. Safely fork a trimmed copy (original file is never modified)
|
|
43
|
+
ctx-surgeon trim ~/.claude/projects/<project>/<session-id>.jsonl --gt 5000 --dedupe-reads --fork
|
|
44
|
+
|
|
45
|
+
# 5. Export a clean, secret-redacted cross-agent Handoff Pack
|
|
46
|
+
ctx-surgeon handoff ~/.codex/sessions/2026/.../rollout-*.jsonl --to claude --out handoff.md
|
|
47
|
+
|
|
48
|
+
# 6. Save a permanent SHA-256 checksummed snapshot (protects against auto-cleanup)
|
|
49
|
+
ctx-surgeon archive ~/.claude/projects/<project>/<session-id>.jsonl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
No sessions on disk yet? Launch `npx github:xudukongju/ctx-surgeon` and click **Load Demo** in the top bar to test the full X-Ray, flame bar, live budget simulator, and Handoff drawer in 5 seconds.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## How It Compares
|
|
57
|
+
|
|
58
|
+
| Tool | Primary Focus | Multi-Agent (Claude + Codex + Kiki) | Surgical Single-Item Trim & Fork | Repeated File-Read Detector | Cross-Agent Handoff Pack | Runtime Deps |
|
|
59
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
60
|
+
| **`ctx-surgeon`** | **Context X-Ray + Surgical Fork Trim + Cross-Agent Handoff** | **Yes** (3 agents) | **Yes** (safe fork + `.bak` in-place) | **Yes** (keeps latest read) | **Yes** (`claude` / `codex` / `markdown` + redaction) | **0** |
|
|
61
|
+
| `ccusage` | Cost & token usage billing tables | Claude / Codex billing | No (read-only analytics) | No | No | Multiple |
|
|
62
|
+
| `claude-code-log` | Convert JSONL transcripts to readable HTML/Markdown | Claude Code | No (read-only viewer) | No | No | Python / deps |
|
|
63
|
+
| `claude-prune` | Bulk prune/compact Claude JSONL transcripts | Claude Code | Coarse rule pruning | No | No | Node deps |
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Supported Agents & Capabilities
|
|
68
|
+
|
|
69
|
+
| Agent | Default Local Paths | X-Ray & Bloat Detection | Safe Fork Trim | In-Place Trim (`.bak`) | Handoff Pack | Archive Snapshot |
|
|
70
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
71
|
+
| **Claude Code** | `~/.claude/projects/**/*.jsonl` | Full | Yes (new UUID `sessionId`, repairs `parentUuid` chain) | Yes | Yes | Yes |
|
|
72
|
+
| **Codex CLI** | `~/.codex/sessions/**/*.jsonl`, `~/.codex/archived_sessions/*.jsonl` | Full (streaming, tested on 160MB+ files) | Yes (`rollout-<ts>-<new-uuid>.jsonl`) | Yes | Yes | Yes |
|
|
73
|
+
| **Kiki** | `~/.kiki/homes/*/sessions/**/agents/main/wire.jsonl` | Full (`loop_event`, `apply_compaction`, `usage.record`) | Disabled by design* | Disabled by design* | Yes | Yes |
|
|
74
|
+
|
|
75
|
+
\* **Why is Fork Trim disabled for Kiki?** Kiki's `wire.jsonl` is an append-only event-sourced journal rather than a flat message list. `ctx-surgeon` refuses to pretend-overwrite event-sourced logs (`capabilities.forkTrim = false`) and instead focuses on X-Ray diagnostics, Handoff Pack export, and permanent archival snapshots.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## CLI Reference
|
|
80
|
+
|
|
81
|
+
### `ctx-surgeon [ui]`
|
|
82
|
+
Start the local web workbench.
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
ctx-surgeon ui [--port 4318] [--dir <path>] [--no-open]
|
|
86
|
+
```
|
|
87
|
+
- Strictly binds to `127.0.0.1` (never `0.0.0.0`).
|
|
88
|
+
- Automatically falls back to a free loopback port if `4318` is already in use.
|
|
89
|
+
|
|
90
|
+
### `ctx-surgeon scan`
|
|
91
|
+
Fast metadata scan across local agent directories (reads only head/tail bytes during discovery so hundreds of large files list in milliseconds).
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
ctx-surgeon scan [--agent claude|codex|kiki] [--dir <path>] [--limit 20] [--sort mtime|size] [--json]
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### `ctx-surgeon inspect <file>`
|
|
98
|
+
Stream-parse a session file and output token category breakdown plus the 3 bloat detectors (Giant Tool Outputs, Repeated File Reads, Compaction & Context Cliffs).
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
ctx-surgeon inspect <file> [--gt 5000] [--json]
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### `ctx-surgeon trim <file>`
|
|
105
|
+
Headless surgical trimming for Claude Code and Codex CLI sessions.
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
ctx-surgeon trim <file> [--gt 5000] [--dedupe-reads] [--ids L5:B0,L8:B0] [--fork | --in-place] [--out <path>] [--dry-run]
|
|
109
|
+
```
|
|
110
|
+
- **Safe Fork is the default**: writes a new session file with a fresh UUID and leaves the original file byte-for-byte untouched.
|
|
111
|
+
- Replaced payloads become traceable 1-line stubs:
|
|
112
|
+
`[ctx-surgeon trimmed: Bash 18450t -> ~25t]`
|
|
113
|
+
- `--in-place` always creates and byte-verifies a `.bak` copy before atomically replacing the target. Do not run `--in-place` on a session file that is actively being appended to by a running agent process (use the default `--fork` mode instead).
|
|
114
|
+
|
|
115
|
+
### `ctx-surgeon handoff <file>`
|
|
116
|
+
Distill a clean, structured continuation prompt (`Goal`, `Workspace & Modified Files`, `Key Decisions & Constraints`, `Open Issues`, `Selected High-Signal Context`) with noisy tool outputs excluded and high-risk secrets automatically redacted.
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
ctx-surgeon handoff <file> [--to claude|codex|markdown] [--ids <id1,id2>] [--out <path>]
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### `ctx-surgeon archive <file>`
|
|
123
|
+
Copy a session byte-for-byte into `~/.ctx-surgeon/archives/<agent>/<date>/` (or `--dir`) alongside a `.meta.json` manifest containing its SHA-256 checksum and bloat summary.
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
ctx-surgeon archive <file> [--dir <backupDir>]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Safety & Privacy Guarantees
|
|
132
|
+
|
|
133
|
+
- **Loopback & origin isolation**: HTTP server binds exclusively to `127.0.0.1`, enforces strict `Host` / `Origin` / `Sec-Fetch-Site` checks, requires a per-session `X-Ctx-Surgeon-Token` CSRF header on every `/api/*` request, and confines HTTP file access strictly to allowed `.jsonl` session roots (no client-chosen `dir`, `outPath`, `inPlace`, or `archiveDir` over HTTP). No outbound network calls, no analytics, no telemetry.
|
|
134
|
+
- **Atomic verified writes**: Every trimmed JSONL file is streamed to a temporary file, validated line-by-line with `JSON.parse`, and only then atomically renamed. Avoid `--in-place` on sessions currently being written to by a live agent process; the default safe fork mode never touches the original file.
|
|
135
|
+
- **Chain integrity**: Claude Code forks assign a new `sessionId` and preserve/repair `parentUuid` links across the entire stream.
|
|
136
|
+
- **Automatic secret redaction**: Handoff Packs and diagnostic previews automatically redact API keys (`sk-ant-*`, `sk-*`, `ghp_*`, `AKIA*`, `AIza*`), JWTs, `Bearer` tokens, `Cookie` headers, private keys, and auth env pairs.
|
|
137
|
+
- **Streaming memory profile**: Built on `fs.createReadStream` + `readline` so 150MB+ Codex rollout logs parse in sub-second time without OOM.
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## Development
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
git clone https://github.com/xudukongju/ctx-surgeon.git
|
|
145
|
+
cd ctx-surgeon
|
|
146
|
+
npm test
|
|
147
|
+
node ./bin/ctx-surgeon.mjs ui
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Requires Node.js `>=20.0.0`. No `npm install` step needed.
|
|
151
|
+
|
|
152
|
+
## License
|
|
153
|
+
|
|
154
|
+
[MIT](./LICENSE)
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# ctx-surgeon
|
|
2
|
+
|
|
3
|
+
**面向 Claude Code、Codex CLI 与 Kiki 的本地 Context 腐烂 X 光诊断台、外科手术单条裁剪器与跨 Agent 无损接力工具。**
|
|
4
|
+
|
|
5
|
+
100% 本地运行(仅监听 `127.0.0.1`)· 零 API Key · 零云端上传 · 零运行时 npm 依赖 · 纯 Node.js ≥20 ESM
|
|
6
|
+
|
|
7
|
+
[English README](./README.md)
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 为什么需要 ctx-surgeon?
|
|
14
|
+
|
|
15
|
+
长时间的 Coding Agent 会话往往在真正撞上上下文上限之前就已经明显变笨、忘约束、重复犯错。绝大多数浪费藏在终端看不见的 JSONL 历史里:
|
|
16
|
+
|
|
17
|
+
1. **巨型工具输出(Giant Tool Outputs)**:一条未截断的测试全量日志、打包 stats JSON 或命令输出动辄吃掉 10k–40k tokens,并在后续每一轮持续占位。
|
|
18
|
+
2. **重复文件读取(Repeated File Reads)**:同一个源码文件在多次修改与压缩之间被反复 `Read`/`cat` 3~10 次,旧副本白白消耗预算。
|
|
19
|
+
3. **压缩断崖与尖刺(Compaction / Context Cliffs)**:自动压缩边界或单步 Token 激增让早期关键约束被挤掉,却留下了大段低价值噪声。
|
|
20
|
+
|
|
21
|
+
`ctx-surgeon` 让你能够**像拍 X 光片一样透视本地会话日志**,**按条勾选毒瘤安全 Fork 一份干净新会话(原文件零改动)**,或**一键导出自动脱敏的跨 Agent 接力包(Handoff Pack)**,在新会话或其他 Agent 中丝滑续跑。
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 30 秒快速上手
|
|
26
|
+
|
|
27
|
+
只需 Node.js ≥20,直接从 GitHub 一行运行(零依赖、免编译):
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# 1. 启动本地可视化手术台(仅绑定 127.0.0.1)
|
|
31
|
+
npx github:xudukongju/ctx-surgeon
|
|
32
|
+
|
|
33
|
+
# 或全局安装一次,之后直接使用短命令 `ctx-surgeon`:
|
|
34
|
+
npm install -g github:xudukongju/ctx-surgeon
|
|
35
|
+
|
|
36
|
+
# 2. 扫描本机所有 Claude Code / Codex CLI / Kiki 会话
|
|
37
|
+
ctx-surgeon scan --limit 20
|
|
38
|
+
|
|
39
|
+
# 3. 终端彩色 X 光拆解单个会话与 Top 毒瘤
|
|
40
|
+
ctx-surgeon inspect ~/.claude/projects/<project>/<session-id>.jsonl
|
|
41
|
+
|
|
42
|
+
# 4. 安全 Fork 裁剪一份干净会话(默认绝不改动原文件)
|
|
43
|
+
ctx-surgeon trim ~/.claude/projects/<project>/<session-id>.jsonl --gt 5000 --dedupe-reads --fork
|
|
44
|
+
|
|
45
|
+
# 5. 导出自动脱敏的跨 Agent 接力包(支持 claude / codex / markdown)
|
|
46
|
+
ctx-surgeon handoff ~/.codex/sessions/2026/.../rollout-*.jsonl --to claude --out handoff.md
|
|
47
|
+
|
|
48
|
+
# 6. 一键保存带 SHA-256 校验的本地永久归档快照(防默认自动清理)
|
|
49
|
+
ctx-surgeon archive ~/.claude/projects/<project>/<session-id>.jsonl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
本机暂时没有会话日志?运行 `npx github:xudukongju/ctx-surgeon` 后点击顶栏 **Load Demo**,5 秒即可体验完整的火焰条、毒瘤勾选、实时预算对比与接力包预览。
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 同类工具定位对比
|
|
57
|
+
|
|
58
|
+
| 工具 | 核心定位 | 多 Agent(Claude + Codex + Kiki) | 单条外科裁剪与安全 Fork | 重复读文件检测 | 跨 Agent 接力包 | 运行时依赖 |
|
|
59
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
60
|
+
| **`ctx-surgeon`** | **Context X 光诊断 + 单条外科 Fork 裁剪 + 跨 Agent 接力** | **支持三端** | **支持**(默认安全 Fork / 原地必生 `.bak`) | **支持**(保留最新一次) | **支持**(3 种目标格式 + 自动脱敏) | **0** |
|
|
61
|
+
| `ccusage` | 账单与 Token 用量统计 | Claude / Codex 计费 | 不支持(只读统计) | 不支持 | 不支持 | 多依赖 |
|
|
62
|
+
| `claude-code-log` | JSONL 转可读 HTML / Markdown | Claude Code | 不支持(只读浏览) | 不支持 | 不支持 | Python 依赖 |
|
|
63
|
+
| `claude-prune` | 按规则批量精简 Claude 会话 | Claude Code | 粗粒度规则清理 | 不支持 | 不支持 | Node 依赖 |
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 三端适配与能力边界
|
|
68
|
+
|
|
69
|
+
| Agent | 默认扫描路径 | X 光诊断与 3 类毒瘤检测 | 安全 Fork 裁剪 | 原地裁剪(必生 `.bak`) | 跨 Agent 接力包 | 永久归档快照 |
|
|
70
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
71
|
+
| **Claude Code** | `~/.claude/projects/**/*.jsonl` | 完整支持 | 支持(生成新 UUID `sessionId`,修补 `parentUuid` 链) | 支持 | 支持 | 支持 |
|
|
72
|
+
| **Codex CLI** | `~/.codex/sessions/**/*.jsonl`, `~/.codex/archived_sessions/*.jsonl` | 完整支持(流式解析,实测 160MB+ 秒开不 OOM) | 支持(同目录生成 `rollout-<ts>-<new-uuid>.jsonl`) | 支持 | 支持 | 支持 |
|
|
73
|
+
| **Kiki** | `~/.kiki/homes/*/sessions/**/agents/main/wire.jsonl` | 完整支持(`loop_event`、`apply_compaction`、`usage.record`) | 明确关闭* | 明确关闭* | 支持 | 支持 |
|
|
74
|
+
|
|
75
|
+
\* **为什么对 Kiki 明确关闭覆写/Fork 裁剪?** Kiki 的 `wire.jsonl` 是严格事件溯源(event-sourced)追加日志,直接篡改事件体存在状态重放不一致风险。`ctx-surgeon` 显式声明 `capabilities.forkTrim = false`,绝不在界面或 CLI 里假装覆写,而是聚焦 X 光诊断、毒瘤定位、跨 Agent 接力包导出与永久快照归档。
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 安全与隐私承诺
|
|
80
|
+
|
|
81
|
+
- **严格回环与跨站防护**:Web 服务只绑定 `127.0.0.1`,对全部请求校验 `Host` / `Origin` / `Sec-Fetch-Site`,全部 `/api/*` 请求强制携带每会话随机 `X-Ctx-Surgeon-Token` 并限制只读/只 Fork 白名单目录内的 `.jsonl` 会话文件(HTTP 端禁用客户端传入 `dir`、`outPath`、`inPlace`、`archiveDir`);零外网请求、零埋点、零遥测。
|
|
82
|
+
- **原子校验写回**:裁剪输出先流式写入临时文件,逐行 `JSON.parse` 校验通过后再原子替换;默认 Fork 模式原文件字节零改动,显式 `--in-place` 模式强制先创建并校验 `.bak` 备份。请勿对当前仍在活跃追加写入的会话执行 `--in-place`(默认安全 Fork 模式不受影响)。
|
|
83
|
+
- **单行可追踪折叠**:被裁剪的冗长工具输出折叠为清晰的 `[ctx-surgeon trimmed: <tool> <origTokens>t -> ~25t]` 标记,便于后续人工或模型追溯。
|
|
84
|
+
- **高风险凭据自动脱敏**:导出接力包与诊断预览时自动脱敏常见 API Key(`sk-ant-*`、`sk-*`、`ghp_*`、`AKIA*`、`AIza*`)、JWT、`Bearer` Token、`Cookie` 与私钥块。
|
|
85
|
+
- **大文件流式零 OOM**:列表阶段只读文件头尾字节提取元数据;深度 X 光与裁剪写回全程 `fs.createReadStream` + `readline` 流式处理,160MB+ 真实 Codex 日志可在 1 秒内完成解析。
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 本地开发与测试
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
git clone https://github.com/xudukongju/ctx-surgeon.git
|
|
93
|
+
cd ctx-surgeon
|
|
94
|
+
npm test
|
|
95
|
+
node ./bin/ctx-surgeon.mjs ui
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
仅需 Node.js `>=20.0.0`,无需 `npm install`。
|
|
99
|
+
|
|
100
|
+
## 开源协议
|
|
101
|
+
|
|
102
|
+
[MIT](./LICENSE)
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { discoverSessions } from '../src/discovery.mjs';
|
|
7
|
+
import { analyzeSession } from '../src/engine/analyzer.mjs';
|
|
8
|
+
import { forkCleanSession, trimInPlaceWithBackup, archiveSnapshot } from '../src/engine/surgeon.mjs';
|
|
9
|
+
import { generateHandoffPack } from '../src/engine/handoff.mjs';
|
|
10
|
+
import { startServer } from '../src/server.mjs';
|
|
11
|
+
import { formatTokens, formatBytes } from '../src/utils/tokens.mjs';
|
|
12
|
+
|
|
13
|
+
const USE_COLOR = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
|
|
14
|
+
const c = {
|
|
15
|
+
bold: (s) => (USE_COLOR ? `\x1b[1m${s}\x1b[0m` : s),
|
|
16
|
+
dim: (s) => (USE_COLOR ? `\x1b[2m${s}\x1b[0m` : s),
|
|
17
|
+
teal: (s) => (USE_COLOR ? `\x1b[36m${s}\x1b[0m` : s),
|
|
18
|
+
green: (s) => (USE_COLOR ? `\x1b[32m${s}\x1b[0m` : s),
|
|
19
|
+
red: (s) => (USE_COLOR ? `\x1b[31m${s}\x1b[0m` : s),
|
|
20
|
+
yellow: (s) => (USE_COLOR ? `\x1b[33m${s}\x1b[0m` : s)
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function printHelp() {
|
|
24
|
+
console.log(`${c.bold('ctx-surgeon')} v0.1.1 — Local Context X-Ray, Surgical Trimmer & Cross-Agent Handoff
|
|
25
|
+
|
|
26
|
+
${c.bold('Usage:')}
|
|
27
|
+
ctx-surgeon [ui] [--port 4318] [--dir <path>] [--no-open]
|
|
28
|
+
ctx-surgeon scan [--agent claude|codex|kiki] [--dir <path>] [--limit 20] [--sort mtime|size] [--json]
|
|
29
|
+
ctx-surgeon inspect <file> [--gt 5000] [--json]
|
|
30
|
+
ctx-surgeon trim <file> [--gt 5000] [--dedupe-reads] [--ids <a,b>] [--fork | --in-place] [--out <path>] [--dry-run]
|
|
31
|
+
ctx-surgeon handoff <file> [--to claude|codex|markdown] [--ids <a,b>] [--out <path>]
|
|
32
|
+
ctx-surgeon archive <file> [--dir <backupDir>]
|
|
33
|
+
|
|
34
|
+
${c.bold('Guarantees:')}
|
|
35
|
+
- 100% local (127.0.0.1 only, zero telemetry, zero API keys, zero runtime dependencies)
|
|
36
|
+
- Safe fork by default; --in-place always creates a verified .bak backup first
|
|
37
|
+
- Kiki wire.jsonl is treated as read-only (X-Ray, Handoff Pack, and Archive supported)
|
|
38
|
+
`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function openBrowser(url) {
|
|
42
|
+
const platform = process.platform;
|
|
43
|
+
const cmd = platform === 'darwin' ? 'open' : (platform === 'win32' ? 'cmd' : 'xdg-open');
|
|
44
|
+
const args = platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
45
|
+
try {
|
|
46
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
47
|
+
child.unref();
|
|
48
|
+
} catch {
|
|
49
|
+
// Ignore browser launch errors in headless environments
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function renderBar(ratio, width = 24) {
|
|
54
|
+
const clamped = Math.max(0, Math.min(1, ratio));
|
|
55
|
+
const filled = Math.round(clamped * width);
|
|
56
|
+
return `${'█'.repeat(filled)}${'░'.repeat(width - filled)}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function runUi(argv) {
|
|
60
|
+
const { values } = parseArgs({
|
|
61
|
+
args: argv,
|
|
62
|
+
options: {
|
|
63
|
+
port: { type: 'string', short: 'p', default: '4318' },
|
|
64
|
+
dir: { type: 'string' },
|
|
65
|
+
'no-open': { type: 'boolean', default: false },
|
|
66
|
+
help: { type: 'boolean', short: 'h', default: false }
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
if (values.help) return printHelp();
|
|
70
|
+
|
|
71
|
+
const srv = await startServer({
|
|
72
|
+
port: Number(values.port) || 4318,
|
|
73
|
+
defaultDir: values.dir,
|
|
74
|
+
extraDirs: values.dir ? [values.dir] : []
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
console.log(`\n ${c.bold('ctx-surgeon')} surgical workbench running locally`);
|
|
78
|
+
console.log(` ${c.teal(srv.url)} ${c.dim('(loopback 127.0.0.1 only · press Ctrl+C to stop)')}\n`);
|
|
79
|
+
|
|
80
|
+
if (!values['no-open']) {
|
|
81
|
+
openBrowser(srv.url);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const shutdown = async () => {
|
|
85
|
+
await srv.close();
|
|
86
|
+
process.exit(0);
|
|
87
|
+
};
|
|
88
|
+
process.on('SIGINT', shutdown);
|
|
89
|
+
process.on('SIGTERM', shutdown);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function runScan(argv) {
|
|
93
|
+
const { values } = parseArgs({
|
|
94
|
+
args: argv,
|
|
95
|
+
options: {
|
|
96
|
+
agent: { type: 'string', short: 'a', default: 'all' },
|
|
97
|
+
dir: { type: 'string' },
|
|
98
|
+
file: { type: 'string' },
|
|
99
|
+
limit: { type: 'string', short: 'n', default: '20' },
|
|
100
|
+
sort: { type: 'string', default: 'mtime' },
|
|
101
|
+
json: { type: 'boolean', default: false },
|
|
102
|
+
help: { type: 'boolean', short: 'h', default: false }
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
if (values.help) return printHelp();
|
|
106
|
+
|
|
107
|
+
const res = await discoverSessions({
|
|
108
|
+
agent: values.agent,
|
|
109
|
+
dir: values.dir,
|
|
110
|
+
file: values.file,
|
|
111
|
+
limit: Number(values.limit) || 20,
|
|
112
|
+
sort: values.sort
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
if (values.json) {
|
|
116
|
+
console.log(JSON.stringify(res, null, 2));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
console.log(`${c.bold('Local Sessions')} (${res.returned} shown / ${res.totalDiscovered} discovered)\n`);
|
|
121
|
+
if (res.sessions.length === 0) {
|
|
122
|
+
console.log(c.dim('No Claude Code, Codex CLI, or Kiki JSONL sessions found.'));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const header = `${'AGENT'.padEnd(8)} ${'SIZE'.padStart(9)} ${'UPDATED'.padEnd(16)} ${'MODEL'.padEnd(20)} PATH`;
|
|
127
|
+
console.log(c.dim(header));
|
|
128
|
+
for (const s of res.sessions) {
|
|
129
|
+
const updated = new Date(s.mtimeMs).toISOString().slice(0, 16).replace('T', ' ');
|
|
130
|
+
const model = String(s.model || '-').slice(0, 20).padEnd(20);
|
|
131
|
+
const agentTag = s.agent.toUpperCase().padEnd(8);
|
|
132
|
+
const sizeCol = formatBytes(s.fileSize).padStart(9);
|
|
133
|
+
console.log(`${c.teal(agentTag)} ${sizeCol} ${updated} ${c.dim(model)} ${s.filePath}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function runInspect(argv) {
|
|
138
|
+
const { values, positionals } = parseArgs({
|
|
139
|
+
args: argv,
|
|
140
|
+
allowPositionals: true,
|
|
141
|
+
options: {
|
|
142
|
+
gt: { type: 'string', default: '5000' },
|
|
143
|
+
json: { type: 'boolean', default: false },
|
|
144
|
+
help: { type: 'boolean', short: 'h', default: false }
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
if (values.help || positionals.length === 0) return printHelp();
|
|
148
|
+
|
|
149
|
+
const filePath = path.resolve(positionals[0]);
|
|
150
|
+
const report = await analyzeSession(filePath, { giantThreshold: Number(values.gt) || 5000 });
|
|
151
|
+
|
|
152
|
+
if (values.json) {
|
|
153
|
+
// Emit structured report without duplicating full verbose event arrays when huge
|
|
154
|
+
const compact = {
|
|
155
|
+
meta: report.meta,
|
|
156
|
+
capabilities: report.capabilities,
|
|
157
|
+
reportedUsage: report.reportedUsage,
|
|
158
|
+
thresholds: report.thresholds,
|
|
159
|
+
totals: report.totals,
|
|
160
|
+
breakdown: report.breakdown,
|
|
161
|
+
bloat: report.bloat,
|
|
162
|
+
recommendedTrimIds: report.recommendedTrimIds,
|
|
163
|
+
modifiedFiles: report.modifiedFiles
|
|
164
|
+
};
|
|
165
|
+
console.log(JSON.stringify(compact, null, 2));
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
console.log(`\n${c.bold('Context X-Ray')} ${c.teal(report.meta.agent.toUpperCase())} ${c.dim(report.meta.filePath)}`);
|
|
170
|
+
const bloatMetric = report.capabilities.forkTrim
|
|
171
|
+
? `Recoverable: ${c.green(`-${formatTokens(report.totals.recommendedSavings)}t (-${report.totals.recommendedSavingsPct}%)`)}`
|
|
172
|
+
: `Detected Bloat: ${c.yellow(`${formatTokens(report.totals.bloatTokens)}t (${report.totals.bloatPct}%)`)}`;
|
|
173
|
+
|
|
174
|
+
console.log(
|
|
175
|
+
`Size: ${c.bold(formatBytes(report.meta.fileSize))} · Events: ${report.meta.eventCount} · ` +
|
|
176
|
+
`Context: ${c.bold(formatTokens(report.totals.tokens) + 't')} · ` +
|
|
177
|
+
`${bloatMetric} · ` +
|
|
178
|
+
`${c.dim(`${report.meta.parseMs}ms`)}`
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
console.log(`\n${c.bold('Token Breakdown')}`);
|
|
182
|
+
const total = Math.max(1, report.totals.tokens);
|
|
183
|
+
for (const [key, label] of [
|
|
184
|
+
['tool_output', 'Tool Outputs'],
|
|
185
|
+
['assistant', 'Assistant'],
|
|
186
|
+
['user', 'User'],
|
|
187
|
+
['thinking', 'Thinking'],
|
|
188
|
+
['tool_call', 'Tool Calls'],
|
|
189
|
+
['system', 'System']
|
|
190
|
+
]) {
|
|
191
|
+
const b = report.breakdown[key];
|
|
192
|
+
const ratio = b.tokens / total;
|
|
193
|
+
const pct = (ratio * 100).toFixed(1).padStart(5);
|
|
194
|
+
console.log(` ${label.padEnd(14)} ${renderBar(ratio)} ${formatTokens(b.tokens).padStart(7)}t ${c.dim(`${pct}% (${b.count})`)}`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
console.log(`\n${c.bold('1. Giant Tool Outputs')} (> ${formatTokens(report.thresholds.giantToolOutput)}t): ${c.red(String(report.bloat.giantToolOutputs.length))}`);
|
|
198
|
+
for (const g of report.bloat.giantToolOutputs.slice(0, 10)) {
|
|
199
|
+
console.log(` ${c.red(g.id.padEnd(8))} ${formatTokens(g.tokens).padStart(7)}t ${c.bold(g.toolName.padEnd(18))} ${c.dim(g.preview.slice(0, 72))}`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
console.log(`\n${c.bold('2. Repeated File Reads')} (>= 3x): ${c.yellow(String(report.bloat.repeatedFileReads.length))}`);
|
|
203
|
+
for (const rep of report.bloat.repeatedFileReads.slice(0, 10)) {
|
|
204
|
+
console.log(` ${c.yellow(`${rep.readCount}x`.padEnd(5))} ${c.bold(rep.filePath)} ${c.dim(`wasted ~${formatTokens(rep.wastedTokens)}t across ${rep.redundantEventIds.length} older read(s)`)}`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
console.log(`\n${c.bold('3. Compaction & Context Cliffs')}: ${report.bloat.cliffs.length}`);
|
|
208
|
+
for (const cliff of report.bloat.cliffs.slice(0, 8)) {
|
|
209
|
+
const beforeStr = cliff.tokensBefore ? ` before=${formatTokens(cliff.tokensBefore)}t` : '';
|
|
210
|
+
const afterStr = cliff.tokensAfter ? ` after=${formatTokens(cliff.tokensAfter)}t` : '';
|
|
211
|
+
console.log(` ${c.teal(`L${cliff.lineNumber}`.padEnd(8))} ${cliff.kind.padEnd(20)}${beforeStr}${afterStr} ${c.dim(cliff.summaryPreview.slice(0, 64))}`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (!report.capabilities.forkTrim) {
|
|
215
|
+
console.log(`\n${c.yellow('Note:')} ${report.capabilities.trimDisabledReason}`);
|
|
216
|
+
}
|
|
217
|
+
console.log('');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function runTrim(argv) {
|
|
221
|
+
const { values, positionals } = parseArgs({
|
|
222
|
+
args: argv,
|
|
223
|
+
allowPositionals: true,
|
|
224
|
+
options: {
|
|
225
|
+
gt: { type: 'string', default: '5000' },
|
|
226
|
+
'dedupe-reads': { type: 'boolean', default: false },
|
|
227
|
+
ids: { type: 'string' },
|
|
228
|
+
fork: { type: 'boolean', default: false },
|
|
229
|
+
'in-place': { type: 'boolean', default: false },
|
|
230
|
+
out: { type: 'string', short: 'o' },
|
|
231
|
+
'dry-run': { type: 'boolean', default: false },
|
|
232
|
+
json: { type: 'boolean', default: false },
|
|
233
|
+
help: { type: 'boolean', short: 'h', default: false }
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
if (values.help || positionals.length === 0) return printHelp();
|
|
237
|
+
|
|
238
|
+
const filePath = path.resolve(positionals[0]);
|
|
239
|
+
const ids = values.ids ? values.ids.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
|
|
240
|
+
const opts = {
|
|
241
|
+
gt: Number(values.gt) || 5000,
|
|
242
|
+
dedupeReads: Boolean(values['dedupe-reads']),
|
|
243
|
+
ids,
|
|
244
|
+
outPath: values.out,
|
|
245
|
+
dryRun: Boolean(values['dry-run'])
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const result = values['in-place']
|
|
249
|
+
? await trimInPlaceWithBackup(filePath, opts)
|
|
250
|
+
: await forkCleanSession(filePath, opts);
|
|
251
|
+
|
|
252
|
+
if (values.json) {
|
|
253
|
+
console.log(JSON.stringify(result, null, 2));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const label = result.dryRun ? c.yellow('DRY RUN') : c.green('SURGERY COMPLETE');
|
|
258
|
+
console.log(`\n${label} (${result.mode} · ${result.agent})`);
|
|
259
|
+
console.log(` Source: ${result.sourcePath}`);
|
|
260
|
+
console.log(` Output: ${result.destPath}`);
|
|
261
|
+
if (result.backupPath) console.log(` Backup: ${result.backupPath}`);
|
|
262
|
+
if (result.newSessionId) console.log(` Session: ${result.newSessionId}`);
|
|
263
|
+
console.log(
|
|
264
|
+
` Tokens: ${formatTokens(result.simulation.beforeTokens)}t -> ` +
|
|
265
|
+
`${c.green(formatTokens(result.simulation.afterTokens) + 't')} ` +
|
|
266
|
+
`${c.bold(`(-${result.simulation.savedPct}%, ${result.trimmedCount} trimmed)`)}\n`
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function runHandoff(argv) {
|
|
271
|
+
const { values, positionals } = parseArgs({
|
|
272
|
+
args: argv,
|
|
273
|
+
allowPositionals: true,
|
|
274
|
+
options: {
|
|
275
|
+
to: { type: 'string', default: 'markdown' },
|
|
276
|
+
ids: { type: 'string' },
|
|
277
|
+
out: { type: 'string', short: 'o' },
|
|
278
|
+
help: { type: 'boolean', short: 'h', default: false }
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
if (values.help || positionals.length === 0) return printHelp();
|
|
282
|
+
|
|
283
|
+
const filePath = path.resolve(positionals[0]);
|
|
284
|
+
const ids = values.ids ? values.ids.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
|
|
285
|
+
const pack = await generateHandoffPack(filePath, { to: values.to, selectedIds: ids });
|
|
286
|
+
|
|
287
|
+
if (values.out) {
|
|
288
|
+
const outPath = path.resolve(values.out);
|
|
289
|
+
await fs.promises.mkdir(path.dirname(outPath), { recursive: true });
|
|
290
|
+
await fs.promises.writeFile(outPath, pack.content, 'utf8');
|
|
291
|
+
console.log(
|
|
292
|
+
`${c.green('Handoff written:')} ${outPath} ` +
|
|
293
|
+
`(${formatTokens(pack.stats.packTokens)}t, -${pack.stats.compressionPct}%, ${pack.stats.redactions} secrets redacted)`
|
|
294
|
+
);
|
|
295
|
+
} else {
|
|
296
|
+
process.stdout.write(pack.content);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function runArchive(argv) {
|
|
301
|
+
const { values, positionals } = parseArgs({
|
|
302
|
+
args: argv,
|
|
303
|
+
allowPositionals: true,
|
|
304
|
+
options: {
|
|
305
|
+
dir: { type: 'string', short: 'd' },
|
|
306
|
+
json: { type: 'boolean', default: false },
|
|
307
|
+
help: { type: 'boolean', short: 'h', default: false }
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
if (values.help || positionals.length === 0) return printHelp();
|
|
311
|
+
|
|
312
|
+
const filePath = path.resolve(positionals[0]);
|
|
313
|
+
const result = await archiveSnapshot(filePath, { archiveDir: values.dir });
|
|
314
|
+
|
|
315
|
+
if (values.json) {
|
|
316
|
+
console.log(JSON.stringify(result, null, 2));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
console.log(`\n${c.green('Archive snapshot saved')}`);
|
|
321
|
+
console.log(` Snapshot: ${result.archivePath}`);
|
|
322
|
+
console.log(` Manifest: ${result.manifestPath}`);
|
|
323
|
+
console.log(` Size: ${formatBytes(result.bytes)}`);
|
|
324
|
+
console.log(` SHA-256: ${result.sha256}\n`);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function main() {
|
|
328
|
+
const rawArgs = process.argv.slice(2);
|
|
329
|
+
if (rawArgs.includes('--version') || rawArgs.includes('-v')) {
|
|
330
|
+
console.log('0.1.1');
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const first = rawArgs[0];
|
|
335
|
+
if (!first || first.startsWith('-')) {
|
|
336
|
+
if (first === '--help' || first === '-h') return printHelp();
|
|
337
|
+
return runUi(rawArgs);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const sub = first.toLowerCase();
|
|
341
|
+
const rest = rawArgs.slice(1);
|
|
342
|
+
|
|
343
|
+
switch (sub) {
|
|
344
|
+
case 'ui':
|
|
345
|
+
return runUi(rest);
|
|
346
|
+
case 'scan':
|
|
347
|
+
return runScan(rest);
|
|
348
|
+
case 'inspect':
|
|
349
|
+
return runInspect(rest);
|
|
350
|
+
case 'trim':
|
|
351
|
+
return runTrim(rest);
|
|
352
|
+
case 'handoff':
|
|
353
|
+
return runHandoff(rest);
|
|
354
|
+
case 'archive':
|
|
355
|
+
return runArchive(rest);
|
|
356
|
+
case 'help':
|
|
357
|
+
return printHelp();
|
|
358
|
+
default:
|
|
359
|
+
console.error(`Unknown command: ${first}\n`);
|
|
360
|
+
printHelp();
|
|
361
|
+
process.exitCode = 1;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
main().catch((err) => {
|
|
366
|
+
console.error(`${c.red('Error:')} ${err instanceof Error ? err.message : String(err)}`);
|
|
367
|
+
process.exitCode = 1;
|
|
368
|
+
});
|