用 Claude Code 做长一点的任务,常会碰到几种情况:会话越拉越长,好像越来越慢、越来越贵;压缩之后它像是忘了点什么;走错了路,你一层层纠正,它越改越乱。这些都和「会话怎么管」有关。
这篇教程讲清楚 Claude Code 每做完一步你有哪几个选择,每个选择背后的成本是怎么算的,再用一组实测看它们在一个小项目里的实际效果。读完你能做到:每一轮都知道该接着聊、回退、压缩还是清空,并会用 /usage 和 /context 看效果。
练习项目接着 用 Skill 搭验证闭环 那个积分台账。需要先装好 Claude Code 并登录,方法见 Claude Code 官方安装说明。
我们在积分台账项目上做了四组对照:继续 / 清空每种做法 4 次,其余每种做法 2 次;改代码的结果都用独立的检查脚本判定对不对。
| 场景 | 对照 | 结果都对吗 | 那一步的花费(美元) | 之后的上下文(token) |
|---|---|---|---|---|
| 走错路之后 | 就地纠正 / 回退后重说 | 2/2 / 2/2 | 0.19、0.26 / 0.20、0.18 | 约 4.0–4.5 万 / 约 3.1 万 |
| 一个阶段做完,下一步要用早先交代的事 | 不压缩 / /compact / /compact 提示 |
6 次都对 | 0.08–0.10 / 0.27–0.29 / 约 0.24 | 3.5–3.9 万 / 2.9–3.1 万 / 2.6–2.7 万 |
| 下一件事用得上刚读过的文件(各 4 次) | 继续 / 清空重来 | 两种都答了 | 0.038–0.042 / 0.11–0.12 | 3.3–4.6 万 / 约 2.2 万 |
| 要从 50 万字的日志里找结论 | 自己读 / 交给子代理 | 4 次都答对 | 0.11、0.14 / 0.26、0.26 | 差不多(22,639、23,380 / 21,897、21,783) |
几条读法:
/compact 也完整保留了早先交代的事,6 次结果都对;压缩本身和压缩后重建缓存,让那一步贵了两到三倍。grep | sort | uniq -c,只拿回几行,交给子代理反而贵了一倍。样本小(每种做法两遍)、项目小、会话短,这些数字是方向,不是精确值;原文那些建议主要针对的是长会话,我们没有测几十万 token 的长会话。
Claude Code 每发一次请求,都会把系统提示、工具定义、CLAUDE.md、到目前为止的整段对话(包括它读过的每个文件、跑过的每条命令的输出)一起发给模型。一个任务往往要发好几次请求:读文件、改代码、跑测试,每一步都是一次。
这听起来很贵,实际上有提示缓存(prompt cache)兜着:如果这次请求的开头和上一次完全一样,那一段就从缓存里读,价格只有正常输入的十分之一左右;只有新加上的部分按全价算。所以平时追加内容很便宜,贵的是让缓存作废。
在我们的实测里,一个刚开的会话第一次请求就有约 1.8 万 token(其中前 13,083 个从缓存读到,我们推测主要是系统提示和工具定义);读完四个源文件后,整段上下文约 2.25 万。之后每多一轮,这 2 万多 token 都要再发一遍。
缓存会在什么时候作废?我们从同一个会话快照恢复,再发一句「只回答 OK」,看这一次请求有多少从缓存读、多少要重新写:
| 恢复时的做法 | 从缓存读 | 重新写入缓存 | 这一轮花费(美元) |
|---|---|---|---|
| 设置不变,马上恢复 | 22,364 | 1,852 | 0.019 |
| 思考力度从 high 改成 low | 22,364 | 1,852 | 0.019 |
| 换成 Sonnet 5.5 | 13,083 | 11,091 | 0.046 |
先 /compact 再问 |
13,083 | 8,786 | 0.073(另加压缩本身 0.079) |
| 离开 65 分钟后恢复 | 13,083 | 11,133 | 0.092 |
| 紧接着再问一次 | 24,216 | 13 | 0.005 |
/effort 会让缓存作废,所以最稳的做法仍是开会话前就定好。promptCacheTtl 设置改成一小时)。E5 主会话的缓存写入都标着一小时;子代理的请求按文档用五分钟,E4 里两次子代理的写入(约 1.8 万 token)也都标着五分钟。所以有两个顺手的习惯:开会话前用 /model 和 /effort 定好,别在长会话中途切;如果反正要压缩,就在离开前压:压缩要让模型读完整段对话,缓存还在时读得便宜。这一条来自原文和上面的计费方式,我们没有测「离开前压缩」和「回来后压缩」的差价。
Claude 做完一步,你有五种走法:
| 情况 | 选 | 为什么 |
|---|---|---|
| 同一件事,刚读过的东西还要用 | 继续 | 上下文里的东西都还有用,没必要重建 |
| 走错了路 | 回退(/rewind,或输入框为空时连按两次 Esc) |
保留有用的读文件结果,扔掉失败的尝试,带着学到的东西重说 |
| 同一件事,但前面堆了一大段已经没用的调试 | /compact 提示 |
让它总结,告诉它保留什么、丢什么 |
| 换一件不相干的事 | /clear,再写几句交接 |
从零开始,带过去什么由你决定 |
| 下一步会产生大量输出,你只要结论 | 交给子代理 | 中间输出留在子代理的上下文里,只带回结论 |
下面一种一种看。
我们让 Claude 先读项目,再给它一个合理但后来被否掉的需求:「每周上限按滚动 7 天算」。它照做,改了规则、生成器、台账和测试。接着两种做法:
结果两种做法 4 次都通过了独立检查(包括跨年、北京时间周日 23 点和周一 0 点半这些边界)。差别在之后:就地纠正的会话里留着整段滚动窗口的实现、测试输出和改回来的过程,上下文 4.0–4.5 万 token;回退重说的只有 3.1 万。之后每一轮都要多带这 1 万多 token,而且模型要在一段被否掉的实现旁边继续想问题。
回退这一步本身不花钱:它只是把对话末尾那几轮剪掉,前面的部分还在缓存里。
用法:在输入框为空时连按两次 Esc,或输入 /rewind,选一条之前的消息。菜单里有几种恢复方式:
要注意的一点:回退能撤销的是 Claude 用编辑工具改过的文件。只被 Bash 命令改过的文件不在追踪范围内(比如它用 sed 改的、make gen 生成的),回退之后要自己用 git 恢复。所以有 git 兜底时回退最放心。
还有一个旁证。我们一开始给的「错误」更明显:「判断是不是同一周就用 isocalendar().week」。这会让 2026 年第 1 周和 2027 年第 1 周算成同一周。4 次里 Claude 都没照做,而是按 (ISO 年, 周) 写,并提醒了跨年问题。所以「走错路」更多是需求本身改了,而不是它犯了个低级错误,这正是回退最常用的场合。
原文提到一种「坏压缩」:会话一直在调试 A,压缩时模型猜不到你下一步要做 B,于是把 B 的细节扔了。
我们这样测:第一句话交代两件事,① 加每周上限,② 「运营说 comment 每次的分数下周要从 2 改成 3,等我说了再改,现在不要动」。做完 ① 之后再让它把测试逐个讲一遍,拉长会话。然后分三种:不压缩;普通 /compact;带提示的 /compact 接下来要做的是我一开始记下的第二件事,保留它的全部细节;每周上限的调试过程可以丢掉。最后只说一句「好,现在做我一开始让你先记下的第二件事」,不提具体内容。
结果 6 次都改对了(改 rules.toml、跑 make gen、测试通过),4 份压缩摘要里都完整保留了第二件事,连「等我说了再改」都写着。
在这么短的会话里,压缩没有丢东西,但它不便宜:压缩本身约 0.09 美元,压缩后下一轮还要重建缓存,有时还要重新读文件。从压缩开始算,普通压缩那一步花了 0.27–0.29 美元,带提示的约 0.24,不压缩的只要 0.08–0.10。省下的是之后的上下文:不压缩的 3.5–3.9 万 token,普通压缩后 2.9–3.1 万,带提示的 2.6–2.7 万。
所以我们的建议是:
/autocompact 200k 设一个更小的窗口(需要 Claude Code 2.1.221 以上)。/clear 会开一个空白的新会话(旧会话保留着,可以 /resume 找回;想以后好找,先 /rename 起个名字)。
我们在上面「走错路」那几个会话的最后,各问了一个问题:「解释一下 tools/gen_rules.py 是怎么把 rules.toml 变成 Python 的」,一次接着问,一次清空后在新会话里问。这个文件在第一步就读过。
| 接着问 | 清空后问 | |
|---|---|---|
| 读文件 / 跑命令 | 0 次 | 2–4 次 |
| 这一轮花费(美元) | 0.038–0.042 | 0.11–0.12 |
| 问完后的上下文(token) | 3.3–4.6 万 | 约 2.2 万 |
清空后它要重新读文件、重新建缓存,这一问贵了约三倍;换来的是之后每一轮少带 1–2.3 万 token。哪边划算,看之后还要聊多少轮、还用不用得上前面的东西。我们的判断方法:
清空之前花半分钟写几句交接,放进新会话的第一句话:在做什么、约束是什么、关键文件是哪几个、哪些路已经试过不通。这比让它从头摸索便宜得多。
子代理有自己独立的上下文,不带你的对话,做完只把结论交回主会话。适合会产生大量中间输出、而你只要结论的活:翻日志、全库搜索、对照规格检查结果。
我们准备了 4 个日志文件,共 5,408 行、约 50 万字符,问「被每日上限挡住次数最多的 3 个用户」。一次直接问,一次加一句「用一个子代理去读日志,只把结论带回来」。
4 次都答对了(23、19、16 次)。但直接问的那两次,Claude 用 grep ... | sort | uniq -c 只拿回几行结果,主会话本来就没被撑大;交给子代理的那两次,子代理自己发了 6–7 次请求、建了自己的缓存,花费 0.26 美元,是直接问的两倍左右,主会话的上下文却几乎一样。
所以子代理的价值在于「隔离输出」,前提是那份输出真的会很大。如果 Claude 自己就能用命令把输出压到几行,子代理就是额外开销。值得交给子代理的,是那种要逐个打开文件、读完才能下判断的活。经常要交出去的同一类活,可以单独定义一个子代理,并指定 model: haiku 或 sonnet,不然它会跟主会话用同一个模型。
@ 引用文件。 在消息里写 @src/points/ledger.py,文件会直接附在第一条请求里,省一次读文件的调用;同一个会话里提一次就够了,再提会再附一份。make test」(它的 unittest 带了 -q,通过时只打印几行)。超过约 3 万字符的输出,Claude Code 会存成文件,只在会话里放预览和路径;真正占地方的是几千行、又没超这个上限的输出。/context。 它显示上下文里都装了什么(CLAUDE.md、MCP 工具定义等),能看出启动时就占了多少,哪些用不到可以关掉。/usage 看花费和缓存。 它显示本次会话的用量和套餐额度,里面的「Prompt cache」一行能看出缓存命中率、现在是不是还热着。/rewind 只能在交互界面里用,所以我们在无界面模式(claude -p)下这样模拟它:在回退点复制一份会话记录、给代码打一个 git 标签;要回退时把会话记录换回那一份、git reset --hard 到那个标签,再用 --resume 接着发消息。这是模拟,不完全等同于交互里的「恢复代码和对话」:git reset --hard 会把所有被 git 跟踪的文件都退回去,包括 make gen 这类 Bash 命令生成的文件,而交互里的回退可能把它们留在原样(见上文)。/compact 在无界面模式下官方文档没有写,我们实测 claude -p "/compact ..." --resume <会话 id> 可以用。
1. 准备项目。 按 上一篇附录 建好积分台账项目,放在 practice/skill-verify/;本文附录的四个脚本放在旁边的 practice/session/。measure.py 每次会把项目复制到 ~/aiworkspace/claude/i1742-session/runs/ 下(在你的仓库外,免得读到仓库自己的 CLAUDE.md),不带 .claude/ 目录(仓库里的练习副本带的是 CLAUDE.md.example,会改名成 CLAUDE.md;照上一篇附录建的项目本来就有 CLAUDE.md),生成日志,再 git 提交一次作为干净基线。
2. 运行。 在 practice/session/ 里:
python3 measure.py E1,E2,E4 2 # 三组对照,各两遍
python3 measure.py E5 1 # 缓存探测,含一次 65 分钟的等待
每一轮调用的命令是:
第一轮用 --session-id 新建会话,之后几轮把它换成 --resume "$SID":
SID=$(uuidgen | tr A-Z a-z)
claude -p "这一轮的话" --session-id "$SID" \
--setting-sources project \
--settings '{"claudeMdExcludes":["/Users/你的用户名/.claude/CLAUDE.md"],"autoMemoryEnabled":false}' \
--permission-mode acceptEdits \
--allowedTools "Bash(make *)" "Bash(python3 *)" "Bash(git diff*)" "Bash(git status*)" "Bash(ls *)" "Bash(cat *)" "Bash(grep *)" "Bash(wc *)" "Bash(head *)" "Bash(tail *)" "Bash(sort *)" "Bash(awk *)" Agent Task \
--output-format stream-json --verbose
--setting-sources 和 --settings 用来排除你自己的全局 CLAUDE.md 和自动记忆;claudeMdExcludes 里写你自己用户目录的绝对路径。--allowedTools 列出的会直接执行,不用确认;没列的命令不一定会被拦,被判定为只读的照常执行。每一轮发的话都写在 measure.py 开头的常量里。
3. 看结果。 results.jsonl 每行一轮,cost_usd 和 turn_tokens 是这一轮(含子代理和压缩本身)的花费和 token,last_context 是这一轮最后一次请求的上下文大小(输入 + 缓存读 + 缓存写)。注意:恢复会话后,结果里的 total_cost_usd 是整个会话累计的,要看单轮得用 model_usage_since_last_result。代码对不对看 step 为 check 的行,它们来自 check_weekly.py 和 check_note.py。
4. 用量。 这组实测(含第一版 E1 的 4 次)按 Claude Code 报告的估算,模型用量约 10 美元(另有一次脚本出错、中途停掉的约 1 美元未计入);E1–E4 共约 45 分钟,E5 因为要等 65 分钟,约 70 分钟。
/compact 后面写明下一步要做什么。长期都要保留的,写进 CLAUDE.md 的「Compact Instructions」。/resume 找;清空前先 /rename 起个名字更好找。积分台账项目与 上一篇附录 相同(不需要 .claude/skills/)。本文新增四个脚本,放在 practice/session/。
make_logs.py:
"""Write four days of award logs for the subagent experiment (deterministic). Usage: make_logs.py <dir>."""
import pathlib
import random
import sys
# Answer key: limited counts for the top users are fixed; everyone else stays at or below 6.
TOP = {"u0417": 23, "u0082": 19, "u0350": 16}
out = pathlib.Path(sys.argv[1])
out.mkdir(parents=True, exist_ok=True)
rng = random.Random(1742)
lines = []
for user, n in TOP.items():
lines += [(user, "comment", "limited")] * n
for i in range(1, 400):
user = f"u{i:04d}"
if user in TOP:
continue
lines += [(user, "comment", "limited")] * rng.randint(0, 6)
lines += [(f"u{rng.randint(1, 399):04d}", rng.choice(["comment", "daily_login", "signup"]), "awarded") for _ in range(4200)]
rng.shuffle(lines)
pts = {"comment": 2, "daily_login": 5, "signup": 100}
for day in range(4):
chunk = lines[day::4]
with open(out / f"award-2026-11-{21 + day}.log", "w") as f:
for k, (user, event, result) in enumerate(chunk):
sec = k * 86400 // len(chunk)
f.write(f"2026-11-{21 + day}T{sec // 3600:02d}:{sec // 60 % 60:02d}:{sec % 60:02d}+08:00 "
f"req={rng.getrandbits(48):012x} user={user} event={event} result={result} "
f"points={pts[event] if result == 'awarded' else 0}\n")
check_weekly.py:
"""Independent check of the weekly limit (run with PYTHONPATH=src POINTS_TZ=Asia/Shanghai). Exit 0 = all pass."""
import sys
from datetime import datetime, timezone
from points.ledger import Ledger
from points.rules_gen import RULES
def utc(y, m, d, h=4, mi=0): # 04:00 UTC = 12:00 Beijing
return datetime(y, m, d, h, mi, tzinfo=timezone.utc)
def fill(led, user): # Mon 2026-03-02 x3, Tue x2: the week's 5
return [led.award(user, "share", utc(2026, 3, 2)) for _ in range(4)] + [led.award(user, "share", utc(2026, 3, 3)) for _ in range(3)]
checks = {}
r = RULES.get("share", {})
if not r:
print("FAIL no share event")
sys.exit(1)
checks["rule share 10/3/5"] = (r.get("points"), r.get("daily_limit"), r.get("weekly_limit")) == (10, 3, 5)
led = Ledger()
checks["daily then weekly limit"] = fill(led, "u") == [10, 10, 10, 0, 10, 10, 0]
checks["next week resets"] = led.award("u", "share", utc(2026, 3, 9)) == 10
checks["other user unaffected"] = led.award("w", "share", utc(2026, 3, 3)) == 10
led = Ledger()
for day in (29, 30): # 2026-W01 starts Mon 2025-12-29
for _ in range(3):
led.award("v", "share", utc(2025, 12, day))
checks["cross-year: 2027-W01 is not 2026-W01"] = led.award("v", "share", utc(2027, 1, 5)) == 10
led = Ledger()
fill(led, "z")
checks["Sun 23:00 Beijing still same week"] = led.award("z", "share", utc(2026, 3, 8, 15)) == 0
checks["Mon 00:30 Beijing is a new week"] = led.award("z", "share", utc(2026, 3, 8, 16, 30)) == 10
led = Ledger()
checks["comment still 10/day, no weekly cap"] = [led.award("c", "comment", utc(2026, 3, 2 + i // 10)) for i in range(30)].count(0) == 0
for k, v in checks.items():
print(("PASS " if v else "FAIL ") + k)
sys.exit(0 if all(checks.values()) else 1)
check_note.py:
"""E2 check: the side note (comment 2 -> 3) was done through rules.toml + make gen, and the weekly work survived."""
import pathlib
import subprocess
import sys
import tomllib
from points.rules_gen import RULES
checks = {
"rules.toml comment = 3": tomllib.loads(pathlib.Path("rules.toml").read_text())["comment"]["points"] == 3,
"rules_gen comment = 3": RULES["comment"]["points"] == 3,
"weekly check passes": subprocess.run([sys.executable, str(pathlib.Path(__file__).with_name("check_weekly.py"))],
capture_output=True).returncode == 0,
}
for k, v in checks.items():
print(("PASS " if v else "FAIL ") + k)
sys.exit(0 if all(checks.values()) else 1)
measure.py:
"""Measure session-management moves in Claude Code on the points ledger (#1742 article 2).
Experiments (each multi-turn, headless, isolated from the user's CLAUDE.md, plugins, hooks and auto memory):
E1 went down a wrong path: correct in place (A) vs rewind to before it and re-prompt (B);
then an unrelated question in the same session (E3 "continue") vs a fresh session (E3 "clear").
E2 a side note given early, a long first task, then compaction: none (A) / plain /compact (B) /
/compact with a hint about what comes next (C); finally "now do the note".
E4 a noisy log job done directly (A) vs in a subagent (B), followed by one small question.
E5 prompt cache after resuming: same settings / other effort / other model / after /compact / after 65 min.
Rewind is emulated the way it behaves: the session transcript is restored to a copy taken at the rewind
point and the working tree is reset to the commit made there. Usage: python3 measure.py E1,E2,E4,E5 [reps].
Runs go to ~/aiworkspace/claude/i1742-session/runs, one record per turn to results.jsonl here.
"""
import json
import pathlib
import re
import shutil
import subprocess
import sys
import time
import uuid
W = pathlib.Path(__file__).resolve().parent
BASE = W.parent / "skill-verify"
RUNS = pathlib.Path.home() / "aiworkspace" / "claude" / "i1742-session" / "runs"
SETTINGS = json.dumps({"claudeMdExcludes": [str(pathlib.Path.home() / ".claude" / "CLAUDE.md")], "autoMemoryEnabled": False})
ALLOWED = ["Bash(make *)", "Bash(python3 *)", "Bash(git diff*)", "Bash(git status*)", "Bash(ls *)", "Bash(cat *)",
"Bash(grep *)", "Bash(wc *)", "Bash(head *)", "Bash(tail *)", "Bash(sort *)", "Bash(awk *)", "Agent", "Task"]
READ = "先读一下 src/points/ledger.py、tests/test_ledger.py、rules.toml 和 tools/gen_rules.py,弄清楚每日上限是怎么实现的。先不要改代码,简单说说你的理解。"
WEEKLY = "给规则加一个每周上限 weekly_limit(0 = 不限),再加一个 share 事件:10 分、每天最多 3 次、每周最多 5 次。"
# v1 of E1 told it to compare only isocalendar().week; it refused in 4/4 runs (results-e1-v1.jsonl), so the
# wrong path is now a reasonable design that product then rejects: a rolling 7-day window.
NATURAL = "一周按台账时区的自然周算(周一 0 点开始),判断是不是同一周要按 (ISO 年, 周)。"
WRONG = WEEKLY + "每周上限按滚动 7 天算:看过去 7×24 小时里领了几次。加上测试,跑 make test。"
FIX = "不对,产品要的不是滚动 7 天,是自然周:" + NATURAL + "改过来,测试也跟着改,跑 make test。"
E1_RIGHT = WEEKLY + NATURAL + "加上测试,跑 make test。"
RIGHT = WEEKLY + "判断是不是同一周要按 (ISO 年, 周),不要只比周数 —— 只比周数的话 2026 年第 1 周和 2027 年第 1 周会被当成同一周。加上测试(包括一个跨年的),跑 make test。"
UNRELATED = "换个话题:解释一下 tools/gen_rules.py 是怎么把 rules.toml 变成 Python 的。只回答,不要改代码。"
TWO_THINGS = ("两件事。① " + RIGHT + " ② 另外先记一下:运营说 comment 每次的分数下周要从 2 改成 3,"
"等我说了再改,现在不要动。")
WALK = "把 tests/test_ledger.py 里每个测试在测什么逐个讲一遍,再说说每周上限还有哪些边界情况没测到。只回答,不要改代码。"
COMPACT_HINT = "/compact 接下来要做的是我一开始记下的第二件事,保留它的全部细节;每周上限的调试过程可以丢掉"
DO_NOTE = "好,现在做我一开始让你先记下的第二件事。"
LOGS = "看一下 logs/ 里的积分日志,找出被每日上限挡住(result=limited)次数最多的 3 个用户,给出各自的次数。"
LOGS_SUB = LOGS + "用一个子代理去读日志,只把结论带回来。"
SMALL = "顺便问一句:Ledger.award 返回 0 是什么意思?一句话回答。"
OK = "只回答 OK。"
def sh(cmd, cwd):
return subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True)
def session_file(d, sid):
return pathlib.Path.home() / ".claude" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", str(d)) / f"{sid}.jsonl"
def setup(d):
shutil.rmtree(d, ignore_errors=True)
shutil.copytree(BASE, d, ignore=shutil.ignore_patterns("skill", ".claude", "__pycache__", ".git", ".gitignore"))
if (d / "CLAUDE.md.example").exists(): # the repository copy; a project built from the article already has CLAUDE.md
shutil.move(d / "CLAUDE.md.example", d / "CLAUDE.md")
subprocess.run([sys.executable, str(W / "make_logs.py"), str(d / "logs")], check=True)
sh("git init -q && git add -A && git -c user.name=t -c user.email=t@t commit -qm base", d)
shutil.rmtree(session_file(d, "x").parent, ignore_errors=True)
def snapshot(d, sid, name):
"""Keep the transcript and the working tree as they are now, to rewind to later."""
shutil.copy(session_file(d, sid), d.parent / f"{d.name}.{name}.session.jsonl")
sh(f"git add -A && git -c user.name=t -c user.email=t@t commit -qm {name} --allow-empty && git tag {name}", d)
def rewind(d, sid, name):
shutil.copy(d.parent / f"{d.name}.{name}.session.jsonl", session_file(d, sid))
sh(f"git reset -q --hard {name} && git clean -qfd", d)
def turn(exp, variant, rep, step, d, sid, prompt, new=False, extra=()):
cmd = ["claude", "-p", prompt, "--setting-sources", "project", "--settings", SETTINGS,
"--permission-mode", "acceptEdits", "--allowedTools", *ALLOWED,
"--output-format", "stream-json", "--verbose", *extra]
cmd += ["--session-id", sid] if new else ["--resume", sid]
p = subprocess.run(cmd, cwd=d, capture_output=True, text=True, timeout=1800, stdin=subprocess.DEVNULL)
(d.parent / f"{d.name}.{variant}.{step}.stream.jsonl").write_text(p.stdout)
events = [json.loads(l) for l in p.stdout.splitlines() if l.strip().startswith("{")]
result = next((e for e in reversed(events) if e.get("type") == "result"), {})
main, sub, seen, tools = [], [], set(), []
for e in events:
if e.get("type") != "assistant" or not isinstance(e.get("message"), dict):
continue
m = e["message"]
for c in m.get("content", []):
if c.get("type") == "tool_use" and not e.get("parent_tool_use_id"):
tools.append(c["name"] + (":" + c["input"].get("command", "")[:80] if c["name"] == "Bash" else ""))
if m.get("id") in seen:
continue
seen.add(m.get("id"))
u = m.get("usage") or {}
row = (u.get("input_tokens", 0), u.get("cache_creation_input_tokens", 0), u.get("cache_read_input_tokens", 0), u.get("output_tokens", 0))
(sub if e.get("parent_tool_use_id") else main).append(row)
# total_cost_usd is cumulative over a resumed session; this turn alone (all models, subagents and
# the compaction call included) is in model_usage_since_last_result.
mu = result.get("model_usage_since_last_result") or {}
this = {k: sum(m.get(k, 0) for m in mu.values()) for k in ("costUSD", "inputTokens", "cacheReadInputTokens", "cacheCreationInputTokens", "outputTokens")}
compact = next((e for e in events if e.get("type") == "user" and "continued from a previous conversation" in str(e.get("message"))), None)
rec = {
"exp": exp, "variant": variant, "rep": rep, "step": step, "prompt": prompt, "extra": list(extra),
"cost_usd": round(this["costUSD"], 4), "turn_tokens": this, "models": sorted(mu), "num_turns": result.get("num_turns"),
"duration_s": round((result.get("duration_ms") or 0) / 1000), "is_error": result.get("is_error"),
"requests": len(main), "subagent_requests": len(sub),
"first_request": dict(zip(("input", "cache_write", "cache_read", "output"), main[0])) if main else None,
"last_context": sum(main[-1][:3]) if main else 0,
"cache_write": sum(r[1] for r in main), "cache_read": sum(r[2] for r in main), "output": sum(r[3] for r in main),
"sub_cache_write": sum(r[1] for r in sub), "sub_cache_read": sum(r[2] for r in sub),
"tools": tools, "compact_summary": compact["message"]["content"] if compact else None,
"final": (result.get("result") or "")[-1500:],
}
with open(W / "results.jsonl", "a") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(f"{exp}-{variant}-{rep} {step} cost={rec['cost_usd']} req={rec['requests']} ctx={rec['last_context']}", flush=True)
return rec
def check(exp, variant, rep, d, script):
p = subprocess.run([sys.executable, str(W / script)], cwd=d, capture_output=True, text=True,
env={"PYTHONPATH": "src", "POINTS_TZ": "Asia/Shanghai", "PATH": "/usr/bin:/bin"})
rec = {"exp": exp, "variant": variant, "rep": rep, "step": "check", "script": script, "ok": p.returncode == 0,
"report": (p.stdout + p.stderr).strip()[-600:], "tests_pass": sh("make test", d).returncode == 0,
"diff": sh("git diff $(git rev-list --max-parents=0 HEAD) --stat", d).stdout.strip()[-600:]}
with open(W / "results.jsonl", "a") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(f"{exp}-{variant}-{rep} check ok={rec['ok']} tests={rec['tests_pass']}", flush=True)
def e1(rep):
for v in "AB":
d, sid = RUNS / f"E1-{v}-{rep}", str(uuid.uuid4())
setup(d)
turn("E1", v, rep, "read", d, sid, READ, new=True)
snapshot(d, sid, "after-read")
turn("E1", v, rep, "wrong", d, sid, WRONG)
if v == "A":
turn("E1", v, rep, "correct", d, sid, FIX)
else:
rewind(d, sid, "after-read")
turn("E1", v, rep, "reprompt", d, sid, E1_RIGHT)
check("E1", v, rep, d, "check_weekly.py")
turn("E3", "continue-" + v, rep, "unrelated", d, sid, UNRELATED)
turn("E3", "clear-" + v, rep, "unrelated", d, str(uuid.uuid4()), UNRELATED, new=True)
def e2(rep):
for v in "ABC":
d, sid = RUNS / f"E2-{v}-{rep}", str(uuid.uuid4())
setup(d)
turn("E2", v, rep, "two-things", d, sid, TWO_THINGS, new=True)
turn("E2", v, rep, "walk", d, sid, WALK)
if v != "A":
turn("E2", v, rep, "compact", d, sid, "/compact" if v == "B" else COMPACT_HINT)
turn("E2", v, rep, "do-note", d, sid, DO_NOTE)
check("E2", v, rep, d, "check_note.py")
def e4(rep):
for v in "AB":
d, sid = RUNS / f"E4-{v}-{rep}", str(uuid.uuid4())
setup(d)
turn("E4", v, rep, "logs", d, sid, LOGS if v == "A" else LOGS_SUB, new=True)
turn("E4", v, rep, "small", d, sid, SMALL)
def e5(rep):
d, sid = RUNS / f"E5-{rep}", str(uuid.uuid4())
setup(d)
turn("E5", "base", rep, "read", d, sid, READ, new=True, extra=("--effort", "high"))
snapshot(d, sid, "after-read")
probes = [("same", ("--effort", "high")), ("effort-low", ("--effort", "low")),
("model-sonnet", ("--model", "sonnet", "--effort", "high"))]
for name, extra in probes:
rewind(d, sid, "after-read")
turn("E5", name, rep, "probe", d, sid, OK, extra=extra)
rewind(d, sid, "after-read")
turn("E5", "compact", rep, "compact", d, sid, "/compact", extra=("--effort", "high"))
turn("E5", "compact", rep, "probe", d, sid, OK, extra=("--effort", "high"))
rewind(d, sid, "after-read")
time.sleep(65 * 60)
turn("E5", "after-65min", rep, "probe", d, sid, OK, extra=("--effort", "high"))
turn("E5", "after-65min-again", rep, "probe", d, sid, OK, extra=("--effort", "high"))
if __name__ == "__main__":
exps = sys.argv[1].split(",") if len(sys.argv) > 1 else ["E1", "E2", "E4", "E5"]
reps = int(sys.argv[2]) if len(sys.argv) > 2 else 2
for rep in range(1, reps + 1):
for e in exps:
if e == "E5" and rep > 1:
continue
try:
{"E1": e1, "E2": e2, "E4": e4, "E5": e5}[e](rep)
except Exception as exc: # noqa: BLE001
print(f"{e}-{rep} FAILED {exc!r}", flush=True)
print("ALL-DONE", flush=True)
| 项目 | 内容 |
|---|---|
| 系统 | macOS 27.0.1(arm64) |
| 工具版本 | Claude Code 2.1.332(模型 claude-opus-5-5,默认思考力度;E5 的基线会话用 --effort high);Python 3.15.2 |
| 隔离方式 | --setting-sources project,claudeMdExcludes 排除用户级 CLAUDE.md,关闭自动记忆,不加载个人插件和 hooks;每组从同一份干净副本开始,项目放在仓库外 |
| 放行范围 | 自动接受文件修改;预先放行 make、python3、git diff/status、ls、cat、grep、wc、head、tail、sort、awk 和子代理 |
| 规模 | E1 走错路 2 种 × 2 遍(另有第一版 4 次,未计入对照);E2 压缩 3 种 × 2 遍;E3 继续 / 清空 2 种 × 4 次;E4 子代理 2 种 × 2 遍;E5 缓存探测 1 组 |
| 判定方法 | 代码对不对由独立的检查脚本判定(check_weekly.py 8 项、check_note.py 3 项),再跑 make test;花费和 token 取每一轮结果里的 model_usage_since_last_result;压缩摘要、工具调用、最终回复都从完整运行记录里读 |
| 结果 | E1 4/4 通过;E2 6/6 改对,4/4 份摘要保留了第二件事;E4 4/4 答对;回退用会话快照 + git 标签模拟 |
| 实测日期 | 2026-11-25 |
| 撰写 / 实跑 | Claude(Claude Code) |
| 复核 | Codex(#1742) |
本文的方法取自以下文章,示例与实测为本站所做: