throughline 0.15.2 → 0.15.4

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/CHANGELOG.md CHANGED
@@ -10,6 +10,47 @@ shipped to npm but were not individually tagged on GitHub.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.15.4] — 2026-10-06
14
+
15
+ ### 修正
16
+
17
+ - Claude Desktopで別のprojectへ移した会話を、移った後に1回もターンを終えないまま自動継続で引き継ぐと、後継へ記憶が入らない不具合を直す(0.15.2・0.15.3)。後継の最初の指示は、前任と後継のprojectが同じ時だけ前任を合流させる。前任の`sessions.project_path`を移った先へ付け替えるのはターン終了(Stop)だけだったので、その前に引き継ぐと移る前の場所のまま残り、合流が`project_mismatch`で見送られていた。後継は継続の指示だけを受け取り、記憶と止めた時点の依頼を持たずに動き出していた。
18
+ - 自動圧縮を止める時(`pre-compact`)にも、移っている会話の`sessions.project_path`を移った先へ付け替える。
19
+
20
+ ### 確認した範囲
21
+
22
+ - macOS、Claude Desktop(同梱の2.1.286、権限はバイパス、0.15.3)。画面から送った指示で、圧縮を止める・旧い会話を止める・後継を立てる・継続の指示が届く、の4段が通り、承認待ちは出なかった。1つ目の後継には記憶が入らず(上の不具合)、後継は自分でフォルダを調べて作業を続け、次の引き継ぎ(後継から後継、記憶あり)を経て作業を完了した。
23
+ - macOS、同じ会話の本物のtranscriptの写しを使い、切り離したHOMEでhookを手で呼ぶ再現。0.15.3は`pre-compact`の後も`sessions.project_path`が移る前の場所で、後継の最初の指示は`project_mismatch`・注入なし。この版は移った先へ付け替わり、合流して注入する。
24
+
25
+ ### 確認していない範囲
26
+
27
+ - Claude Desktopの画面で、この版の1つ目の後継に記憶が入ること。
28
+ - Linuxで実物のClaude Codeを動かした通し。Windowsのバイパスの会話、Opus・Fableの後継(0.15.3と同じ)。
29
+
30
+
31
+ ## [0.15.3] — 2026-10-06
32
+
33
+ ### 修正
34
+
35
+ - Claude Codeの自動継続(`auto-handoff enable --host claude`)で、旧い会話が権限のバイパス(`bypassPermissions`)の時、後継が継続の指示を受け取らずに止まる不具合を直す。後継は旧い会話の権限を引き継ぐ。Claude Codeは、バイパス中の会話へ別の会話やprocessから届いた文を、送り手が権限のmodeを名乗らない限り利用者の承認まで止める(画面には`Held peer message`と出る)。0.15.2までは、後継を立てた後で受け口へ指示を送っていたので、ここで止まり、記録は`unknown`・`handoff_delivery_timeout`になっていた。バイパス以外の権限では起きない。
36
+ - 継続の指示は、後継を立てる時の最初の指示として渡す(`claude --bg … "<指示>"`)。立てた後で外から送らない。後継の受信の設定(`crossSessionInbound`)は変えない([ADR 0033](docs/adr/0033-claude-auto-handoff-new-session.md)の4と5を書き換え)。
37
+ - 受領は、後継の最初の指示が`~/.throughline/claude-auto-handoff/<旧会話のsession_id>.accepted`に残し、workerがそれを待って`sent`にする。最初の指示は、workerが後継のIDを記録へ写す前に届くことがあるので、その間は指示が運ぶ引き継ぎIDで後継と認める。期限(60秒)までに残らなければ`unknown`・`handoff_delivery_unconfirmed`にし、後継は立て直さない。`handoff_successor_target_unavailable`と`handoff_delivery_timeout`は出なくなる。
38
+ - 継続の指示の文に、「実行されなかった道具」はまだ実行されていないこと、最初にそれを呼び出すことを書き足す。指示が利用者の発言として届くようになり、Haiku 4.5の後継が、止められた道具をやり直さずに「読みました」と書いて先へ進んだ回があった(macOS、1回)。
39
+ - 後継の`SessionStart`は受け口を控えなくなる。Codexの自動継続は変えない。
40
+
41
+ ### 確認した範囲
42
+
43
+ - macOS、Claude Desktop(同梱の2.1.286、権限はバイパス、0.15.2)。作業フォルダを移した会話で、圧縮を止める・旧い会話を止める・後継を立てる、の3段がDesktopの画面から送った指示で通り、4段目が上の理由で止まることを確かめた。
44
+ - macOS、端末の会話(Claude Code 2.1.289、Haiku 4.5)。この版で、バイパスの会話は4回、編集の自動許可(`acceptEdits`)の会話も4回、連続で引き継いで14個を読み切り完了。どの引き継ぎも`sent`で、承認待ちは出ない。指示の文を書き足す前の版では、バイパスで2回動かし、1回は完了、1回は上の「読みました」で未完了。
45
+ - Windows 11、端末の会話(2.1.289、Haiku 4.5、`acceptEdits`)。この版で4回連続で引き継いで完了。最初の指示(改行と日本語を含む)は、そのまま後継のhookへ届く。
46
+
47
+ ### 確認していない範囲
48
+
49
+ - Claude Desktopの画面で、この版が最後まで通ること(後継が指示を受け取って作業を終える所)。
50
+ - Linuxで実物のClaude Codeを動かした通し。単体と結合の試験だけ。
51
+ - Windowsのバイパスの会話、Opus・Fableの後継。
52
+
53
+
13
54
  ## [0.15.2] — 2026-10-06
14
55
 
15
56
  ### 修正
@@ -1790,7 +1831,9 @@ two attempts, instrument first instead of patching again.
1790
1831
 
1791
1832
  ---
1792
1833
 
1793
- [Unreleased]: https://github.com/kitepon/Throughline/compare/v0.15.2...HEAD
1834
+ [Unreleased]: https://github.com/kitepon/Throughline/compare/v0.15.4...HEAD
1835
+ [0.15.4]: https://github.com/kitepon/Throughline/compare/v0.15.3...v0.15.4
1836
+ [0.15.3]: https://github.com/kitepon/Throughline/compare/v0.15.2...v0.15.3
1794
1837
  [0.15.2]: https://github.com/kitepon/Throughline/compare/v0.15.1...v0.15.2
1795
1838
  [0.15.1]: https://github.com/kitepon/Throughline/compare/v0.15.0...v0.15.1
1796
1839
  [0.15.0]: https://github.com/kitepon/Throughline/compare/v0.14.3...v0.15.0
@@ -28,8 +28,8 @@
28
28
  最初の成立検証はCodex Desktopで行う。OSごとの仕組みと受入条件は共通にし、
29
29
  差分は既存の `src/os/` と配送ライブラリの環境適合へ閉じ込める。
30
30
  VS Code・CLIとClaude/Grok/Cursorの対応はhostごとに同じ条件で検証する。
31
- Claude Codeは同じ並び(圧縮を止める、旧い会話を止める、新しい会話を立てる、継続の指示を1通送る)を、
32
- Claude Codeの入口(hook、`claude --bg`、会話ごとの受け口)で行う([ADR 0033](adr/0033-claude-auto-handoff-new-session.md))。
31
+ Claude Codeは同じ並び(圧縮を止める、旧い会話を止める、新しい会話を立てる、継続の指示を1通渡す)を、
32
+ Claude Codeの入口(hook、最初の指示つきの`claude --bg`)で行う([ADR 0033](adr/0033-claude-auto-handoff-new-session.md))。
33
33
  この節の処理順と進行状態の細目はCodexだけに適用する。
34
34
  一つのhostの成功で他のhostも対応済みとはしない。
35
35
 
@@ -14,10 +14,10 @@ Codex 版の各段に当たるものを、Claude Code 2.1.289 の公式文書と
14
14
  | Codex 版の段 | Claude Code で当たるもの | 確認 |
15
15
  |---|---|---|
16
16
  | 圧縮の前に旧タスクを止める | `PreCompact` の exit code 2 で圧縮を止める。`PreToolUse` が `permissionDecision: "deny"` と `continue: false` を返すと、その道具は実行されずにターンが止まる | 実機 |
17
- | 新しいタスクを作る | `claude --bg`。指示を付けずに起動すると、指示を待つ会話が立つ(`idle — send a prompt to start`) | 実機 |
17
+ | 新しいタスクを作る | `claude --bg`。指示を付けずに起動すると、指示を待つ会話が立つ(`idle — send a prompt to start`)。指示を付けて起動すると、その指示でターンが始まる | 実機 |
18
18
  | 止めたターンを取り込んでから記憶を作る | hook で止めたターンでは Stop hook が走らない。worker が、後継を立てる前に transcript から取り込む | 実機(0.14.1) |
19
19
  | 記憶を入れる | 最初の指示の `UserPromptSubmit` hook の出力。`/tl` の印(baton)の引き継ぎと同じ | 実機 |
20
- | 「続けて」を送る | 会話ごとの受け口(inbox socket)。配送ライブラリ `aiterm-steer-delivery` 0.1.13 の `sendClaudeInbox` | 実機 |
20
+ | 「続けて」を送る | `claude --bg` の最初の指示(0.15.3 から)。0.15.2 までは会話ごとの受け口(inbox socket)へ `aiterm-steer-delivery` の `sendClaudeInbox` で送っていた | 実機 |
21
21
 
22
22
  `PreCompact` の `continue` は捨てられるので、圧縮を止める hook と作業を止める hook は別になる。
23
23
  `PreToolUse` が `continue: false` だけを返すと、その道具は実行されてから止まる。`deny` を一緒に返すと実行されない。
@@ -33,6 +33,7 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
33
33
  印の project は、会話を起動した場所(`CLAUDE_PROJECT_DIR`)を、その OS の書き方にそろえたもの(0.14.2)。
34
34
  Claude Desktop で会話を別の project へ移している時は、transcript の `relocated` の行(`relocatedCwd`)が示す移った先を使う。
35
35
  `CLAUDE_PROJECT_DIR` は移る前の場所のまま届くため(0.15.2)。
36
+ この時、前任の `sessions.project_path` も移った先へ付け替える(0.15.4)。後継は同じ project の前任だけを合流させる。
36
37
  hook の cwd は Bash の `cd` に追従するので使わない。後継は起動した場所で立ち、その cwd で印を探す。
37
38
  手動の `/compact`、無効な project、subagent の中の圧縮(payload に `agent_id`)、script から起動した会話
38
39
  (`CLAUDE_CODE_ENTRYPOINT` が `sdk-` で始まる)では止めない。
@@ -40,7 +41,8 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
40
41
  実行させずに止める。旧い会話は止めるだけで、空にしない。同じ応答に並んだ道具も全て止め、後継の立ち上げは1回だけ行う。
41
42
  記録が無い会話では、記録のファイルの有無だけを見て終わる。subagent の中の道具は止めない。
42
43
  3. **新しい会話を立てる**: 切り離した worker が、止めた時点の依頼・モデル・推論強度・権限を記録へ写し、
43
- 同じ project で `claude --bg` を指示なしで起動する。起動時に `--model`・`--effort`・`--permission-mode` を渡し、
44
+ 同じ project で `claude --bg` を、継続の指示を最初の指示として付けて起動する(0.15.3。下の4)。
45
+ 起動時に `--model`・`--effort`・`--permission-mode` を渡し、
44
46
  `--settings '{"worktree":{"bgIsolation":"none"}}'` で同じ作業ツリーを編集させる。
45
47
  依頼と直前の発言は、止めた道具の呼び出しが transcript に書かれるのを待ってから読む(hook の時点では直前の発言が
46
48
  まだ書かれていないことがある)。
@@ -48,10 +50,14 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
48
50
  bodies の本文にし、道具の入出力は transcript の末尾(止めた道具の呼び出し)まで details に入れる。
49
51
  完了したターンは最後の本文だけを残すが、止めたターンには結論の発言が無いので、全部を残す。
50
52
  取り込めなくても引き継ぎは止めない。理由は worker のログに残り、状態の `in_flight_captured` が `false` になる。
51
- 4. **継続の指示を1通送る**: 後継の `SessionStart` hook が、同じ project に立ち上げ中の引き継ぎがある時だけ、
52
- 自分の受け口(`CLAUDE_CODE_MESSAGING_SOCKET` と token)を控える。worker はそれを読んで消し、
53
- `sendClaudeInbox` で継続の指示を1通送る。配送は公開 API だけを使い、Throughline の中に送信の実装を持たない。
54
- 届いた時の `UserPromptSubmit` が baton を消費して前任を合流させ、記憶を注入する。
53
+ 4. **継続の指示を1通渡す**: 継続の指示は、後継を起動する時の最初の指示として渡す(0.15.3、オーナーの判断 2026-10-06)。
54
+ 立てた後で外から送らない。Claude Code は、権限のバイパス中の会話へ届いた文を、送り手が権限の mode を名乗らない限り
55
+ 利用者の承認まで止める(cross-session messaging の決まり。画面には `Held peer message` と出る)。
56
+ 後継は旧い会話の権限を引き継ぐので、旧い会話がバイパスだと、0.15.2 までの配送(後継の受け口へ `sendClaudeInbox` で送る)は
57
+ 承認待ちで止まり、引き継ぎが進まなかった。後継の設定で受信を緩める方法(`crossSessionInbound: accept`)は採らない。
58
+ バイパス中の後継が、他の会話からの文も確認なしで受け取るようになるため。
59
+ `claude` は stdin も指示に足すので、起動時に stdin は渡さない。
60
+ その指示の `UserPromptSubmit` が baton を消費して前任を合流させ、記憶を注入する。
55
61
  注入は ADR 0016 と同じ予算(9,500 字)で、ヘッダに作業ディレクトリ、現在地、案内、直近の L2 の順に載せる。
56
62
  宣言文は求めない。現在地は止めたターンで、次の順に載せる(0.14.1)。
57
63
  - 止めた時点の依頼(3,500 字まで)。
@@ -61,9 +67,11 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
61
67
  - 止める直前に呼ぼうとして、実行されなかった道具。圧縮を止めた後の応答が呼んだ道具は、どれも実行されていない。
62
68
  hook は並んで走るので、同じ応答(`message.id`)の道具をまとめて扱う。
63
69
  止めたターンは現在地にだけ載せ、L2 の一覧には重ねない。そのターンの道具の入出力は `throughline detail` で取り出せる。
64
- 5. **受領**: 継続の指示は引き継ぎ ID を含む。後継の最初の指示がその ID を含む時だけ、受領を記録する。
65
- `sendClaudeInbox` の結果が `accepted` なら `sent`、`not_sent` なら `failed`、`unknown` なら `unknown` にする。
66
- 結果が不明な時は再送しない。後継が作業を進めたことまでは確かめない(オーナーの判断: 不要)。
70
+ 5. **受領**: 継続の指示は引き継ぎ ID を含む。後継の最初の指示がその ID を含む時だけ、受領を残す
71
+ (`<旧会話の session_id>.accepted`。記録は worker だけが書き換える)。最初の指示は、worker が後継の ID を記録へ写す前に
72
+ 届くことがあるので、その間は指示が運ぶ引き継ぎ ID で後継と認める。worker は受領を待ち、残れば `sent`、
73
+ 期限(60秒)までに残らなければ `unknown`(`handoff_delivery_unconfirmed`)にする。
74
+ 受領を確かめられない時も、後継を立て直さない。後継が作業を進めたことまでは確かめない(オーナーの判断: 不要)。
67
75
  6. **連続の引き継ぎ**: 後継も同じ hook で止まり、次の後継へ引き継ぐ。後継の最後の user 発言は前の引き継ぎの
68
76
  継続の指示なので、現在地には前の引き継ぎが運んだ元の依頼を引き続き載せる。
69
77
  7. **道具を呼ばずに終わったターン**: 圧縮を止めた後、モデルが道具を呼ばずにターンを終えたら、Stop hook が記録を取り下げる。
@@ -108,4 +116,8 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
108
116
  - Windows 11。端末の会話(2.1.289)から始めた。0.14.2 で、Haiku 4.5 は4回、連続で引き継いで完了した。
109
117
  0.14.1 までは、印(baton)に残す project の場所が `C:/…` の形で、後継が `C:\…` の形で探して見つけられなかった。
110
118
  印と記録に残す場所は、その OS の書き方にそろえる(0.14.2)。
111
- - Claude Desktop の画面から始めた会話、Fable、subagent が動いている最中の引き継ぎは確かめていない。
119
+ - Claude Desktop の画面から送った指示(同梱の 2.1.286、権限はバイパス、作業フォルダを移した会話、0.15.2)。圧縮を止める・
120
+ 旧い会話を止める・後継を立てる、の3段は通った。継続の指示は、バイパス中の後継が承認待ちで止めた(0.15.3 で渡し方を変えた理由)。
121
+ - 0.15.3(継続の指示を最初の指示として渡す)。macOS の端末の会話(2.1.289、Haiku 4.5)で、バイパスは4回、`acceptEdits` も4回、
122
+ 連続で引き継いで完了。Windows 11 の端末の会話(`acceptEdits`)でも4回連続で引き継いで完了した。
123
+ - 0.15.3 が Claude Desktop の画面で最後まで通ること、Linux の実物での通し、Fable、subagent が動いている最中の引き継ぎは確かめていない。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "throughline",
3
- "version": "0.15.2",
3
+ "version": "0.15.4",
4
4
  "type": "module",
5
5
  "description": "Persistent memory hooks for Claude Code, Codex, Grok, and Cursor (/clear-safe context compression)",
6
6
  "keywords": [
@@ -8,24 +8,24 @@
8
8
  * 2. PreToolUse : 記録がある会話の次の道具を、実行させずに止める(deny + continue:false)。
9
9
  * 止めた時点の依頼・設定を記録へ写し、後継を立てる worker を起動する。
10
10
  * 3. worker : 止めたターンを DB へ取り込み(発言の全部と道具の入出力)、ここまでにしたことを
11
- * 記録へ写す。`claude --bg` で、指示を待つ新しい会話を同じ project に立てる。
12
- * 4. worker : 後継の SessionStart が残した受け口へ、配送ライブラリで継続の指示を1通送る。
13
- * 届いた時の UserPromptSubmit が baton を消費し、記憶を注入する。
11
+ * 記録へ写す。`claude --bg` を、継続の指示を最初の指示として付けて、同じ project に立てる。
12
+ * 4. 後継の UserPromptSubmit : その指示が baton を消費し、記憶を注入して、受領を残す。worker は受領を待つ。
13
+ * 外から後継へ文を送らない。権限のバイパス中の会話は、外から届いた文を
14
+ * 利用者の承認まで止めるため(0.15.3)。
14
15
  *
15
16
  * 旧い会話は止めるだけで、空にしない。手動の /compact と subagent の中の圧縮は対象にしない。
16
17
  * 状態は ~/.throughline/claude-auto-handoff/ のファイルに持つ(schema は変えない)。
17
18
  */
18
19
 
19
- import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
21
  import { homedir } from 'node:os';
21
22
  import { basename, dirname, join, posix, resolve, win32 } from 'node:path';
22
23
  import { randomUUID } from 'node:crypto';
23
24
  import { fileURLToPath } from 'node:url';
24
25
  import { setTimeout as delay } from 'node:timers/promises';
25
- import { sendClaudeInbox } from 'aiterm-steer-delivery';
26
26
  import { readClaudeAutoHandoffConfig, claudeAutoHandoffEnabledFor } from './claude-auto-handoff-config.mjs';
27
27
  import { CLAUDE_HOST, hostOfSessionId } from './hosts/identity.mjs';
28
- import { claudeHostAdapter } from './hosts/claude.mjs';
28
+ import { claudeHostAdapter, readClaudeRelocatedCwd } from './hosts/claude.mjs';
29
29
  import {
30
30
  isJunkAssistantText,
31
31
  normalizeTerminalText,
@@ -45,7 +45,7 @@ const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), '../bin/throug
45
45
  const STALE_RECORD_MS = 24 * 60 * 60 * 1000;
46
46
  // session id を記録のファイル名に使う。Claude の id は UUID で、path の区切りを含む値は受け付けない。
47
47
  const CLAUDE_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
48
- // `claude --bg` の出力(例: "backgrounded · a41a97ae · name (idle — send a prompt to start)")。
48
+ // `claude --bg` の出力(例: "backgrounded · a41a97ae · name"。指示なしで立てた時は "(idle — send a prompt to start)" が続く)。
49
49
  // 後継の中から起動した時は ID に色の制御文字が付くので、外してから読む。
50
50
  const BACKGROUNDED_PATTERN = /backgrounded\s+\S+\s+([0-9a-f]{8})\b/;
51
51
  // 後継へ渡さない、会話ごとの環境変数。後継は自分の値を持つ。
@@ -54,11 +54,14 @@ const PER_SESSION_ENV = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_ME
54
54
 
55
55
  // requested と failed は、次の道具の hook が後継の立ち上げを始められる。
56
56
  const RETRYABLE_STATES = new Set(['requested', 'failed']);
57
- const TARGET_WAIT_STATES = new Set(['launching', 'launched']);
58
- const ACCEPTABLE_STATES = new Set(['launched', 'sending', 'sent', 'unknown']);
57
+ // 後継の最初の指示は、worker が後継の ID を記録へ写す前に届くことがある(launching)。
58
+ const ACCEPTABLE_STATES = new Set(['launching', 'launched', 'sent', 'unknown']);
59
59
 
60
60
  export const claudeAutoHandoffDir = () => join(homedir(), '.throughline', 'claude-auto-handoff');
61
+ // 0.15.2 までが受け口の控えを置いた場所。期限の掃除だけを続ける。
61
62
  const targetsDir = (dir) => join(dir, 'targets');
63
+ // 後継の最初の指示が残す受領。記録(worker が書き換える)とは別のファイルにして、書き込みが重ならないようにする。
64
+ const acceptancePath = (sessionId, dir) => join(dir, `${sessionId}.accepted`);
62
65
 
63
66
  class ClaudeHandoffError extends Error {
64
67
  constructor(code) { super(code); this.code = code; }
@@ -141,7 +144,7 @@ function removeStale(dir, now) {
141
144
  throw error;
142
145
  }
143
146
  for (const name of names) {
144
- if (!/\.(json|claim|log)$/.test(name)) continue;
147
+ if (!/\.(json|claim|log|accepted)$/.test(name)) continue;
145
148
  const path = join(folder, name);
146
149
  let modifiedAt;
147
150
  try { modifiedAt = statSync(path).mtimeMs; }
@@ -219,7 +222,15 @@ export function requestClaudeAutoHandoff({
219
222
  }
220
223
 
221
224
  // /tl と同じ印。後継の最初の指示が、この会話を前任として合流させる。
222
- writeBaton(openDb(), { projectPath, sessionId, now });
225
+ const db = openDb();
226
+ // 会話が別の project へ移っている時(Claude Desktop)は、sessions の project も移った先にそろえる。
227
+ // 合流は前任と後継の project が同じ時だけ行う。付け替えは Stop でも行うが、移った後に1回も Stop を
228
+ // 通らないまま引き継ぐ会話があり、その時は後継へ記憶が入らなかった(0.15.2・0.15.3、macOS で実測)。
229
+ if (readClaudeRelocatedCwd(payload.transcript_path)) {
230
+ db.prepare('UPDATE sessions SET project_path = ? WHERE session_id = ? AND project_path <> ?')
231
+ .run(projectPath, sessionId, projectPath);
232
+ }
233
+ writeBaton(db, { projectPath, sessionId, now });
223
234
  mkdirSync(dir, { recursive: true, mode: 0o700 });
224
235
  removeStale(dir, now);
225
236
  const handoffId = randomUUID();
@@ -476,44 +487,12 @@ export function completeClaudeTurnWithoutHandoff({ sessionId, dir = claudeAutoHa
476
487
 
477
488
  /** 後継へ送る継続の指示。引き継ぎIDを含め、後継の最初の指示がこの配送のものかを照合できるようにする。 */
478
489
  export function claudeContinuationInput(record) {
490
+ // この文は後継の最初の指示(利用者の発言)として届く。止めた道具をやり直さずに「済んだ」と書いて
491
+ // 先へ進む後継が出たので(Haiku 4.5、macOS で実測)、実行されていない道具から始めることを明記する。
479
492
  return `Throughline自動継続 ${record.handoff_id}\n` +
480
493
  '注入された記憶と元のユーザー依頼に従い、未完了の作業をそのまま継続してください。' +
481
- '直前の実行結果を確認し、完了済みの操作を重複実行しないでください。';
482
- }
483
-
484
- /**
485
- * SessionStart から呼ぶ。同じ project で後継の立ち上げ中の引き継ぎがある時だけ、この会話の受け口を控える。
486
- * worker が、`claude --bg` の返した ID と会話の ID を照合して読み、読んだら消す。
487
- */
488
- export function recordClaudeSuccessorTarget({ payload, env = process.env, dir = claudeAutoHandoffDir(), now = Date.now() }) {
489
- const sessionId = payload?.session_id;
490
- const socketPath = env.CLAUDE_CODE_MESSAGING_SOCKET;
491
- if (!validSessionId(sessionId) || payload.agent_id || payload.source !== 'startup' ||
492
- typeof socketPath !== 'string' || !socketPath) return false;
493
- const cwd = payload.cwd ?? process.cwd();
494
- const waiting = listClaudeAutoHandoffs({ dir }).some(record =>
495
- TARGET_WAIT_STATES.has(record.state) && sameProjectPath(record.project_path, cwd) &&
496
- (!record.successor?.short_id || sessionId.startsWith(record.successor.short_id)));
497
- if (!waiting) return false;
498
- writeJsonPrivate(join(targetsDir(dir), `${sessionId}.json`), {
499
- session_id: sessionId, socket_path: socketPath, token: env.CLAUDE_CODE_MESSAGING_TOKEN ?? null, recorded_at: now,
500
- });
501
- return true;
502
- }
503
-
504
- function takeSuccessorTarget(shortId, dir) {
505
- let names;
506
- try { names = readdirSync(targetsDir(dir)); }
507
- catch (error) {
508
- if (error.code === 'ENOENT') return null;
509
- throw error;
510
- }
511
- const name = names.find(entry => entry.startsWith(shortId) && entry.endsWith('.json'));
512
- if (!name) return null;
513
- const path = join(targetsDir(dir), name);
514
- const target = readJson(path);
515
- rmSync(path, { force: true });
516
- return target;
494
+ '記憶の「実行されなかった道具」は、まだ実行されていません。最初にそれを実際に呼び出してから、先へ進んでください。' +
495
+ '「ここまでにしたこと」に載っている完了済みの操作は、重複実行しないでください。';
517
496
  }
518
497
 
519
498
  /**
@@ -526,15 +505,26 @@ export function acceptClaudeAutoContinuation({ predecessorId, successorSessionId
526
505
  dir = claudeAutoHandoffDir(), now = Date.now() }) {
527
506
  if (!validSessionId(predecessorId) || typeof successorSessionId !== 'string') return null;
528
507
  const record = readClaudeAutoHandoff(predecessorId, dir);
529
- if (!record || !ACCEPTABLE_STATES.has(record.state) || !record.successor?.short_id ||
530
- !successorSessionId.startsWith(record.successor.short_id)) return null;
531
- if (typeof prompt === 'string' && prompt.includes(`Throughline自動継続 ${record.handoff_id}`) && !record.accepted_at) {
532
- updateRecord(predecessorId, { accepted_at: now }, { dir, now });
508
+ if (!record || !ACCEPTABLE_STATES.has(record.state)) return null;
509
+ const carriesInstruction = typeof prompt === 'string' && prompt.includes(`Throughline自動継続 ${record.handoff_id}`);
510
+ // 後継の ID が記録に入っていれば ID で、まだなら指示が運ぶ引き継ぎ ID で、後継と認める。
511
+ const isSuccessor = record.successor?.short_id
512
+ ? successorSessionId.startsWith(record.successor.short_id)
513
+ : carriesInstruction;
514
+ if (!isSuccessor) return null;
515
+ if (carriesInstruction && !record.accepted_at && !existsSync(acceptancePath(predecessorId, dir))) {
516
+ writeJsonPrivate(acceptancePath(predecessorId, dir),
517
+ { handoff_id: record.handoff_id, successor_session_id: successorSessionId, accepted_at: now });
533
518
  }
534
519
  return { handoffId: record.handoff_id, projectPath: record.project_path, inFlight: record.in_flight ?? null,
535
520
  transcriptPath: record.transcript_path ?? null };
536
521
  }
537
522
 
523
+ function readAcceptance(sessionId, handoffId, dir) {
524
+ const acceptance = readJson(acceptancePath(sessionId, dir));
525
+ return acceptance?.handoff_id === handoffId && typeof acceptance.accepted_at === 'number' ? acceptance : null;
526
+ }
527
+
538
528
  function successorArgs(record) {
539
529
  const args = ['--bg', '--name', `tl-${basename(record.project_path)}-${record.handoff_id.slice(0, 8)}`];
540
530
  const { model, effort, permission_mode: permissionMode } = record.settings ?? {};
@@ -543,6 +533,9 @@ function successorArgs(record) {
543
533
  if (permissionMode) args.push('--permission-mode', permissionMode);
544
534
  // 後継は旧い会話の続きなので、同じ作業ツリーを編集する。別の worktree へ移さない。
545
535
  args.push('--settings', JSON.stringify({ worktree: { bgIsolation: 'none' } }));
536
+ // 継続の指示は、起動時の最初の指示として渡す。立てた後で外から送ると、権限のバイパス中の後継は
537
+ // その文を利用者の承認まで止める(Claude Code の cross-session messaging の決まり)。
538
+ args.push(claudeContinuationInput(record));
546
539
  return args;
547
540
  }
548
541
 
@@ -553,17 +546,16 @@ function successorEnv(env) {
553
546
  }
554
547
 
555
548
  /**
556
- * 後継を立てて、継続の指示を1通送る。失敗は固定の理由を記録して止まる。送信の結果が不明な時は再送しない。
549
+ * 継続の指示を付けて後継を立て、後継の最初の指示が受領を残すのを待つ。失敗は固定の理由を記録して止まる。
550
+ * 受領を確かめられない時も、後継を立て直さない(同じ指示を持った会話を2つ作らない)。
557
551
  */
558
552
  export async function runClaudeAutoHandoffWorker(sessionId, {
559
553
  dir = claudeAutoHandoffDir(),
560
554
  env = process.env,
561
555
  spawn = spawnPortableSync,
562
- send = sendClaudeInbox,
563
556
  openDb = null,
564
557
  transcriptTimeoutMs = 5_000,
565
- targetTimeoutMs = 30_000,
566
- sendTimeoutMs = 30_000,
558
+ acceptTimeoutMs = 60_000,
567
559
  pollMs = 200,
568
560
  } = {}) {
569
561
  let record = readClaudeAutoHandoff(sessionId, dir);
@@ -573,7 +565,8 @@ export async function runClaudeAutoHandoffWorker(sessionId, {
573
565
  const fail = code => update({ state: 'failed', error_code: code });
574
566
 
575
567
  // 止めた時点の依頼・ここまでにしたこと・その時のモデルを写し、止めたターンを DB へ取り込む。
576
- // 後継の最初の指示が、これを現在地として受け取る。
568
+ // 後継の最初の指示が、これを現在地として受け取る。前の引き継ぎの受領が残っていれば消す。
569
+ rmSync(acceptancePath(sessionId, dir), { force: true });
577
570
  await waitForStoppedToolUse(record, { timeoutMs: transcriptTimeoutMs, pollMs });
578
571
  const inFlight = record.transcript_path ? snapshotInFlight(record, dir) : null;
579
572
  if (inFlight && openDb) inFlight.turn = captureStoppedTurn(record, openDb);
@@ -597,31 +590,15 @@ export async function runClaudeAutoHandoffWorker(sessionId, {
597
590
  }
598
591
  update({ state: 'launched', successor: { short_id: shortId, session_id: null } });
599
592
 
600
- let target = null;
601
- for (const deadline = Date.now() + targetTimeoutMs; !target && Date.now() < deadline;) {
602
- target = takeSuccessorTarget(shortId, dir);
603
- if (!target) await delay(pollMs);
593
+ // 指示は起動時に渡してある。後継の最初の UserPromptSubmit が受領を残すのを待つ。
594
+ for (const deadline = Date.now() + acceptTimeoutMs; Date.now() < deadline;) {
595
+ const acceptance = readAcceptance(sessionId, record.handoff_id, dir);
596
+ if (acceptance) {
597
+ rmSync(acceptancePath(sessionId, dir), { force: true });
598
+ return update({ state: 'sent', error_code: null, accepted_at: acceptance.accepted_at,
599
+ successor: { short_id: shortId, session_id: acceptance.successor_session_id } });
600
+ }
601
+ await delay(pollMs);
604
602
  }
605
- if (!target) return fail('handoff_successor_target_unavailable');
606
- update({ successor: { short_id: shortId, session_id: target.session_id } });
607
-
608
- // ここから先は後継へ指示が届き得る。結果が不明でも、同じ指示をもう一度送らない。
609
- update({ state: 'sending' });
610
- const result = await send(
611
- { socket_path: target.socket_path, ...(target.token ? { token: target.token } : {}) },
612
- claudeContinuationInput(record),
613
- {
614
- timeout_ms: sendTimeoutMs,
615
- confirm_acceptance: async signal => {
616
- while (!signal.aborted) {
617
- if (readClaudeAutoHandoff(sessionId, dir)?.accepted_at) return true;
618
- await delay(pollMs);
619
- }
620
- return false;
621
- },
622
- },
623
- );
624
- if (result.status === 'accepted') return update({ state: 'sent', error_code: null });
625
- if (result.status === 'not_sent') return fail(`handoff_delivery_${result.reason}`);
626
- return update({ state: 'unknown', error_code: `handoff_delivery_${result.reason}` });
603
+ return update({ state: 'unknown', error_code: 'handoff_delivery_unconfirmed' });
627
604
  }
@@ -10,7 +10,6 @@ import {
10
10
  requestClaudeAutoHandoff,
11
11
  stopClaudeTurnForHandoff,
12
12
  completeClaudeTurnWithoutHandoff,
13
- recordClaudeSuccessorTarget,
14
13
  acceptClaudeAutoContinuation,
15
14
  runClaudeAutoHandoffWorker,
16
15
  readClaudeAutoHandoff,
@@ -71,13 +70,19 @@ test('PreCompact: 会話が別の project へ移っている時は、移った
71
70
  writeFileSync(transcriptPath, jsonl([user('読んで', '2026-10-05T22:38:17.050Z'), assistant('読みました', '2026-10-05T22:39:18.926Z'),
72
71
  { type: 'relocated', sessionId: SESSION, relocatedCwd: moved }]));
73
72
  const onlyMoved = { enabled: true, projects: [moved] };
73
+ // SessionStart は移る前の場所で sessions の行を作っている
74
+ const relocatedDb = makeBatonDb();
75
+ relocatedDb.exec('CREATE TABLE sessions (session_id TEXT PRIMARY KEY, project_path TEXT NOT NULL)');
76
+ relocatedDb.prepare('INSERT INTO sessions VALUES (?, ?)').run(SESSION, scratch);
74
77
 
75
- const { result, db } = request(dir, { config: onlyMoved, transcriptPath, env: { CLAUDE_PROJECT_DIR: scratch }, payload: { cwd: moved } });
78
+ const { result, db } = request(dir, { db: relocatedDb, config: onlyMoved, transcriptPath, env: { CLAUDE_PROJECT_DIR: scratch }, payload: { cwd: moved } });
76
79
  assert.equal(result.status, 'requested');
77
80
  assert.equal(result.block, true);
78
81
  assert.equal(result.projectPath, moved);
79
82
  assert.equal(readClaudeAutoHandoff(SESSION, dir).project_path, moved);
80
83
  assert.equal(db.prepare('SELECT session_id FROM handoff_batons WHERE project_path = ?').get(moved).session_id, SESSION);
84
+ assert.equal(db.prepare('SELECT project_path FROM sessions WHERE session_id = ?').get(SESSION).project_path, moved,
85
+ '後継は同じ project の前任だけを合流させるので、sessions の project も移った先にそろえる');
81
86
  }));
82
87
 
83
88
  test('PreCompact: 移っていない会話は、これまでどおり起動した project で決める', () => withDir(dir => {
@@ -243,64 +248,48 @@ test('Stop: 圧縮を止めた後、道具を呼ばずにターンが終わっ
243
248
  assert.equal(readClaudeAutoHandoff(SESSION, dir).state, 'stopped');
244
249
  }));
245
250
 
246
- /** 止めた直後の記録を作り、後継の SessionStart と配送を差し替えて worker を走らせる。 */
247
- async function runWorker(dir, { spawn, send, onLaunched }) {
251
+ /** 止めた直後の記録を作り、後継の起動を差し替えて worker を走らせる。 */
252
+ async function runWorker(dir, { spawn, onLaunched }) {
248
253
  request(dir);
249
254
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app', permission_mode: 'acceptEdits',
250
255
  effort: { level: 'high' } }, dir, launchWorker: async () => {} });
251
- const calls = { spawn: [], send: [] };
256
+ const calls = { spawn: [] };
252
257
  const record = await runClaudeAutoHandoffWorker(SESSION, {
253
258
  dir, env: { PATH: '/bin', CLAUDECODE: '1', CLAUDE_CODE_ENTRYPOINT: 'claude-desktop', CLAUDE_CODE_MESSAGING_SOCKET: '/old.sock',
254
259
  CLAUDE_CODE_MESSAGING_TOKEN: 'old-token', CLAUDE_PROJECT_DIR: '/work/app', CLAUDE_CODE_USE_BEDROCK: '1' },
255
- targetTimeoutMs: 300, sendTimeoutMs: 300, pollMs: 10,
260
+ acceptTimeoutMs: 300, pollMs: 10,
256
261
  spawn: (command, args, options) => {
257
262
  calls.spawn.push({ command, args, options });
258
263
  const result = spawn(command, args, options);
259
- if (result.status === 0) onLaunched?.();
264
+ if (result.status === 0) onLaunched?.(args);
260
265
  return result;
261
266
  },
262
- send: async (target, text, options) => { calls.send.push({ target, text }); return send(target, text, options); },
263
267
  });
264
268
  return { record, calls };
265
269
  }
266
270
 
267
- const launchedOk = () => ({ status: 0, stdout: 'Starting background service…\nbackgrounded · a41a97ae · tl-app-1234 (idle — send a prompt to start)\n', stderr: '' });
268
- const successorStarts = dir => () => recordClaudeSuccessorTarget({
269
- payload: { session_id: SUCCESSOR, source: 'startup', cwd: '/work/app' },
270
- env: { CLAUDE_CODE_MESSAGING_SOCKET: '/tmp/cc-socks/271650.sock', CLAUDE_CODE_MESSAGING_TOKEN: 'secret-token' }, dir });
271
-
272
- test('worker: 指示を待つ後継を同じprojectに立て、後継の受け口へ継続の指示を1通送る', () => withDir(async dir => {
273
- const { record, calls } = await runWorker(dir, {
274
- spawn: launchedOk,
275
- onLaunched: successorStarts(dir),
276
- send: async (target, text, options) => {
277
- // 届いた指示で、後継の最初の UserPromptSubmit が受領を記録する
278
- const accepted = acceptClaudeAutoContinuation({ predecessorId: SESSION, successorSessionId: SUCCESSOR, prompt: text, dir });
279
- assert.ok(accepted);
280
- return await options.confirm_acceptance(new AbortController().signal)
281
- ? { status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' }
282
- : { status: 'unknown', outcome_unknown: true, reason: 'unconfirmed' };
283
- },
284
- });
271
+ const launchedOk = () => ({ status: 0, stdout: 'Starting background service…\nbackgrounded · a41a97ae · tl-app-1234\n', stderr: '' });
272
+ // 後継の最初の UserPromptSubmit。起動時に渡された指示で、受領を残す。worker が後継の ID を記録へ写す前に届く。
273
+ const successorStarts = (dir, predecessorId = SESSION) => args => acceptClaudeAutoContinuation({
274
+ predecessorId, successorSessionId: SUCCESSOR, prompt: args.at(-1), dir, now: 5_000 });
275
+
276
+ test('worker: 継続の指示を最初の指示として付けて後継を同じprojectに立て、後継の受領を待つ', () => withDir(async dir => {
277
+ const { record, calls } = await runWorker(dir, { spawn: launchedOk, onLaunched: successorStarts(dir) });
285
278
  assert.equal(calls.spawn.length, 1);
286
279
  const { command, args, options } = calls.spawn[0];
287
280
  assert.equal(command, 'claude');
288
281
  assert.deepEqual(args, ['--bg', '--name', `tl-app-${record.handoff_id.slice(0, 8)}`, '--effort', 'high',
289
- '--permission-mode', 'acceptEdits', '--settings', '{"worktree":{"bgIsolation":"none"}}'],
290
- '指示は起動時に渡さない。モデルは transcript が無いので付かない');
282
+ '--permission-mode', 'acceptEdits', '--settings', '{"worktree":{"bgIsolation":"none"}}', claudeContinuationInput(record)],
283
+ '指示は起動時に渡す(外から送ると、権限のバイパス中の後継が承認まで止める)。モデルは transcript が無いので付かない');
284
+ assert.match(args.at(-1), new RegExp(`^Throughline自動継続 ${record.handoff_id}\\n注入された記憶と元のユーザー依頼に従い、未完了の作業をそのまま継続してください。`));
291
285
  assert.equal(options.cwd, '/work/app');
292
286
  assert.deepEqual(options.env, { PATH: '/bin', CLAUDE_CODE_USE_BEDROCK: '1' }, '会話ごとの環境変数は後継へ渡さない');
287
+ assert.deepEqual(options.stdio, ['ignore', 'pipe', 'pipe'], 'stdin を渡さない(claude は stdin も指示に足す)');
293
288
 
294
- assert.equal(calls.send.length, 1);
295
- assert.deepEqual(calls.send[0].target, { socket_path: '/tmp/cc-socks/271650.sock', token: 'secret-token' });
296
- assert.equal(calls.send[0].text, claudeContinuationInput(record));
297
- assert.match(calls.send[0].text, new RegExp(`^Throughline自動継続 ${record.handoff_id}\\n注入された記憶と元のユーザー依頼に従い、未完了の作業をそのまま継続してください。`));
298
-
299
- assert.deepEqual([record.state, record.error_code], ['sent', null]);
289
+ assert.deepEqual([record.state, record.error_code, record.accepted_at], ['sent', null, 5_000]);
300
290
  assert.deepEqual(record.successor, { short_id: 'a41a97ae', session_id: SUCCESSOR });
301
- assert.deepEqual(readdirSync(join(dir, 'targets')), [], '受け口の控えは読んだら消す');
302
- assert.doesNotMatch(JSON.stringify(publicClaudeAutoHandoff(record)), /secret-token|cc-socks/);
303
- assert.doesNotMatch(readFileSync(join(dir, `${SESSION}.json`), 'utf8'), /secret-token/, 'token は記録に残さない');
291
+ assert.equal(existsSync(join(dir, `${SESSION}.accepted`)), false, '受領の控えは読んだら消す');
292
+ assert.equal(existsSync(join(dir, 'targets')), false, '受け口は控えない');
304
293
 
305
294
  // 引き継ぎ済みの会話の道具は、後継を案内して止める
306
295
  const output = await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app' }, dir,
@@ -309,9 +298,8 @@ test('worker: 指示を待つ後継を同じprojectに立て、後継の受け
309
298
  }));
310
299
 
311
300
  test('worker: 止めた時点の依頼とモデルを transcript から写し、色付きの出力からも後継のIDを読む。後継が止められた時は元の依頼を運ぶ', () => withDir(async dir => {
312
- const sendOk = async () => ({ status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' });
313
301
  const colored = () => ({ status: 0, stderr: '',
314
- stdout: 'backgrounded · \u001b[36ma41a97ae\u001b[39m · tl-app-1234\u001b[2m (idle — send a prompt to start)\u001b[22m\n' });
302
+ stdout: 'backgrounded · \u001b[36ma41a97ae\u001b[39m · tl-app-1234\u001b[2m\u001b[22m\n' });
315
303
  const run = async (sessionId, transcriptPath, toolUseId) => {
316
304
  const db = makeBatonDb();
317
305
  requestClaudeAutoHandoff({ payload: { session_id: sessionId, trigger: 'auto', cwd: '/work/app', transcript_path: transcriptPath },
@@ -319,13 +307,12 @@ test('worker: 止めた時点の依頼とモデルを transcript から写し、
319
307
  await stopClaudeTurnForHandoff({ payload: { session_id: sessionId, cwd: '/work/app', transcript_path: transcriptPath,
320
308
  tool_use_id: toolUseId }, dir, launchWorker: async () => {} });
321
309
  const calls = [];
322
- const record = await runClaudeAutoHandoffWorker(sessionId, { dir, env: {}, send: sendOk, pollMs: 10, targetTimeoutMs: 300,
310
+ const record = await runClaudeAutoHandoffWorker(sessionId, { dir, env: {}, pollMs: 10, acceptTimeoutMs: 300,
323
311
  transcriptTimeoutMs: 300,
324
312
  spawn: (command, args) => {
325
313
  calls.push(args);
326
314
  // 止めた道具の呼び出しは、hook の後で transcript に書かれる
327
- recordClaudeSuccessorTarget({ payload: { session_id: SUCCESSOR, source: 'startup', cwd: '/work/app' },
328
- env: { CLAUDE_CODE_MESSAGING_SOCKET: '/tmp/cc-socks/1.sock' }, dir });
315
+ successorStarts(dir, sessionId)(args);
329
316
  return colored();
330
317
  } });
331
318
  return { record, calls };
@@ -364,12 +351,10 @@ test('worker: 止めた時点の依頼とモデルを transcript から写し、
364
351
  // 後継 B が止められた時、最後の user 発言は A からの継続の指示。現在地には元の依頼を運ぶ
365
352
  const transcriptB = join(dir, 'b.jsonl');
366
353
  writeFileSync(transcriptB, jsonl([
367
- user(`Another Claude session sent a message:\n${claudeContinuationInput(first.record)}\n\nThis came from another Claude session — not typed by your user.`,
368
- '2026-10-04T03:01:00Z'),
354
+ user(claudeContinuationInput(first.record), '2026-10-04T03:01:00Z'),
369
355
  assistant('part09 を読みました。次に part10 を読みます。', '2026-10-04T03:01:20Z', 'claude-opus-5'),
370
356
  { type: 'assistant', message: { role: 'assistant', model: 'claude-opus-5', content: [{ type: 'tool_use', id: 'toolu_10', name: 'Read', input: {} }] } },
371
357
  ]));
372
- rmSync(join(dir, 'targets'), { recursive: true, force: true });
373
358
  const second = await run(SUCCESSOR, transcriptB, 'toolu_10');
374
359
  assert.deepEqual(second.record.in_flight, {
375
360
  user: { content: '14個のファイルを順に読んで', timestamp: Date.parse('2026-10-04T03:00:10Z') },
@@ -428,13 +413,11 @@ test('worker: 止めたターンを DB へ取り込み、ここまでにした
428
413
  // hook は並んで走る。記録に残る止めた道具は、応答の中の2つ目のこともある
429
414
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app', transcript_path: transcript, tool_use_id: 't5' },
430
415
  dir, launchWorker: async () => {} });
431
- const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, targetTimeoutMs: 300, transcriptTimeoutMs: 300,
416
+ const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, acceptTimeoutMs: 300, transcriptTimeoutMs: 300,
432
417
  openDb: () => db,
433
- send: async () => ({ status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' }),
434
- spawn: () => {
435
- recordClaudeSuccessorTarget({ payload: { session_id: SUCCESSOR, source: 'startup', cwd: '/work/app' },
436
- env: { CLAUDE_CODE_MESSAGING_SOCKET: '/tmp/cc-socks/1.sock' }, dir });
437
- return { status: 0, stderr: '', stdout: 'backgrounded · a41a97ae · tl-app (idle — send a prompt to start)\n' };
418
+ spawn: (command, args) => {
419
+ successorStarts(dir)(args);
420
+ return { status: 0, stderr: '', stdout: 'backgrounded · a41a97ae · tl-app\n' };
438
421
  } });
439
422
  assert.equal(record.state, 'sent');
440
423
  assert.deepEqual(record.in_flight.steps, [
@@ -474,13 +457,11 @@ test('worker: 止めたターンを取り込めなくても後継を立て、取
474
457
  env: {}, config: ENABLED, openDb: () => db, dir, platform: 'linux' });
475
458
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app', transcript_path: transcript, tool_use_id: 'toolu_1' },
476
459
  dir, launchWorker: async () => {} });
477
- const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, targetTimeoutMs: 300, transcriptTimeoutMs: 300,
460
+ const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, acceptTimeoutMs: 300, transcriptTimeoutMs: 300,
478
461
  openDb: () => db,
479
- send: async () => ({ status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' }),
480
- spawn: () => {
481
- recordClaudeSuccessorTarget({ payload: { session_id: SUCCESSOR, source: 'startup', cwd: '/work/app' },
482
- env: { CLAUDE_CODE_MESSAGING_SOCKET: '/tmp/cc-socks/1.sock' }, dir });
483
- return { status: 0, stderr: '', stdout: 'backgrounded · a41a97ae · tl-app (idle — send a prompt to start)\n' };
462
+ spawn: (command, args) => {
463
+ successorStarts(dir)(args);
464
+ return { status: 0, stderr: '', stdout: 'backgrounded · a41a97ae · tl-app\n' };
484
465
  } });
485
466
  assert.equal(record.state, 'sent');
486
467
  assert.equal(record.in_flight.turn, null);
@@ -488,23 +469,19 @@ test('worker: 止めたターンを取り込めなくても後継を立て、取
488
469
  assert.equal(publicClaudeAutoHandoff(record).in_flight_captured, false);
489
470
  }));
490
471
 
491
- test('worker: 立ち上げ・受け口・配送の失敗は固定の理由を残し、結果が不明な配送は再送しない', () => withDir(async dir => {
492
- const sendOk = async () => ({ status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' });
472
+ test('worker: 立ち上げの失敗は固定の理由を残し、受領を確かめられない時は後継を立て直さない', () => withDir(async dir => {
493
473
  const cases = [
494
- [{ spawn: () => ({ error: Object.assign(new Error('not found'), { code: 'ENOENT' }) }), send: sendOk }, 'failed', 'handoff_claude_cli_unavailable', 0],
495
- [{ spawn: () => ({ status: 1, stdout: '', stderr: 'Workspace not trusted' }), send: sendOk }, 'failed', 'handoff_successor_launch_failed', 0],
496
- [{ spawn: () => ({ status: 0, stdout: 'unexpected output', stderr: '' }), send: sendOk }, 'failed', 'handoff_successor_launch_failed', 0],
497
- [{ spawn: launchedOk, send: sendOk }, 'failed', 'handoff_successor_target_unavailable', 0],
498
- [{ spawn: launchedOk, onLaunched: successorStarts(dir),
499
- send: async () => ({ status: 'not_sent', outcome_unknown: false, reason: 'connect_failed' }) }, 'failed', 'handoff_delivery_connect_failed', 1],
500
- [{ spawn: launchedOk, onLaunched: successorStarts(dir),
501
- send: async () => ({ status: 'unknown', outcome_unknown: true, reason: 'unconfirmed' }) }, 'unknown', 'handoff_delivery_unconfirmed', 1],
474
+ [{ spawn: () => ({ error: Object.assign(new Error('not found'), { code: 'ENOENT' }) }) }, 'failed', 'handoff_claude_cli_unavailable'],
475
+ [{ spawn: () => ({ status: 1, stdout: '', stderr: 'Workspace not trusted' }) }, 'failed', 'handoff_successor_launch_failed'],
476
+ [{ spawn: () => ({ status: 0, stdout: 'unexpected output', stderr: '' }) }, 'failed', 'handoff_successor_launch_failed'],
477
+ // 後継は立ったが、最初の指示の受領が期限までに残らない
478
+ [{ spawn: launchedOk }, 'unknown', 'handoff_delivery_unconfirmed'],
502
479
  ];
503
- for (const [deps, state, code, sends] of cases) {
480
+ for (const [deps, state, code] of cases) {
504
481
  rmSync(join(dir, `${SESSION}.json`), { force: true });
505
482
  rmSync(join(dir, `${SESSION}.claim`), { force: true });
506
- const { record, calls } = await runWorker(dir, deps);
507
- assert.deepEqual([record.state, record.error_code, calls.send.length], [state, code, sends], code);
483
+ const { record } = await runWorker(dir, deps);
484
+ assert.deepEqual([record.state, record.error_code], [state, code], code);
508
485
  }
509
486
  // 結果が不明な引き継ぎは、次の道具でも立ち上げ直さない
510
487
  const launched = [];
@@ -513,52 +490,42 @@ test('worker: 立ち上げ・受け口・配送の失敗は固定の理由を残
513
490
  assert.equal((await runClaudeAutoHandoffWorker(SESSION, { dir, spawn: () => { throw new Error('must not spawn'); } })).state, 'unknown');
514
491
  }));
515
492
 
516
- test('SessionStart: 後継の立ち上げ中の引き継ぎがある project の、新しく始まった会話だけが受け口を控える', () => withDir(async dir => {
517
- const env = { CLAUDE_CODE_MESSAGING_SOCKET: '/tmp/cc-socks/1.sock', CLAUDE_CODE_MESSAGING_TOKEN: 't' };
518
- const start = (overrides = {}, environment = env) => recordClaudeSuccessorTarget({
519
- payload: { session_id: SUCCESSOR, source: 'startup', cwd: '/work/app', ...overrides }, env: environment, dir });
520
- assert.equal(start(), false, '引き継ぎが無い');
521
- request(dir);
522
- assert.equal(start(), false, 'まだ旧い会話を止めていない');
523
-
524
- const write = fields => writeFileSync(join(dir, `${SESSION}.json`),
525
- JSON.stringify({ ...readClaudeAutoHandoff(SESSION, dir), ...fields }));
526
- write({ state: 'launching' });
527
- assert.equal(start({ cwd: '/work/other' }), false, '別の project');
528
- assert.equal(start({ source: 'resume' }), false);
529
- assert.equal(start({ source: 'compact' }), false);
530
- assert.equal(start({ agent_id: 'agent-1' }), false);
531
- assert.equal(start({}, {}), false, '受け口を持たない会話');
532
- assert.equal(start({ session_id: `grok:${SUCCESSOR}` }), false);
533
- assert.equal(start(), true);
534
- rmSync(join(dir, 'targets'), { recursive: true });
535
-
536
- write({ state: 'launched', successor: { short_id: 'a41a97ae', session_id: null } });
537
- assert.equal(start({ session_id: 'bbbbbbbb-0000-4000-8000-000000000001' }), false, '後継のIDと合わない会話');
538
- assert.equal(start(), true);
539
- write({ state: 'sent' });
540
- rmSync(join(dir, 'targets'), { recursive: true });
541
- assert.equal(start(), false, '送り終えた引き継ぎ');
542
- }));
543
-
544
- test('最初の指示: 後継だけが止めた時点の依頼を受け取り、この引き継ぎの配送だけが受領になる', () => withDir(async dir => {
493
+ test('最初の指示: 後継だけが止めた時点の依頼を受け取り、この引き継ぎの指示だけが受領になる', () => withDir(async dir => {
545
494
  request(dir);
546
495
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app' }, dir, launchWorker: async () => {} });
547
496
  const accept = (overrides = {}) => acceptClaudeAutoContinuation({ predecessorId: SESSION, successorSessionId: SUCCESSOR, dir, ...overrides });
548
- assert.equal(accept(), null, '後継がまだ立っていない');
497
+ const acceptance = () => existsSync(join(dir, `${SESSION}.accepted`))
498
+ ? JSON.parse(readFileSync(join(dir, `${SESSION}.accepted`), 'utf8')) : null;
549
499
  const record = readClaudeAutoHandoff(SESSION, dir);
500
+ const instruction = claudeContinuationInput(record);
501
+ assert.equal(accept({ prompt: instruction }), null, '後継をまだ立てていない(stopped)');
550
502
  const inFlight = { user: { content: '依頼', timestamp: 1 }, last_fragment: null };
551
- writeFileSync(join(dir, `${SESSION}.json`), JSON.stringify({ ...record, state: 'sending',
552
- successor: { short_id: 'a41a97ae', session_id: SUCCESSOR }, in_flight: inFlight }));
553
- assert.equal(accept({ successorSessionId: 'bbbbbbbb-0000-4000-8000-000000000001' }), null, '後継ではない会話');
503
+ const expected = { handoffId: record.handoff_id, projectPath: '/work/app', inFlight, transcriptPath: null };
504
+ const write = fields => writeFileSync(join(dir, `${SESSION}.json`), JSON.stringify({ ...record, in_flight: inFlight, ...fields }));
505
+
506
+ // 立ち上げ中(後継の ID はまだ記録に無い): 指示が運ぶ引き継ぎ ID で後継と認める
507
+ write({ state: 'launching' });
508
+ assert.equal(accept(), null, '指示を持たない会話');
509
+ assert.equal(accept({ prompt: '別の指示' }), null, '同じ project で人が始めた別の会話');
510
+ assert.equal(accept({ prompt: 'Throughline自動継続 00000000-0000-4000-8000-000000000000\n…' }), null, '別の引き継ぎの指示');
511
+ assert.equal(acceptance(), null);
512
+ assert.deepEqual(accept({ prompt: instruction, now: 9_000 }), expected);
513
+ assert.deepEqual(acceptance(), { handoff_id: record.handoff_id, successor_session_id: SUCCESSOR, accepted_at: 9_000 });
514
+ assert.equal(readClaudeAutoHandoff(SESSION, dir).accepted_at, null, '記録は worker だけが書き換える');
515
+ accept({ prompt: instruction, now: 9_999 });
516
+ assert.equal(acceptance().accepted_at, 9_000, '受領は1回だけ残す');
517
+ rmSync(join(dir, `${SESSION}.accepted`));
518
+
519
+ // 後継の ID が記録に入った後: ID で後継と認める
520
+ write({ state: 'launched', successor: { short_id: 'a41a97ae', session_id: null } });
521
+ assert.equal(accept({ successorSessionId: 'bbbbbbbb-0000-4000-8000-000000000001', prompt: instruction }), null, '後継ではない会話');
554
522
  assert.equal(accept({ predecessorId: 'aaaaaaaa-0000-4000-8000-000000000009' }), null);
555
523
  assert.equal(accept({ predecessorId: `codex:${SESSION}` }), null);
556
-
557
524
  // 人が先に別の指示を打った時は、依頼は渡すが受領にはしない
558
- assert.deepEqual(accept({ prompt: '別の指示' }), { handoffId: record.handoff_id, projectPath: '/work/app', inFlight, transcriptPath: null });
559
- assert.equal(readClaudeAutoHandoff(SESSION, dir).accepted_at, null);
560
- accept({ prompt: `Another Claude session sent a message:\n${claudeContinuationInput(record)}`, now: 9_000 });
561
- assert.equal(readClaudeAutoHandoff(SESSION, dir).accepted_at, 9_000);
525
+ assert.deepEqual(accept({ prompt: '別の指示' }), expected);
526
+ assert.equal(acceptance(), null);
527
+ accept({ prompt: instruction, now: 9_500 });
528
+ assert.equal(acceptance().accepted_at, 9_500);
562
529
  }));
563
530
 
564
531
  test('公開CLI: --host claude は enable・disable・status・worker を受け取る', () => {
@@ -710,19 +677,14 @@ test('hook: 自動圧縮を止め、次の道具を止めて worker を起動し
710
677
  assert.equal(handoff.in_flight_captured, true);
711
678
  assert.equal(record.in_flight.turn.origin_session_id, SESSION);
712
679
  assert.equal(record.in_flight.turn.details, 3);
680
+ // 後継の最初の指示は、worker が後継の ID を記録へ写す前(launching)に届くことがある
713
681
  writeFileSync(recordFile, JSON.stringify({ ...record, state: 'launching', error_code: null }));
714
682
  const started = hook('session-start', { hook_event_name: 'SessionStart', source: 'startup' }, SUCCESSOR);
715
683
  assert.equal(started.status, 0, started.stderr);
716
684
  assert.equal(started.stdout, '');
717
- assert.equal(existsSync(join(handoffDir, 'targets')), false, '受け口を持たない会話は控えない');
718
- const withSocket = cli(home, ['session-start'], JSON.stringify({ session_id: SUCCESSOR, cwd: project, hook_event_name: 'SessionStart', source: 'startup' }),
719
- { ...extra, CLAUDE_CODE_MESSAGING_SOCKET: join(home, 'in.sock'), CLAUDE_CODE_MESSAGING_TOKEN: 'secret-token' });
720
- assert.equal(withSocket.status, 0, withSocket.stderr);
721
- assert.deepEqual(readdirSync(join(handoffDir, 'targets')), [`${SUCCESSOR}.json`]);
722
- writeFileSync(recordFile, JSON.stringify({ ...record, state: 'sending', error_code: null,
723
- successor: { short_id: SUCCESSOR.slice(0, 8), session_id: SUCCESSOR } }));
724
-
725
- const prompt = `Another Claude session sent a message:\n${claudeContinuationInput(record)}`;
685
+ assert.equal(existsSync(join(handoffDir, 'targets')), false, '受け口は控えない');
686
+
687
+ const prompt = claudeContinuationInput(record);
726
688
  const first = cli(home, ['prompt-submit'], JSON.stringify({ session_id: SUCCESSOR, cwd: project, hook_event_name: 'UserPromptSubmit', prompt }), extra);
727
689
  assert.equal(first.status, 0, first.stderr);
728
690
  assert.match(first.stdout, /^## Throughline: 自動継続の文脈\n/);
@@ -734,7 +696,9 @@ test('hook: 自動圧縮を止め、次の道具を止めて worker を起動し
734
696
  assert.equal(first.stdout.split('big1.txt と big2.txt を読んで').length, 2, '止めたターンの依頼は現在地に1回だけ');
735
697
  assert.doesNotMatch(first.stdout, /宣言|\/clear/);
736
698
  assert.ok(first.stdout.length <= 9_501);
737
- assert.ok(JSON.parse(readFileSync(recordFile, 'utf8')).accepted_at > 0, '届いた指示で受領を記録する');
699
+ const acceptance = JSON.parse(readFileSync(join(handoffDir, `${SESSION}.accepted`), 'utf8'));
700
+ assert.deepEqual([acceptance.handoff_id, acceptance.successor_session_id], [record.handoff_id, SUCCESSOR], '最初の指示が受領を残す');
701
+ assert.ok(acceptance.accepted_at > 0);
738
702
 
739
703
  // 記憶は後継へ合流している(今の /tl の引き継ぎと同じ)
740
704
  const db = new DatabaseSync(join(home, '.throughline', 'throughline.db'));
@@ -759,6 +723,59 @@ test('hook: 自動圧縮を止め、次の道具を止めて worker を起動し
759
723
  assert.deepEqual([merged.triggered_path, merged.injection.auto_handoff_id], ['baton', record.handoff_id]);
760
724
  }));
761
725
 
726
+ test('hook: 別の project へ移した会話(Claude Desktop)を、移った後に1回も Stop を通らないまま引き継いでも、後継へ記憶が入る', () => withDir(async home => {
727
+ // Desktop は「フォルダなし」で始めた会話を project へ移す。SessionStart は移る前の場所で呼ばれ、
728
+ // CLAUDE_PROJECT_DIR は移った後も移る前の場所のまま届く。
729
+ const scratch = join(home, 'scratch-2026-10-05-ac3fa8');
730
+ const project = join(home, 'project');
731
+ mkdirSync(scratch, { recursive: true });
732
+ mkdirSync(project, { recursive: true });
733
+ const transcriptPath = join(home, 'transcript.jsonl');
734
+ const base = Date.parse('2026-10-05T22:38:00Z');
735
+ const at = seconds => new Date(base + seconds * 1000).toISOString();
736
+ const moved = { ...fakeClaudePath(home), CLAUDE_PROJECT_DIR: scratch };
737
+ const hook = (command, payload, cwd = project) =>
738
+ cli(home, [command], JSON.stringify({ session_id: SESSION, cwd, transcript_path: transcriptPath, ...payload }), moved);
739
+
740
+ assert.equal(cli(home, ['auto-handoff', 'enable', '--host', 'claude', '--project', project, '--json']).status, 0);
741
+ assert.equal(hook('session-start', { hook_event_name: 'SessionStart', source: 'startup' }, scratch).status, 0);
742
+ writeFileSync(transcriptPath, jsonl([
743
+ user('14個を順に読んで', at(0)),
744
+ assistant('読み終えました。', at(60)),
745
+ { type: 'relocated', sessionId: SESSION, relocatedCwd: project },
746
+ user('part06 から part09 をもう一度読んで', at(3000)),
747
+ assistant('part06 から読みます。', at(3002)),
748
+ toolUse('toolu_6', 'Read', { file_path: join(project, 'part06.txt') }),
749
+ ]));
750
+
751
+ const pre = hook('pre-compact', { hook_event_name: 'PreCompact', trigger: 'auto' });
752
+ assert.equal(pre.status, 2, pre.stderr);
753
+ const stopped = hook('pre-tool-use', { hook_event_name: 'PreToolUse', tool_name: 'Read', tool_use_id: 'toolu_6', permission_mode: 'bypassPermissions' });
754
+ assert.equal(JSON.parse(stopped.stdout).continue, false);
755
+ const status = () => JSON.parse(cli(home, ['auto-handoff', 'status', '--host', 'claude', '--json']).stdout).handoffs;
756
+ let handoff;
757
+ for (let i = 0; i < 100 && (handoff = status()[0]).state !== 'failed'; i++) await new Promise(r => setTimeout(r, 100));
758
+ assert.equal(handoff.error_code, 'handoff_successor_launch_failed', '偽の claude で止まる。本物は起動しない');
759
+
760
+ // 後継の最初の指示(起動時に渡された継続の指示)
761
+ const recordFile = join(home, '.throughline', 'claude-auto-handoff', `${SESSION}.json`);
762
+ const record = JSON.parse(readFileSync(recordFile, 'utf8'));
763
+ writeFileSync(recordFile, JSON.stringify({ ...record, state: 'launching', error_code: null }));
764
+ const successorPayload = { session_id: SUCCESSOR, cwd: project, hook_event_name: 'SessionStart', source: 'startup' };
765
+ assert.equal(cli(home, ['session-start'], JSON.stringify(successorPayload), fakeClaudePath(home)).status, 0);
766
+ const first = cli(home, ['prompt-submit'], JSON.stringify({ ...successorPayload, hook_event_name: 'UserPromptSubmit',
767
+ prompt: claudeContinuationInput(record) }), fakeClaudePath(home));
768
+ assert.equal(first.status, 0, first.stderr);
769
+ assert.match(first.stdout, /^## Throughline: 自動継続の文脈\n/);
770
+ assert.match(first.stdout, /\*\*作業中のユーザー依頼\*\* \[\d\d:\d\d:\d\d\]: part06 から part09 をもう一度読んで\n/);
771
+ assert.match(first.stdout, /\*\*止める直前に呼ぼうとして、実行されなかった道具\*\*: Read .*part06\.txt\n/);
772
+
773
+ const db = new DatabaseSync(join(home, '.throughline', 'throughline.db'));
774
+ assert.equal(db.prepare('SELECT merged_into FROM sessions WHERE session_id = ?').get(SESSION).merged_into, SUCCESSOR);
775
+ assert.equal(db.prepare('SELECT project_path FROM sessions WHERE session_id = ?').get(SESSION).project_path, project);
776
+ db.close();
777
+ }));
778
+
762
779
  test('hook: 自動継続が無効な時、自動圧縮を止めず、何も残さない', () => withDir(home => {
763
780
  const project = join(home, 'project');
764
781
  mkdirSync(project, { recursive: true });
@@ -24,9 +24,8 @@
24
24
  *
25
25
  * 【自動継続の後継】 ADR 0033
26
26
  *
27
- * 同じ project で後継の立ち上げ中の引き継ぎがある時だけ、この会話の受け口(inbox socket)を
28
- * 控える。worker がそれを読んで、継続の指示を1通送る。記憶の注入は、その指示が届いた時の
29
- * UserPromptSubmit(上の二相ハンドオフの第二相)が行う。
27
+ * 後継は、継続の指示を最初の指示として付けて起動される。SessionStart では何もしない。
28
+ * 記憶の注入と受領は、その指示の UserPromptSubmit(上の二相ハンドオフの第二相)が行う。
30
29
  */
31
30
 
32
31
  import { getDb } from './db.mjs';
@@ -41,7 +40,6 @@ import { recordRuntimeErrorBestEffort } from './runtime-error-store.mjs';
41
40
  import { logHookFailure } from './hook-failure-log.mjs';
42
41
  import { CLAUDE_HOST, hostAdapterForSessionId, hostOfSessionId, NON_CLAUDE_SESSION_PREFIXES, parseHookPayload } from './hosts/index.mjs';
43
42
  import { executeFirstPromptHandoff } from './handoff-executor.mjs';
44
- import { recordClaudeSuccessorTarget } from './claude-auto-handoff.mjs';
45
43
 
46
44
  const ENV_DISABLE_AUTO_HANDOFF = 'THROUGHLINE_DISABLE_AUTO_HANDOFF';
47
45
 
@@ -170,11 +168,6 @@ export async function run() {
170
168
  pending_registered: true,
171
169
  });
172
170
 
173
- // 自動継続の後継として立ち上がった会話なら、worker が指示を送れるように受け口を控える (ADR 0033)。
174
- if (hostOfSessionId(session_id) === CLAUDE_HOST) {
175
- recordClaudeSuccessorTarget({ payload, env: process.env, now });
176
- }
177
-
178
171
  // Cursor は beforeSubmitPrompt が additional_context を持たない。
179
172
  // 新規 composer 会話の sessionStart が公式の注入口なので、ここで第二相を実行する。
180
173
  // Claude の幽霊 SessionStart 問題はこの host では sessionStart = 会話作成のため適用しない。