0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Claude CodeのCode Modeを18回比べた:API往復は減らず、入力トークンは約4割減

0
Posted at

thumbnail

Claude Code の新しい Code Mode は、ツール呼び出しをコードにまとめて実行する機能です。それなら API の往復は半分くらいに減りそうだな、と思いませんか?
同じ3つの課題を Code Mode のオフとオンで3回ずつ、計18セッション走らせて比べました(Claude Code 2.1.330・Sonnet 5.5・サブスク内で0円)。
結論、API の往復(モデルへのリクエスト数)は1回も減らず、入力トークンの合計は約4割減りました(0.62〜0.64倍。短い作業での値で、API 料金換算の参考値は 0.91〜0.93倍どまりです)。1コマンドで回せる計測スクリプトは末尾に全文あります!

Code Mode オン/オフの比較。往復回数は全課題で同じ、入力トークンは0.62〜0.64倍

見るのは2列です。api_calls_main が往復の回数(モデルへのリクエスト数)で、オフもオンも同じ。tokens_total_in が入力トークンの合計で、オンはオフの 0.62〜0.64倍。どれも3回の中央値です。
なお、この記事の黒い画像3枚は、計測ログから必要な行と列を抜き出して画像にしたものです(ターミナルのスクショそのものではありません。数字はログのままです)。

こんにちは、八兵衛です。
「まとめて実行するなら往復は半分になるはず!」という僕の予想は、きれいに外れました。
でも外れ方がちょっと面白かったので、そのまま書きます!

先に結論と持ち帰り

  • API の往復(Claude Code がモデルにリクエストを送った回数)は、3課題ともオフとオンで同じでした。オフでも Claude が自分で Python スクリプトや sed の一括置換を書いて、1〜2回のツール呼び出しで片付けていたからです。
  • 入力トークンの合計は、オンでオフの 0.62〜0.64倍。まとめようがない「package.json のバージョンを答えるだけ」の質問でも、同じくらい減りました。
  • 中身は、課題に関係なく「1リクエストあたり約1万3千トークン少ない」でほぼ一定でした。オンだと、モデルに毎回渡すツール定義(使えるツールの説明書き)が15個 → 2個、文字数で半分以下になっていて、これが主な理由の可能性が高いです。
  • なので「約4割」は、1リクエストがオフで約3万5千トークンしかない短い作業だから出た割合です。長い会話では、割合はもっと小さくなるはずです(測っていません)。
  • 料金は4割も下がりません。API 料金換算の参考値では、オンはオフの 0.91〜0.93倍でした。
  • 18回すべて正解で、正解率に差はなし。時間は30ファイルの一括修正だけ、オンのほうが長くなりました(オフ 3.4秒 → オン 6.4秒)。
  • claude -p(対話画面を出さない起動方法。CI やバッチで使うもの)では Code Mode になりませんでした。ただしこれは下調べ中に v2.1.325 で1回試しただけで、ログは残していません。ドキュメントの要件も「ターミナルの対話セッション」です。

じゃあ、どう使い分けるか。測った範囲で言えるのはこれくらいです。

  • 対話で長く使うセッションなら、オンにする価値はありそうです。リクエストのたびに約1万3千トークン軽くなります(今回の環境での値です。長い会話そのものや、使用量の上限・コンテキストの上限にどれだけ効くかは測っていません)。
  • 「往復が減って速くなる」は、今回の課題では起きませんでした。速さ目当てなら、まず自分の作業で測るのがよさそうです。
  • CI・claude -p 運用は、今のところ対象外と考えておきます。

Claude Code の Code Mode ってなに?

ドキュメント(https://code.claude.com/docs/en/code-mode 、2026-11-23 確認)によると、Code Mode では Claude が Bash・Read・Edit を1回ずつ呼ぶ代わりに、JavaScript を書いて、その中で複数のツール呼び出しをまとめて実行します。
v2.1.323 で入った実験的機能で、11/18 に公式 X で告知されました。

オンにするには、環境変数をつけて起動します。ドキュメントによると、初回だけ確認を求められます。

CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude

オンになると、起動画面の上のほうにこの1行が出ます。

Code Mode (experimental) is on · this session can be resumed only with Code Mode on

ドキュメントが「関連するツール呼び出しが多い作業で試してみて」と例に挙げているのは、次の3つです。

  • 多数のファイルにまたがる同じ変更
  • 結果を絞ってから読みたい検索
  • 同時に走らせられる独立したコマンド

なので課題も、ドキュメントに出てくる例を下敷きにしました(retryPolicy の maxAttempts を3→5にする、存在しないローカルファイルへのリンクを探す)。
ドキュメントの例は1ファイルの修正ですが、「多数のファイル」に当たるように30ファイルに増やしています。
「公式が例に挙げている作業で、本当に往復が減るのか?」を見たかったんです。

ちなみに「往復が半分になる」は僕の予想です。ドキュメントには、往復やトークンがどれだけ減るかという数字は書かれていません。

やったこと: 3つの課題をオフ/オンで3回ずつ

課題は3つ。スクリプトが固定シードで毎回同じものを作ります。カッコの中は、ログや画像に出てくる呼び名です。

課題 中身 正解の判定
リンク切れ探し(links) docs/ 下の Markdown 40ファイルから、存在しないローカルファイルへのリンクを探して JSON に書く 37件と完全一致、docs は書き換えない
30ファイルの一括修正(retry) src/ 下の36モジュールのうち retryPolicy を持つ30個だけ maxAttempts を3→5。おとりの6個は3のまま。最後に node test.js 全ファイル一致&テスト成功
1問だけの質問(single・対照) package.json の version を答える 4.17.3

1セッションずつ tmux の中で対話モードの Claude Code を起動して、プロンプトを1回送り、ターンが終わったらセッションログ(~/.claude/projects/ の jsonl)から数字を抜いて、正誤も自動で判定しています。
claude -p を使わずにわざわざ tmux で画面を操作しているのは、後で書く「つまずき」のせいです。

条件

  • 日付: 2026-11-23(JST)、08:28:59 開始、約5分で18セッション
  • Claude Code 2.1.330(計測中は自動更新を止めた)、モデル Sonnet 5.5(claude-sonnet-5-5、effort medium)
  • 3課題 × オフ/オン × 3回 = 18セッション。18回すべてで Code Mode の状態が狙いどおり(オンの9回は起動時の画面に「Code Mode (experimental) is on」)
  • オフ/オンの順番は課題ごとに固定でした(リンク切れ探しと1問だけの質問はオフ→オン、一括修正はオン→オフ)。回ごとに入れ替えるつもりでしたが、スクリプトの式の都合で、同じ課題は3回とも同じ順番になっていました
  • 権限モードは bypassPermissions(確認を全部スキップする設定)。/tmp の使い捨てフォルダで作業。1ターンだけの会話
  • 費用: Max サブスク内で0円。文中の API 料金換算は Claude Code がログに残す参考値で、請求ではありません

限界

  • 課題が簡単で、オフでも1〜2回のツール呼び出しで済んだ。調べながら何度も読み直すような作業では結果が変わる可能性があります
  • 各区分 n=3。傾向として読んでください(有意差は主張しません)
  • 「約4割」は短い1ターンの作業での割合です。差は1リクエストあたり約1万3千トークンでほぼ一定だったので、長い会話では割合は小さくなるはずです(測っていません)
  • オフ側のツール定義は、契約・ログイン方法・設定で変わります。今回はオフの15個のうち、Artifact というツール1個の定義が全体の約45%を占めていました。これが入らない環境では、差はもっと小さくなるはずです(結果2に書きます)
  • 18回とも、最初のリクエストの時点で先頭部分がキャッシュ読み込みになっていました。キャッシュが効いていない状態からの比較はしていません
  • 往復の回数と入力トークンは、メインの会話のリクエストだけを数えています。Claude Code は裏でもモデルを呼んでいて(オフ/オン共通)、料金換算の参考値にはその分も入っています
  • Code Mode は実験的機能で、ドキュメントにも「It may change or be removed in any release」とあります。2.1.330 時点の結果です
  • Sonnet 5.5・bypassPermissions だけ。他のモデル、auto モード、確認ありのモードは試していません
  • claude -p と「Claude Code の中から起動」の話は、下調べ中に1回ずつ見ただけで、ログは残していません(claude -p は v2.1.325)。本番の 2.1.330 では claude -p を試していません

結果1: API の往復(リクエスト数)は1回も減らなかった

往復の回数は、リンク切れ探し2回・一括修正3回・1問だけの質問2回で、オフもオンも全く同じでした。18回とも、ばらつきすらゼロ!

数え方を補足すると、ツールを1回呼んで答えるだけでも、「ツールを呼ぶ」「結果を受け取って答える」でリクエストは2回になります。

中身を見ると理由はシンプルで、オフでも Claude はすでに「まとめて」やっていました。
リンク切れ探しの1回目のログを並べるとこうです(1回目の値なので、冒頭の中央値とは少し違います)。

links 課題の1回目。オフは Bash 1回、オンは REPL 1回の中で190回のツール呼び出し

配列は左から、モデルが直接呼んだツール/その中で呼ばれたツール/往復の回数/入力トークンの合計です。
ツールの回数は、3回とも同じでした。

  • リンク切れ探し・オフ: Bash を1回だけ呼んで、その中で Python スクリプトを書いて docs/ 全体を一気に調べていた
  • リンク切れ探し・オン: REPL(Code Mode のコード実行ツール)を1回呼んで、その JavaScript の中で190回のツール呼び出し(Bash 149・Read 40・Write 1)
  • 一括修正・オフ: Bash 2回(grep で確認 → sed で一括置換して、テスト実行)
  • 一括修正・オン: REPL 2回。中で Bash 3回・Edit 30回

つまり、オフの Claude は「シェルや Python」でまとめていて、オンの Claude は「JavaScript」でまとめていた、という違いでした。
モデルから見た往復はどちらも同じ。そりゃ減らないわけです笑

ちなみに画面の見え方は課題で違いました。一括修正のオンでは Edit の差分がファイルごとに並び、リンク切れ探しのオンでは「read 40 files, ran 148 shell commands」と1行にまとまっていました(保存した最終画面で確認)。

結果2: 入力トークンは約4割減った(1問答えるだけの課題でも)

ここが今回いちばん「え?」となったところです。
入力トークンの合計(各リクエストでモデルに送った量を足したもの。キャッシュ作成・キャッシュ読み込みとして数えられた分も含みます)は、オンでオフの 0.63倍(リンク切れ探し)・0.64倍(一括修正)・0.62倍(1問だけの質問)。

1問だけの質問は package.json を1回読むだけです。まとめる余地なんてありません。
それでも同じくらい減っている!

じゃあ何が減ったのか? セッションログに残っている「モデルに送ったリクエストの形」を集計しました(集計スクリプト analysis.py も末尾に置いています)。

モデルに渡しているツール定義と、1リクエストごとの入力トークン

画像は上から、モデルに渡したツール定義、一括修正の1リクエストごとの入力トークン、最初のリクエストだけを比べた表です。見てほしいのは一番下の diff の列です。
下の箇条書きには、画像に入れていない集計(同じ analysis.py の出力)も含みます。

  • まだ何も読んでいない最初のリクエストの時点で、入力トークンが約1万3千少ない(3課題の差は 13246・13241・13249)
  • 2回目以降のリクエストでも、差は 12799〜13037。少しずつ縮みますが、約1万3千のままです
  • 最初のリクエストのうちキャッシュから読まれた量は、オフが9回とも 26552、オンが9回とも 13455。課題が違っても同じ値でした
  • ツール定義(使えるツールの説明書きで、リクエストのたびに一緒に送られます)は、オフが15個(Bash・Read・Edit・Agent・Skill など)で JSON にして 75819 文字、オンは Poll(コードの終了などの知らせを受け取るツール)と REPL の2個で 34338 文字
  • システムプロンプトはほぼ同じ(オフ 9052 文字、オン 9099 文字)

課題の中身に関係なく、毎回同じだけ軽い。なので「Code Mode がまとめてくれたから減った」のではなく、ツール定義が小さくなった分だけ、毎回の荷物が軽くなった可能性が高いと見ています。
ツール定義だけで何トークンなのかはログに出ていないので、言えるのはここまでです。

「15個が2個になったのに、文字数は半分弱も残るの?」と思った方へ。
オンの 34338 文字は、ほとんどが REPL 1個の定義(33013 文字)です。中で使えるツールの呼び方が、REPL の説明文に短い形でまとめて書いてあります。ツールが無くなったのではなく、1個ずつの長い説明が REPL 1個の説明に置き換わった、が近いです。

数字のつながりも書いておきます。
リンク切れ探しはリクエストが2回なので、約1万3千 × 2回。合計の差(70283 → 44086 で 26197)と合います。
そして「約4割」という割合は、1リクエストがオフで約3万5千トークンの短い作業だから大きく出た数字です。会話が長くなって1リクエストが大きくなれば、同じ1万3千の差でも割合は小さくなるはずです(長い会話は測っていません)。

注意が2つあります。

1つ目は環境の差です。
オフ側の15個のうち、Artifact というツール1個の定義だけで 33909 文字(オフ全体の約45%)ありました。公式のツール一覧(https://code.claude.com/docs/en/tools-reference 、2026-11-23 確認)によると、Artifact は Pro や Max などのプランでログインしているときに使えるツールです。API キーで使っている環境のようにこれが入らない場合、差はもっと小さくなるはずです(試していません)。

2つ目は料金です。
減ったのはほぼキャッシュ読み込み(すでにキャッシュにある部分を使い回した、と数えられる分)でした。リンク切れ探しの中央値で 61219 → 34876 です。キャッシュ作成のほうはほとんど変わっていません(9062 → 9202)。
Claude Code が記録している API 料金換算(参考値)では、オンはオフの 0.91〜0.93倍にしかなっていません。キャッシュ読み込みは単価が安いためだと見ていますが、料金表との突き合わせはしていません。
「トークン4割減=料金4割減」ではないので、そこは混ぜないほうがいいです。

結果3: 30ファイルの一括修正は、オンのほうが時間がかかった

1ターンの所要時間は、リンク切れ探しと1問だけの質問ではほぼ同じでした(オフ 5.9秒・オン 6.0秒、オフ 1.4秒・オン 1.4秒)。
一括修正だけ、オフ 3.4秒・オン 6.4秒(1.88倍)です。

ログの時刻を見ると、モデルの最後のツール呼び出しから最終回答までの間隔が、オフ 0.5〜0.7秒に対してオン 3.6〜4.3秒。
オンではこの間に、2回目のコード(Edit を30回+テストを1回)が走っています。ログに残っていたこのコードの実行時間は 3.0〜3.7秒で、間隔のほとんどを占めていました。
オンのコードは3回とも、30ファイルを1つずつ順番に Edit する書き方です。オフは同じ作業を sed の一括置換1回で済ませていました。

なので差は、モデルの側ではなくコードを実行する側にありそうです。
ただ、数秒の話ですし n=3、しかもこの課題は3回ともオンを先に実行しているので、参考程度に。

もう1つ、書いておくことがあります。
オンのときモデルに渡される REPL の説明文に、この課題とそっくりの例(retryPolicy を探して maxAttempts を3→5に Edit する)が入っていました。オン側はお手本つきで解いたことになるので、ほかの置換作業でも同じ書き方・同じ時間になるとは限りません。

つまずいたこと

1. claude -p では Code Mode にならなかった

最初は CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude -p で一気に回すつもりでした(-p は、対話画面を出さずに1回だけ実行する起動方法です)。
ところが、起動時のツール一覧に REPL が無く、Claude は普通の Bash を呼びました。
これは記事の下調べ中に v2.1.325 で1回試しただけで、そのときのログは残していません。本番の 2.1.330 では claude -p を試していません。
次の「つまずき2」のように親の Claude Code の環境変数を引き継いだ状態だったかどうかも、記録がありません。なので、原因が -p そのものだとは、僕の確認だけでは言い切れません。

ドキュメントは claude -p を名指ししてはいませんが、要件に「an interactive claude session in a terminal」とあるので、それと合う結果です。
CI やバッチで claude -p を使っている人は、今のところ Code Mode の対象外と考えておくのがよさそうです。だから今回は tmux で対話画面を操作して計測しました。

2. Claude Code の中から起動すると有効にならなかった(env -i で回避)

計測スクリプトを Claude Code 経由で動かしたら、tmux の中なのに「isn't available: for now it only works in the interactive terminal」と出てオンになりませんでした(これも下調べ中に1回見ただけで、画面は保存していません)。
env -i で親の環境変数をまるごと切って起動したら、有効になりました。親の Claude Code から引き継いだ環境変数(CLAUDECODE=1 など)のどれかが効いていたようですが、どの変数かまでは切り分けていません。
本番の18回は全部 env -i 経由で、オンの9回すべてで、起動時に「Code Mode (experimental) is on」の表示を確認しています。

3. 下調べ中に Claude Code が自動更新されていた(2.1.325 → 2.1.330)

題材を決める下調べ中に対話セッションを起動したら、2.1.325 → 2.1.330 に自動更新されていました。
計測では DISABLE_AUTOUPDATER=1 で途中の更新を止めて、開始時に claude --version を記録しています。記事のバージョンもその値(2.1.330)です。
実験的機能は版ごとに修正が入っているので、自分で測るときもバージョンは必ず残すのがおすすめです。

オンにする前に知っておくこと(ドキュメント https://code.claude.com/docs/en/code-mode から。ここは試していません)

  • 権限のルールとフック: deny/ask ルールや PreToolUse フックは、コードの中のツール呼び出し1回1回にも、いつものツール名で効く。
  • 確認ありのモード: そのモードで確認が出るツール呼び出しごとに、確認が出る。今回は確認を全部スキップする設定だったので、190回の呼び出しで実際にどう見えるかは分かりません。
  • auto モード: 分類器はツール呼び出しごとではなく、コード単位で見る。実行時に決まる値(検索結果から取ったパスなど)は見えないので、止めたい操作は deny/ask ルールやフックで押さえておく必要がある。
  • 再開: オンで始めたセッションは、オンのままでないと再開できない(起動画面の1行にも「this session can be resumed only with Code Mode on」と出ます)。
  • 使えなくなるもの: Remote Control・Claude in Chrome・computer use は、Code Mode では使えない。
  • オフに戻す: 環境変数を消すか、値を 0 にして新しいセッションを始める。

まとめ

Code Mode をオンにすると、API の往復は半分くらいに減るのか。今回の3課題での答えは「1回も減らない」でした。
代わりに、毎回の荷物(入力トークン)が約1万3千トークン軽くなっていました。短い作業だったので割合にすると約4割、料金換算の参考値では 0.91〜0.93倍です。

まとめるのが上手いのは Code Mode だけじゃなくて、オフの Claude も十分上手かったです。
往復が本当に多い作業(何度も調べ直すような作業)や長い会話で差が出るかは、次に測ってみたいところです。

計測スクリプトは末尾に全文置きました。課題を差し替えれば自分の作業でも測れるはずです(差し替えての実行は、僕もまだ試していません)。
「うちの作業だと往復も減ったよ!」という結果があれば、ぜひ教えてください!

最後まで読んでいただきありがとうございました!

付録: 計測スクリプト全文

./verify/run_all.sh の1コマンドで、課題の生成 → 18セッション → 集計(summary.md / summary.csv)まで回ります。
動かすのに要るのは、tmux・python3・node・Claude Code と、~/.config/claude/oauth_token に置いたサブスクのトークンです。verify/ に5ファイル、その1つ上に analysis.py を置きます。
OAuth トークンはファイルから読むだけで、記事にもスクリプトにも値は入っていません。ANTHROPIC_API_KEY は使いません。

課題を差し替えるときに触るのは、make_fixture.py(課題のファイルを作る)と、run_session.py の PROMPTS(指示文)・check(正誤判定)です。
このスクリプトは Claude Code を bypassPermissions(確認を全部スキップする設定)で起動します。 作業は /tmp にコピーしたフォルダの中で行う作りですが、自分の作業に差し替えるときは、壊れても困らないコピーで試してください。

verify/ の5本は、実行したときのまま載せています。run_all.sh のコメントには「回ごとに順番を入れ替える」とありますが、課題が3つだと同じ課題は毎回同じ順番になります(今回もそうでした)。回ごとに入れ替えたい場合は、順番を決める式を直してください。

verify/run_all.sh(1コマンドで全部回す)
verify/run_all.sh
#!/usr/bin/env bash
# Code Mode (CLAUDE_CODE_EXPERIMENTAL_CODE_MODE) on/off comparison, one command.
#   ./verify/run_all.sh            # full run: 3 tasks x 2 modes x REPS (default 3) = 18 sessions
#   REPS=1 TASKS=single ./verify/run_all.sh   # small smoke test (2 sessions)
# Subscription only (Max OAuth token). ANTHROPIC_API_KEY is never used.
# Logs: ./logs/<timestamp>/
set -euo pipefail
cd "$(dirname "$0")/.."
ROOT="$(pwd)"
REPS="${REPS:-3}"
TASKS="${TASKS:-links retry single}"
MODEL="${MODEL:-sonnet}"
MAX_SESSIONS="${MAX_SESSIONS:-40}"
TS="$(date +%Y%m%d-%H%M%S)"
LOG="$ROOT/logs/$TS"
FIX="/tmp/cm-verify-fixture"
mkdir -p "$LOG"
exec > >(tee -a "$LOG/run_all.log") 2>&1

echo "== preflight $(date '+%Y-%m-%d %H:%M:%S %Z')"
unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN
command -v tmux >/dev/null || { echo "tmux missing"; exit 1; }
[ -s "$HOME/.config/claude/oauth_token" ] || { echo "no OAuth token file"; exit 1; }
{
  echo "date: $(date -Iseconds)"
  echo "claude_version: $(claude --version 2>/dev/null)"
  echo "node: $(node -v)"
  echo "model_arg: $MODEL"
  echo "reps: $REPS tasks: $TASKS"
  echo "uname: $(uname -sr)"
} | tee "$LOG/env.txt"

n_tasks=$(wc -w <<<"$TASKS")
total=$(( n_tasks * 2 * REPS ))
if [ "$total" -gt "$MAX_SESSIONS" ]; then echo "too many sessions: $total > $MAX_SESSIONS"; exit 1; fi
echo "sessions planned: $total"

python3 "$ROOT/verify/make_fixture.py" "$FIX" | tee "$LOG/fixture.json"
cp -r "$FIX" "$LOG/fixture"   # keep the exact inputs next to the results

# interleave: off,on then on,off on the next rep (reduces time-of-day / cache-order bias)
i=0
for rep in $(seq 1 "$REPS"); do
  for task in $TASKS; do
    if [ $(( (rep + i) % 2 )) -eq 1 ]; then order="off on"; else order="on off"; fi
    i=$((i + 1))
    for mode in $order; do
      echo "== $(date '+%H:%M:%S') task=$task mode=$mode rep=$rep"
      if ! python3 "$ROOT/verify/run_session.py" "$mode" "$task" "$rep" "$FIX" "$LOG" "$MODEL"; then
        echo "session script failed (see $LOG/${task}_${mode}_r${rep}/)"
      fi
      if grep -qs '"error": "usage limit reached"' "$LOG/${task}_${mode}_r${rep}/metrics.json"; then
        echo "usage limit reached: stopping (no API fallback by design)"; break 3
      fi
    done
  done
done

echo "== analyze"
python3 "$ROOT/verify/analyze.py" "$LOG"
echo "done: $LOG"
verify/launch_claude.sh(tmux の中で Claude Code を起動。オン/オフ切り替え)
verify/launch_claude.sh
#!/usr/bin/env bash
# Started inside tmux under `env -i` (no parent Claude Code variables).
# Usage: launch_claude.sh <on|off> <model>
# Subscription only: reads the OAuth token from file, never uses ANTHROPIC_API_KEY.
set -u
MODE="$1"; MODEL="${2:-sonnet}"
unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_BASE_URL
export CLAUDE_CODE_OAUTH_TOKEN="$(cat "$HOME/.config/claude/oauth_token")"
export DISABLE_AUTOUPDATER=1
if [ "$MODE" = "on" ]; then
  export CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1
else
  export CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=0
fi
exec claude --model "$MODEL" --permission-mode bypassPermissions
verify/run_session.py(1セッションを動かして数字を取る・正誤判定)
verify/run_session.py
#!/usr/bin/env python3
"""Run ONE interactive Claude Code session in tmux, send one prompt, wait for the
turn to finish, then collect metrics from the session transcript and check the
result.

Code Mode only works in an interactive terminal session (claude -p does not get
the REPL tool; checked 2026-11-23), so this drives the TUI with tmux.

Usage: run_session.py <mode on|off> <task links|retry|single> <rep> <fixture_dir> <log_dir> [model]
Writes <log_dir>/<task>_<mode>_r<rep>/{metrics.json,pane.txt,transcript.jsonl,work.tar.gz}
"""
import glob
import json
import os
import re
import shutil
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
SOCK = "cmverify"
TIMEOUT_SEC = 600  # 1 run <= 10 min

PROMPTS = {
    "links": (
        "Read every Markdown file under docs/ and find the local links (including images) that point to files "
        "that don't exist. Ignore http/https/mailto URLs and links that are only an #anchor; for other links, "
        "drop any #fragment before checking. Resolve each link relative to the Markdown file's folder. "
        "Write the result to broken_links.json as a JSON array of objects {\"file\": <path from the project root, "
        "e.g. docs/api/page03.md>, \"link\": <link text exactly as written>}, sorted by file then link. "
        "Do not change any other file. When done, reply with the number of broken links only."
    ),
    "retry": (
        "In every file under src/ that defines retryPolicy, change maxAttempts from 3 to 5. "
        "Do not change anything else (other functions keep their values). Then run `node test.js` and "
        "reply with its last line only."
    ),
    "single": "What is the version in package.json? Reply with the version string only.",
}


def tmux(*args, check=True):
    return subprocess.run(["tmux", "-L", SOCK, *args], capture_output=True, text=True, check=check)


def pane():
    r = tmux("capture-pane", "-p", "-t", "s", "-S", "-200", check=False)
    return r.stdout


def keys(*k):
    tmux("send-keys", "-t", "s", *k, check=False)


def slug(path):
    return re.sub(r"[^A-Za-z0-9]", "-", path)


def handle_dialogs(deadline):
    """Answer the start-up dialogs; return when the prompt box is ready."""
    handled = []
    while time.time() < deadline:
        p = pane()
        if "hit your" in p.lower() and "limit" in p.lower():
            raise RuntimeError("usage limit reached")
        if "Choose the text style" in p:
            keys("Enter"); handled.append("theme")
        elif "Press Enter to continue" in p:
            keys("Enter"); handled.append("security-notes")
        elif "Yes, I trust this folder" in p:
            keys("Down"); time.sleep(0.3); keys("Enter"); handled.append("trust")
        elif "Yes, I accept" in p:
            keys("Down"); time.sleep(0.3); keys("Enter"); handled.append("bypass")
        elif "Yes, turn on Code Mode" in p:
            keys("Down"); time.sleep(0.3); keys("Enter"); handled.append("codemode-confirm")
        elif "bypass permissions on" in p and "❯" in p:
            return handled, p
        time.sleep(2)
    raise RuntimeError("session did not become ready")


def parse_transcript(path):
    msgs = {}   # message id -> (entry, sidechain)
    order = []
    inner_tools = []
    model_tools = []
    turn_ms = []
    repl_mode = None
    cost = None
    texts = []
    for line in open(path, encoding="utf-8"):
        try:
            d = json.loads(line)
        except json.JSONDecodeError:
            continue
        t = d.get("type")
        if t == "repl-mode":
            repl_mode = d.get("replMode")
        elif t == "cost-state":
            cost = d.get("totalCostUSD")
        elif t == "system" and d.get("subtype") == "turn_duration":
            turn_ms.append(d.get("durationMs"))
        elif t == "assistant":
            m = d["message"]
            side = bool(d.get("isSidechain"))
            synthetic = m.get("model") == "<synthetic>"
            for c in m.get("content", []):
                if c.get("type") == "tool_use":
                    (inner_tools if synthetic else model_tools).append({"name": c["name"], "side": side})
                if c.get("type") == "text" and not side and not synthetic:
                    texts.append(c["text"])
            if not synthetic:
                mid = m.get("id")
                if mid not in msgs:
                    order.append(mid)
                msgs[mid] = (m, side)
    usage = {"input": 0, "cache_creation": 0, "cache_read": 0, "output": 0}
    calls_main = calls_side = 0
    last_ctx = 0
    for mid in order:
        m, side = msgs[mid]
        u = m.get("usage", {})
        usage["input"] += u.get("input_tokens", 0) or 0
        usage["cache_creation"] += u.get("cache_creation_input_tokens", 0) or 0
        usage["cache_read"] += u.get("cache_read_input_tokens", 0) or 0
        usage["output"] += u.get("output_tokens", 0) or 0
        if side:
            calls_side += 1
        else:
            calls_main += 1
            last_ctx = (u.get("input_tokens", 0) or 0) + (u.get("cache_creation_input_tokens", 0) or 0) + (u.get("cache_read_input_tokens", 0) or 0)
    def count(lst):
        out = {}
        for x in lst:
            out[x["name"]] = out.get(x["name"], 0) + 1
        return out
    return {
        "repl_mode": repl_mode,
        "api_calls_main": calls_main,
        "api_calls_subagent": calls_side,
        "tokens": usage,
        "tokens_total_in": usage["input"] + usage["cache_creation"] + usage["cache_read"],
        "last_request_context": last_ctx,
        "model_tool_calls": len(model_tools),
        "model_tools": count(model_tools),
        "inner_tool_calls": len(inner_tools),
        "inner_tools": count(inner_tools),
        "turn_duration_ms": sum(x for x in turn_ms if x),
        "api_equiv_cost_usd_reference_only": cost,
        "final_text": texts[-1] if texts else "",
        "models": sorted({msgs[i][0].get("model") for i in order}),
    }


def check(task, fixture, work, final_text):
    truth = json.load(open(os.path.join(fixture, task, "truth.json")))
    if task == "links":
        p = os.path.join(work, "broken_links.json")
        try:
            got = json.load(open(p))
            got_set = {(x["file"], x["link"]) for x in got}
        except Exception as e:  # noqa: BLE001
            return {"pass": False, "reason": f"broken_links.json unreadable: {e}"}
        want = {(x["file"], x["link"]) for x in truth["broken"]}
        tp = len(got_set & want)
        # docs must be untouched
        orig_dir = os.path.join(fixture, task, "work")
        changed = []
        for root, _, fs in os.walk(orig_dir):
            for f in fs:
                rel = os.path.relpath(os.path.join(root, f), orig_dir)
                if open(os.path.join(root, f), "rb").read() != open(os.path.join(work, rel), "rb").read():
                    changed.append(rel)
        return {"pass": got_set == want and not changed, "found": len(got_set), "want": len(want),
                "true_pos": tp, "false_pos": len(got_set - want), "missed": len(want - got_set),
                "docs_changed": changed}
    if task == "retry":
        exp = truth["expected"]
        wrong = []
        for rel, text in exp.items():
            fp = os.path.join(work, rel)
            if not os.path.exists(fp) or open(fp, encoding="utf-8").read() != text:
                wrong.append(rel)
        r = subprocess.run(["node", "test.js"], cwd=work, capture_output=True, text=True)
        decoys_changed = [d for d in truth["decoys"] if d in wrong]
        return {"pass": not wrong and r.returncode == 0, "files_wrong": wrong, "decoys_changed": decoys_changed,
                "test_rc": r.returncode, "test_last": r.stdout.strip().splitlines()[-1:] }
    if task == "single":
        return {"pass": truth["answer"] in final_text, "answer": final_text.strip()[:80]}
    raise ValueError(task)


def main():
    mode, task, rep, fixture, log_dir = sys.argv[1:6]
    model = sys.argv[6] if len(sys.argv) > 6 else "sonnet"
    run_id = f"{task}_{mode}_r{rep}"
    out = os.path.join(log_dir, run_id)
    os.makedirs(out, exist_ok=True)
    # fresh folder per run (no shared auto-memory or history between runs)
    work = f"/tmp/cm-verify/{os.path.basename(os.path.abspath(log_dir))}/{run_id}/work"
    shutil.rmtree(os.path.dirname(work), ignore_errors=True)
    shutil.copytree(os.path.join(fixture, task, "work"), work)
    proj_dir = os.path.expanduser(f"~/.claude/projects/{slug(work)}")
    before = set(glob.glob(os.path.join(proj_dir, "*.jsonl")))

    tmux("kill-server", check=False)
    env_cmd = (f"env -i HOME={os.environ['HOME']} PATH={os.environ['PATH']} TERM=xterm-256color LANG=C.UTF-8 "
               f"bash {HERE}/launch_claude.sh {mode} {model}; sleep 5")
    tmux("new-session", "-d", "-s", "s", "-x", "200", "-y", "50", "-c", work, env_cmd)
    result = {"run_id": run_id, "mode": mode, "task": task, "rep": int(rep), "model_arg": model,
              "started_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "work": work}
    try:
        handled, p0 = handle_dialogs(time.time() + 120)
        result["dialogs"] = handled
        result["code_mode_banner"] = ("Code Mode (experimental) is on" in p0)
        m = re.search(r"Claude Code v([0-9.]+)", p0)
        result["cc_version_banner"] = m.group(1) if m else None
        time.sleep(1)
        tmux("send-keys", "-t", "s", "-l", PROMPTS[task])
        time.sleep(0.5)
        keys("Enter")
        t0 = time.time()
        transcript = None
        done = False
        while time.time() - t0 < TIMEOUT_SEC:
            time.sleep(3)
            p = pane()
            if "hit your" in p.lower() and "limit" in p.lower():
                raise RuntimeError("usage limit reached")
            new = sorted(set(glob.glob(os.path.join(proj_dir, "*.jsonl"))) - before, key=os.path.getmtime)
            if new:
                transcript = new[-1]
                txt = open(transcript, encoding="utf-8").read()
                if '"subtype":"turn_duration"' in txt.replace(" ", ""):
                    done = True
                    break
        result["wall_sec"] = round(time.time() - t0, 1)
        result["timed_out"] = not done
        time.sleep(2)
        open(os.path.join(out, "pane.txt"), "w").write(pane())
        keys("C-c"); time.sleep(0.5); keys("C-c"); time.sleep(2)
        if transcript:
            shutil.copy(transcript, os.path.join(out, "transcript.jsonl"))
            result.update(parse_transcript(transcript))
        result["check"] = check(task, fixture, work, result.get("final_text", ""))
        result["mode_ok"] = (result.get("repl_mode") is True) == (mode == "on")
    except Exception as e:  # noqa: BLE001
        result["error"] = str(e)
        open(os.path.join(out, "pane.txt"), "w").write(pane())
    finally:
        tmux("kill-server", check=False)
        subprocess.run(["tar", "czf", os.path.join(out, "work.tar.gz"), "-C", os.path.dirname(work), "work"], check=False)
    json.dump(result, open(os.path.join(out, "metrics.json"), "w"), indent=1, ensure_ascii=False)
    print(json.dumps({k: result.get(k) for k in ("run_id", "mode_ok", "wall_sec", "api_calls_main", "tokens_total_in",
                                                 "model_tool_calls", "inner_tool_calls", "error")} | {"pass": result.get("check", {}).get("pass")},
                     ensure_ascii=False))


if __name__ == "__main__":
    main()
verify/make_fixture.py(固定シードで課題を作る)
verify/make_fixture.py
#!/usr/bin/env python3
"""Build the deterministic fixtures for the Code Mode on/off comparison.

Usage: make_fixture.py <out_dir>
Creates <out_dir>/<task>/work (copied per run) and <out_dir>/<task>/truth.json
for tasks: links, retry, single. Same seed every time, so every run sees the
same files.
"""
import json
import os
import random
import sys

SEED = 20261123


def write(path, text):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text)


def make_links(base):
    """40 Markdown files in 4 folders; some local links point to missing files."""
    rng = random.Random(SEED)
    work = os.path.join(base, "work")
    dirs = ["guide", "api", "ops", "faq"]
    files = []
    for d in dirs:
        for i in range(10):
            files.append(f"docs/{d}/page{i:02d}.md")
    # assets that exist
    write(os.path.join(work, "docs/assets/diagram.png.txt"), "placeholder\n")
    write(os.path.join(work, "README.md"), "# fixture\nSee [docs](docs/guide/page00.md).\n")
    broken = []
    for idx, f in enumerate(files):
        fdir = os.path.dirname(f)
        lines = [f"# {os.path.basename(f)}", ""]
        n_links = rng.randint(3, 6)
        for j in range(n_links):
            kind = rng.random()
            if kind < 0.15:
                lines.append(f"- external [site](https://example.com/{idx}/{j})")
                continue
            if kind < 0.22:
                lines.append(f"- anchor [here](#section-{j})")
                continue
            target_file = rng.choice(files)
            rel = os.path.relpath(target_file, fdir)
            if kind < 0.30:
                rel = rel + f"#part-{j}"
            if kind > 0.86:
                # broken: a file name that does not exist
                rel = os.path.relpath(f"docs/{rng.choice(dirs)}/gone-{idx:02d}-{j}.md", fdir)
                broken.append({"file": f, "link": rel})
            title = ' "title"' if rng.random() < 0.2 else ""
            lines.append(f"- see [link {j}]({rel}{title})")
        if idx % 9 == 4:
            lines.append("- image ![diagram](../assets/diagram.png.txt)")
        if idx % 13 == 6:
            lines.append("- image ![old](../assets/old-diagram.png)")
            broken.append({"file": f, "link": "../assets/old-diagram.png"})
        lines.append("")
        write(os.path.join(work, f), "\n".join(lines))
    broken.sort(key=lambda x: (x["file"], x["link"]))
    # self-check: recompute broken links from disk
    import re
    pat = re.compile(r"\]\(\s*([^)\s]+)(?:\s+\"[^\"]*\")?\s*\)")
    recomputed = []
    for f in files:
        text = open(os.path.join(work, f), encoding="utf-8").read()
        for m in pat.finditer(text):
            link = m.group(1)
            if re.match(r"^[a-z]+:", link) or link.startswith("#"):
                continue
            p = link.split("#", 1)[0]
            full = os.path.normpath(os.path.join(work, os.path.dirname(f), p))
            if not os.path.exists(full):
                recomputed.append({"file": f, "link": link})
    recomputed.sort(key=lambda x: (x["file"], x["link"]))
    assert recomputed == broken, ("truth mismatch", len(recomputed), len(broken))
    json.dump({"broken": broken, "n_files": len(files)}, open(os.path.join(base, "truth.json"), "w"), indent=1)
    return len(files), len(broken)


RETRY_TMPL = """// module {name}
export function retryPolicy() {{
  return {{ maxAttempts: 3, backoffMs: {backoff} }};
}}

export function describe() {{
  return "{name}";
}}
"""

DECOY_TMPL = """// module {name}
export function uploadPolicy() {{
  return {{ maxAttempts: 3, chunkKb: {chunk} }};
}}
"""

TEST_JS = """// node test.js : checks retryPolicy().maxAttempts === 5 in every src module that has it
import { readdirSync } from "node:fs";
import { pathToFileURL } from "node:url";
import path from "node:path";
const dir = path.resolve("src");
let ok = 0, ng = 0;
for (const f of readdirSync(dir).filter((x) => x.endsWith(".mjs")).sort()) {
  const mod = await import(pathToFileURL(path.join(dir, f)).href);
  if (typeof mod.retryPolicy !== "function") continue;
  if (mod.retryPolicy().maxAttempts === 5) ok++; else { ng++; console.log("NG", f); }
}
console.log(`ok=${ok} ng=${ng}`);
process.exit(ng === 0 ? 0 : 1);
"""


def make_retry(base):
    """30 modules with retryPolicy (3 -> 5 wanted) and 6 decoys that must stay 3."""
    rng = random.Random(SEED + 1)
    work = os.path.join(base, "work")
    targets, decoys = [], []
    for i in range(30):
        name = f"svc{i:02d}"
        write(os.path.join(work, f"src/{name}.mjs"), RETRY_TMPL.format(name=name, backoff=rng.choice([100, 200, 500])))
        targets.append(f"src/{name}.mjs")
    for i in range(6):
        name = f"upload{i:02d}"
        write(os.path.join(work, f"src/{name}.mjs"), DECOY_TMPL.format(name=name, chunk=rng.choice([64, 128])))
        decoys.append(f"src/{name}.mjs")
    write(os.path.join(work, "test.js"), TEST_JS)
    write(os.path.join(work, "package.json"), json.dumps({"name": "retry-fixture", "type": "module", "private": True}, indent=2) + "\n")
    expected = {}
    for root, _, fs in os.walk(work):
        for f in fs:
            rel = os.path.relpath(os.path.join(root, f), work)
            text = open(os.path.join(root, f), encoding="utf-8").read()
            if rel in targets:
                text = text.replace("maxAttempts: 3", "maxAttempts: 5")
            expected[rel] = text
    json.dump({"targets": targets, "decoys": decoys, "expected": expected}, open(os.path.join(base, "truth.json"), "w"), indent=1)
    return len(targets), len(decoys)


def make_single(base):
    """Control: a one-step question. Code Mode should not help much here."""
    work = os.path.join(base, "work")
    write(os.path.join(work, "package.json"), json.dumps({"name": "single-fixture", "version": "4.17.3", "private": True}, indent=2) + "\n")
    write(os.path.join(work, "README.md"), "# single fixture\n")
    json.dump({"answer": "4.17.3"}, open(os.path.join(base, "truth.json"), "w"))


def main():
    out = sys.argv[1]
    if os.path.exists(out):
        import shutil
        shutil.rmtree(out)
    n, b = make_links(os.path.join(out, "links"))
    t, d = make_retry(os.path.join(out, "retry"))
    make_single(os.path.join(out, "single"))
    print(json.dumps({"links_files": n, "links_broken": b, "retry_targets": t, "retry_decoys": d}))


if __name__ == "__main__":
    main()
verify/analyze.py(summary.md / summary.csv を作る)
verify/analyze.py
#!/usr/bin/env python3
"""Aggregate <log_dir>/*/metrics.json into summary.csv and summary.md.
Usage: analyze.py <log_dir>
"""
import csv
import glob
import json
import os
import statistics
import sys

log_dir = sys.argv[1]
rows = []
for p in sorted(glob.glob(os.path.join(log_dir, "*", "metrics.json"))):
    m = json.load(open(p))
    rows.append({
        "run_id": m["run_id"], "task": m["task"], "mode": m["mode"], "rep": m["rep"],
        "mode_ok": m.get("mode_ok"), "pass": (m.get("check") or {}).get("pass"),
        "error": m.get("error", ""), "timed_out": m.get("timed_out"),
        "wall_sec": m.get("wall_sec"), "turn_sec": round((m.get("turn_duration_ms") or 0) / 1000, 1),
        "api_calls_main": m.get("api_calls_main"), "api_calls_subagent": m.get("api_calls_subagent"),
        "model_tool_calls": m.get("model_tool_calls"), "inner_tool_calls": m.get("inner_tool_calls"),
        "tokens_total_in": m.get("tokens_total_in"),
        "cache_creation": (m.get("tokens") or {}).get("cache_creation"),
        "output_tokens": (m.get("tokens") or {}).get("output"),
        "last_request_context": m.get("last_request_context"),
        "api_equiv_usd_ref": m.get("api_equiv_cost_usd_reference_only"),
        "cc_version": m.get("cc_version_banner"), "models": ",".join(m.get("models") or []),
    })

with open(os.path.join(log_dir, "summary.csv"), "w", newline="") as f:
    if rows:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)

METRICS = ["turn_sec", "api_calls_main", "model_tool_calls", "inner_tool_calls", "tokens_total_in",
           "output_tokens", "last_request_context", "api_equiv_usd_ref"]


def med(vals):
    vals = [v for v in vals if isinstance(v, (int, float))]
    return round(statistics.median(vals), 3) if vals else None


lines = ["# Code Mode on/off summary", "",
         f"runs: {len(rows)} / valid (mode_ok, no error, not timed out): "
         f"{sum(1 for r in rows if r['mode_ok'] and not r['error'] and not r['timed_out'])}", "",
         "Medians over valid runs. api_equiv_usd_ref is the API-price equivalent Claude Code records; "
         "runs are on the subscription and are not billed per token.", ""]
lines.append("| task | mode | n | pass | " + " | ".join(METRICS) + " |")
lines.append("|" + "---|" * (4 + len(METRICS)))
for task in ["links", "retry", "single"]:
    for mode in ["off", "on"]:
        rs = [r for r in rows if r["task"] == task and r["mode"] == mode and r["mode_ok"] and not r["error"] and not r["timed_out"]]
        if not rs:
            continue
        passed = sum(1 for r in rs if r["pass"])
        lines.append(f"| {task} | {mode} | {len(rs)} | {passed}/{len(rs)} | " + " | ".join(str(med([r[k] for r in rs])) for k in METRICS) + " |")
lines.append("")
lines.append("## ratio on/off (median)")
for task in ["links", "retry", "single"]:
    on = [r for r in rows if r["task"] == task and r["mode"] == "on" and r["mode_ok"] and not r["error"]]
    off = [r for r in rows if r["task"] == task and r["mode"] == "off" and r["mode_ok"] and not r["error"]]
    if not on or not off:
        continue
    parts = []
    for k in ["turn_sec", "api_calls_main", "tokens_total_in", "output_tokens"]:
        a, b = med([r[k] for r in on]), med([r[k] for r in off])
        parts.append(f"{k} {a}/{b}" + (f" = {a / b:.2f}x" if a is not None and b else ""))
    lines.append(f"- {task}: " + "; ".join(parts))
lines.append("")
bad = [r for r in rows if not r["mode_ok"] or r["error"] or r["timed_out"]]
if bad:
    lines.append("## excluded / failed runs")
    for r in bad:
        lines.append(f"- {r['run_id']}: mode_ok={r['mode_ok']} timed_out={r['timed_out']} error={r['error']}")
open(os.path.join(log_dir, "summary.md"), "w").write("\n".join(lines) + "\n")
print("\n".join(lines))
analysis.py(記事用の追加集計。ツール定義のサイズ、リクエストごとのトークンなど)
analysis.py
#!/usr/bin/env python3
"""Extra aggregation for the Code Mode on/off run.
Reads logs/<run>/<session>/transcript.jsonl and prints:
  - tools sent to the model (count, names, JSON chars) and system prompt chars
    (from the 'api-request-shape' record Claude Code writes)
  - per API request input tokens (input + cache_creation + cache_read),
    de-duplicated by message id
  - (added in review) tool definition size per tool, the first request split into
    cache_read / cache_creation / input, the off/on difference at every request
    position, totals per session, and the run time of each Code Mode script
Usage: python3 analysis.py logs/20261123-082859 > logs/analysis_out.txt
"""
import json, sys, os, statistics

run = sys.argv[1]
sessions = sorted(d for d in os.listdir(run) if os.path.isfile(os.path.join(run, d, 'transcript.jsonl')))
rows = []
for s in sessions:
    recs = [json.loads(l) for l in open(os.path.join(run, s, 'transcript.jsonl'))]
    shape = next(r['shape'] for r in recs if r.get('type') == 'api-request-shape')
    tools = shape.get('tools', [])
    sys_chars = sum(len(p.get('text', '')) for p in shape['system'])
    tool_chars = len(json.dumps(tools, ensure_ascii=False))
    seen, per_req, per_req_parts = set(), [], []
    for r in recs:
        if r.get('type') != 'assistant' or r.get('isSidechain'):
            continue
        m = r['message']; mid = m.get('id', '')
        if not mid.startswith('msg_') or mid in seen:
            continue
        seen.add(mid)
        u = m.get('usage', {})
        per_req.append(u.get('input_tokens', 0) + u.get('cache_creation_input_tokens', 0) + u.get('cache_read_input_tokens', 0))
        per_req_parts.append((u.get('input_tokens', 0), u.get('cache_creation_input_tokens', 0), u.get('cache_read_input_tokens', 0)))
    rows.append(dict(s=s, task=s.split('_')[0], mode=s.split('_')[1], ntools=len(tools),
                     names=[t.get('name') for t in tools], tool_chars=tool_chars, sys_chars=sys_chars,
                     per_req=per_req, per_req_parts=per_req_parts,
                     tool_sizes=[(t.get('name'), len(json.dumps(t, ensure_ascii=False))) for t in tools]))

print('== tools and system prompt sent to the model (first api-request-shape)')
print(f"{'session':<14}{'tools':>6}{'tool_json_chars':>17}{'system_chars':>14}")
for r in rows:
    print(f"{r['s']:<14}{r['ntools']:>6}{r['tool_chars']:>17}{r['sys_chars']:>14}")
print()
for mode in ('off', 'on'):
    names = sorted({tuple(r['names']) for r in rows if r['mode'] == mode})
    for n in names:
        print(f'tool names ({mode}): ' + ', '.join(n))
print()
print('== input tokens per API request (input + cache_creation + cache_read)')
print(f"{'session':<14}{'requests':>9}  per_request")
for r in rows:
    print(f"{r['s']:<14}{len(r['per_req']):>9}  " + ' '.join(str(x) for x in r['per_req']))
print()
print('== median first-request input tokens, off vs on')
print(f"{'task':<8}{'off':>8}{'on':>8}{'diff':>8}{'on/off':>8}")
for task in ('links', 'retry', 'single'):
    off = statistics.median(r['per_req'][0] for r in rows if r['task'] == task and r['mode'] == 'off')
    on = statistics.median(r['per_req'][0] for r in rows if r['task'] == task and r['mode'] == 'on')
    print(f"{task:<8}{off:>8.0f}{on:>8.0f}{off-on:>8.0f}{on/off:>8.2f}")

# --- time from the model's last tool call to its final answer (retry task) ---
from datetime import datetime
def ts(x):
    return datetime.fromisoformat(x.replace('Z', '+00:00'))
print()
print('== retry: seconds from the last model tool call to the final answer')
print("   (timestamps in transcript.jsonl; on = the REPL code runs in this gap)")
print(f"{'session':<14}{'last_tool_call':>16}{'final_answer':>14}{'gap_sec':>9}")
for s in sessions:
    if not s.startswith('retry'):
        continue
    recs = [json.loads(l) for l in open(os.path.join(run, s, 'transcript.jsonl'))]
    last_call = final = None
    for r in recs:
        if r.get('type') != 'assistant' or r.get('isSidechain'):
            continue
        m = r['message']
        if not m.get('id', '').startswith('msg_'):
            continue
        kinds = [c.get('type') for c in m.get('content', [])]
        if 'tool_use' in kinds:
            last_call = r['timestamp']
        elif 'text' in kinds and last_call:
            final = r['timestamp']
    gap = (ts(final) - ts(last_call)).total_seconds()
    print(f"{s:<14}{last_call[11:23]:>16}{final[11:23]:>14}{gap:>9.1f}")

# --- where the input tokens are: cache_read vs cache_creation (median per task/mode) ---
print()
print('== median token breakdown and API-price reference (not billed; subscription)')
print(f"{'task':<8}{'mode':<6}{'cache_read':>11}{'cache_creation':>15}{'input':>7}{'usd_ref':>9}")
for task in ('links', 'retry', 'single'):
    for mode in ('off', 'on'):
        ms = [json.load(open(os.path.join(run, s, 'metrics.json'))) for s in sessions
              if s.startswith(f'{task}_{mode}_')]
        med = lambda k: statistics.median(m['tokens'][k] for m in ms)
        usd = statistics.median(m['api_equiv_cost_usd_reference_only'] for m in ms)
        print(f"{task:<8}{mode:<6}{med('cache_read'):>11.0f}{med('cache_creation'):>15.0f}{med('input'):>7.0f}{usd:>9.3f}")
for task in ('links', 'retry', 'single'):
    u = {mode: statistics.median(json.load(open(os.path.join(run, s, 'metrics.json')))['api_equiv_cost_usd_reference_only']
                                 for s in sessions if s.startswith(f'{task}_{mode}_')) for mode in ('off', 'on')}
    print(f"{task}: usd_ref on/off = {u['on']/u['off']:.2f}x")

# --- added in review (2026-11-23): what the ~13k difference is made of ---
# which tools make up the tool definitions (JSON chars per tool)
print()
print('== tool definition size per tool (JSON chars, largest first)')
for mode in ('off', 'on'):
    variants = sorted({tuple(r['tool_sizes']) for r in rows if r['mode'] == mode})
    n = sum(1 for r in rows if r['mode'] == mode)
    for v in variants:
        total = next(r['tool_chars'] for r in rows if r['mode'] == mode and tuple(r['tool_sizes']) == v)
        same = sum(1 for r in rows if r['mode'] == mode and tuple(r['tool_sizes']) == v)
        print(f"{mode}: total {total} chars, {len(v)} tools (same list in {same}/{n} sessions)")
        for name, chars in sorted(v, key=lambda x: -x[1]):
            print(f"  {name:<26}{chars:>7}{chars / total * 100:>6.0f}%")
off_c = statistics.median(r['tool_chars'] for r in rows if r['mode'] == 'off')
on_c = statistics.median(r['tool_chars'] for r in rows if r['mode'] == 'on')
print(f"tool_json_chars off - on = {off_c - on_c:.0f}")

# first request of each session, split into cache_read / cache_creation / input
print()
print('== first request of each session: token breakdown (min..max over sessions)')
print(f"{'mode':<6}{'sessions':>9}{'cache_read':>16}{'cache_creation':>18}{'input':>9}")
first = {}
for mode in ('off', 'on'):
    parts = [r['per_req_parts'][0] for r in rows if r['mode'] == mode]
    rng = lambda i: f"{min(p[i] for p in parts)}..{max(p[i] for p in parts)}"
    first[mode] = statistics.median(p[2] for p in parts)
    print(f"{mode:<6}{len(parts):>9}{rng(2):>16}{rng(1):>18}{rng(0):>9}")
print(f"first-request cache_read off - on = {first['off'] - first['on']:.0f}")

# difference at every request position, not only the first
print()
print('== median input tokens by request position in the session, off vs on')
print(f"{'task':<8}{'request':>8}{'off':>8}{'on':>8}{'diff':>8}{'on/off':>8}")
for task in ('links', 'retry', 'single'):
    n_req = min(len(r['per_req']) for r in rows if r['task'] == task)
    for i in range(n_req):
        off = statistics.median(r['per_req'][i] for r in rows if r['task'] == task and r['mode'] == 'off')
        on = statistics.median(r['per_req'][i] for r in rows if r['task'] == task and r['mode'] == 'on')
        print(f"{task:<8}{i + 1:>8}{off:>8.0f}{on:>8.0f}{off - on:>8.0f}{on / off:>8.2f}")

# total per session (same numbers as tokens_total_in in summary.md), with the difference
print()
print('== median total input tokens per session, off vs on')
print(f"{'task':<8}{'requests':>9}{'off':>8}{'on':>8}{'diff':>8}{'on/off':>8}")
for task in ('links', 'retry', 'single'):
    off = statistics.median(sum(r['per_req']) for r in rows if r['task'] == task and r['mode'] == 'off')
    on = statistics.median(sum(r['per_req']) for r in rows if r['task'] == task and r['mode'] == 'on')
    n_req = statistics.median(len(r['per_req']) for r in rows if r['task'] == task)
    print(f"{task:<8}{n_req:>9.0f}{off:>8.0f}{on:>8.0f}{off - on:>8.0f}{on / off:>8.2f}")

# how long each Code Mode script ran (the 'ms' Claude Code records for each REPL run)
import re
print()
print('== on: run time of each REPL script in ms (poll_events in transcript.jsonl)')
print(f"{'session':<14}  script_ms (one value per REPL call, in order)")
last_ms = {}
for s in sessions:
    if '_on_' not in s:
        continue
    ms = {}
    for l in open(os.path.join(run, s, 'transcript.jsonl')):
        r = json.loads(l)
        att = r.get('attachment') or {}
        if r.get('type') != 'attachment' or att.get('type') != 'poll_events':
            continue
        for env in att.get('envelopes', []):
            m = re.search(r'kind="repl-eval"[^>]*\beval="(\d+)"[^>]*\bms="(\d+)"', env)
            if m:
                ms[int(m.group(1))] = int(m.group(2))
    vals = [ms[k] for k in sorted(ms)]
    last_ms.setdefault(s.split('_')[0], []).append(vals[-1])
    print(f"{s:<14}  " + ' '.join(str(v) for v in vals))
for task in ('links', 'retry', 'single'):
    v = last_ms[task]
    print(f"{task}: last script {min(v)} to {max(v)} ms = {min(v) / 1000:.1f} to {max(v) / 1000:.1f} sec")

おまけ: 今週ほかに出た発表

一次情報のページを開いて確認できたものだけです。

日付は日本時間に直したものです。もとにしたのは公式ページの公開日(米国時間の日付だけのページは翌日にしています)で、ページに日付が無いものは公式 X の投稿時刻です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?