throughline 0.15.2 → 0.15.3

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,29 @@ shipped to npm but were not individually tagged on GitHub.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.15.3] — 2026-10-06
14
+
15
+ ### 修正
16
+
17
+ - Claude Codeの自動継続(`auto-handoff enable --host claude`)で、旧い会話が権限のバイパス(`bypassPermissions`)の時、後継が継続の指示を受け取らずに止まる不具合を直す。後継は旧い会話の権限を引き継ぐ。Claude Codeは、バイパス中の会話へ別の会話やprocessから届いた文を、送り手が権限のmodeを名乗らない限り利用者の承認まで止める(画面には`Held peer message`と出る)。0.15.2までは、後継を立てた後で受け口へ指示を送っていたので、ここで止まり、記録は`unknown`・`handoff_delivery_timeout`になっていた。バイパス以外の権限では起きない。
18
+ - 継続の指示は、後継を立てる時の最初の指示として渡す(`claude --bg … "<指示>"`)。立てた後で外から送らない。後継の受信の設定(`crossSessionInbound`)は変えない([ADR 0033](docs/adr/0033-claude-auto-handoff-new-session.md)の4と5を書き換え)。
19
+ - 受領は、後継の最初の指示が`~/.throughline/claude-auto-handoff/<旧会話のsession_id>.accepted`に残し、workerがそれを待って`sent`にする。最初の指示は、workerが後継のIDを記録へ写す前に届くことがあるので、その間は指示が運ぶ引き継ぎIDで後継と認める。期限(60秒)までに残らなければ`unknown`・`handoff_delivery_unconfirmed`にし、後継は立て直さない。`handoff_successor_target_unavailable`と`handoff_delivery_timeout`は出なくなる。
20
+ - 継続の指示の文に、「実行されなかった道具」はまだ実行されていないこと、最初にそれを呼び出すことを書き足す。指示が利用者の発言として届くようになり、Haiku 4.5の後継が、止められた道具をやり直さずに「読みました」と書いて先へ進んだ回があった(macOS、1回)。
21
+ - 後継の`SessionStart`は受け口を控えなくなる。Codexの自動継続は変えない。
22
+
23
+ ### 確認した範囲
24
+
25
+ - macOS、Claude Desktop(同梱の2.1.286、権限はバイパス、0.15.2)。作業フォルダを移した会話で、圧縮を止める・旧い会話を止める・後継を立てる、の3段がDesktopの画面から送った指示で通り、4段目が上の理由で止まることを確かめた。
26
+ - macOS、端末の会話(Claude Code 2.1.289、Haiku 4.5)。この版で、バイパスの会話は4回、編集の自動許可(`acceptEdits`)の会話も4回、連続で引き継いで14個を読み切り完了。どの引き継ぎも`sent`で、承認待ちは出ない。指示の文を書き足す前の版では、バイパスで2回動かし、1回は完了、1回は上の「読みました」で未完了。
27
+ - Windows 11、端末の会話(2.1.289、Haiku 4.5、`acceptEdits`)。この版で4回連続で引き継いで完了。最初の指示(改行と日本語を含む)は、そのまま後継のhookへ届く。
28
+
29
+ ### 確認していない範囲
30
+
31
+ - Claude Desktopの画面で、この版が最後まで通ること(後継が指示を受け取って作業を終える所)。
32
+ - Linuxで実物のClaude Codeを動かした通し。単体と結合の試験だけ。
33
+ - Windowsのバイパスの会話、Opus・Fableの後継。
34
+
35
+
13
36
  ## [0.15.2] — 2026-10-06
14
37
 
15
38
  ### 修正
@@ -1790,7 +1813,8 @@ two attempts, instrument first instead of patching again.
1790
1813
 
1791
1814
  ---
1792
1815
 
1793
- [Unreleased]: https://github.com/kitepon/Throughline/compare/v0.15.2...HEAD
1816
+ [Unreleased]: https://github.com/kitepon/Throughline/compare/v0.15.3...HEAD
1817
+ [0.15.3]: https://github.com/kitepon/Throughline/compare/v0.15.2...v0.15.3
1794
1818
  [0.15.2]: https://github.com/kitepon/Throughline/compare/v0.15.1...v0.15.2
1795
1819
  [0.15.1]: https://github.com/kitepon/Throughline/compare/v0.15.0...v0.15.1
1796
1820
  [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` を一緒に返すと実行されない。
@@ -40,7 +40,8 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
40
40
  実行させずに止める。旧い会話は止めるだけで、空にしない。同じ応答に並んだ道具も全て止め、後継の立ち上げは1回だけ行う。
41
41
  記録が無い会話では、記録のファイルの有無だけを見て終わる。subagent の中の道具は止めない。
42
42
  3. **新しい会話を立てる**: 切り離した worker が、止めた時点の依頼・モデル・推論強度・権限を記録へ写し、
43
- 同じ project で `claude --bg` を指示なしで起動する。起動時に `--model`・`--effort`・`--permission-mode` を渡し、
43
+ 同じ project で `claude --bg` を、継続の指示を最初の指示として付けて起動する(0.15.3。下の4)。
44
+ 起動時に `--model`・`--effort`・`--permission-mode` を渡し、
44
45
  `--settings '{"worktree":{"bgIsolation":"none"}}'` で同じ作業ツリーを編集させる。
45
46
  依頼と直前の発言は、止めた道具の呼び出しが transcript に書かれるのを待ってから読む(hook の時点では直前の発言が
46
47
  まだ書かれていないことがある)。
@@ -48,10 +49,14 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
48
49
  bodies の本文にし、道具の入出力は transcript の末尾(止めた道具の呼び出し)まで details に入れる。
49
50
  完了したターンは最後の本文だけを残すが、止めたターンには結論の発言が無いので、全部を残す。
50
51
  取り込めなくても引き継ぎは止めない。理由は 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 を消費して前任を合流させ、記憶を注入する。
52
+ 4. **継続の指示を1通渡す**: 継続の指示は、後継を起動する時の最初の指示として渡す(0.15.3、オーナーの判断 2026-10-06)。
53
+ 立てた後で外から送らない。Claude Code は、権限のバイパス中の会話へ届いた文を、送り手が権限の mode を名乗らない限り
54
+ 利用者の承認まで止める(cross-session messaging の決まり。画面には `Held peer message` と出る)。
55
+ 後継は旧い会話の権限を引き継ぐので、旧い会話がバイパスだと、0.15.2 までの配送(後継の受け口へ `sendClaudeInbox` で送る)は
56
+ 承認待ちで止まり、引き継ぎが進まなかった。後継の設定で受信を緩める方法(`crossSessionInbound: accept`)は採らない。
57
+ バイパス中の後継が、他の会話からの文も確認なしで受け取るようになるため。
58
+ `claude` は stdin も指示に足すので、起動時に stdin は渡さない。
59
+ その指示の `UserPromptSubmit` が baton を消費して前任を合流させ、記憶を注入する。
55
60
  注入は ADR 0016 と同じ予算(9,500 字)で、ヘッダに作業ディレクトリ、現在地、案内、直近の L2 の順に載せる。
56
61
  宣言文は求めない。現在地は止めたターンで、次の順に載せる(0.14.1)。
57
62
  - 止めた時点の依頼(3,500 字まで)。
@@ -61,9 +66,11 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
61
66
  - 止める直前に呼ぼうとして、実行されなかった道具。圧縮を止めた後の応答が呼んだ道具は、どれも実行されていない。
62
67
  hook は並んで走るので、同じ応答(`message.id`)の道具をまとめて扱う。
63
68
  止めたターンは現在地にだけ載せ、L2 の一覧には重ねない。そのターンの道具の入出力は `throughline detail` で取り出せる。
64
- 5. **受領**: 継続の指示は引き継ぎ ID を含む。後継の最初の指示がその ID を含む時だけ、受領を記録する。
65
- `sendClaudeInbox` の結果が `accepted` なら `sent`、`not_sent` なら `failed`、`unknown` なら `unknown` にする。
66
- 結果が不明な時は再送しない。後継が作業を進めたことまでは確かめない(オーナーの判断: 不要)。
69
+ 5. **受領**: 継続の指示は引き継ぎ ID を含む。後継の最初の指示がその ID を含む時だけ、受領を残す
70
+ (`<旧会話の session_id>.accepted`。記録は worker だけが書き換える)。最初の指示は、worker が後継の ID を記録へ写す前に
71
+ 届くことがあるので、その間は指示が運ぶ引き継ぎ ID で後継と認める。worker は受領を待ち、残れば `sent`、
72
+ 期限(60秒)までに残らなければ `unknown`(`handoff_delivery_unconfirmed`)にする。
73
+ 受領を確かめられない時も、後継を立て直さない。後継が作業を進めたことまでは確かめない(オーナーの判断: 不要)。
67
74
  6. **連続の引き継ぎ**: 後継も同じ hook で止まり、次の後継へ引き継ぐ。後継の最後の user 発言は前の引き継ぎの
68
75
  継続の指示なので、現在地には前の引き継ぎが運んだ元の依頼を引き続き載せる。
69
76
  7. **道具を呼ばずに終わったターン**: 圧縮を止めた後、モデルが道具を呼ばずにターンを終えたら、Stop hook が記録を取り下げる。
@@ -108,4 +115,8 @@ Claude Desktop の新しい会話は、画面を開いただけでは process
108
115
  - Windows 11。端末の会話(2.1.289)から始めた。0.14.2 で、Haiku 4.5 は4回、連続で引き継いで完了した。
109
116
  0.14.1 までは、印(baton)に残す project の場所が `C:/…` の形で、後継が `C:\…` の形で探して見つけられなかった。
110
117
  印と記録に残す場所は、その OS の書き方にそろえる(0.14.2)。
111
- - Claude Desktop の画面から始めた会話、Fable、subagent が動いている最中の引き継ぎは確かめていない。
118
+ - Claude Desktop の画面から送った指示(同梱の 2.1.286、権限はバイパス、作業フォルダを移した会話、0.15.2)。圧縮を止める・
119
+ 旧い会話を止める・後継を立てる、の3段は通った。継続の指示は、バイパス中の後継が承認待ちで止めた(0.15.3 で渡し方を変えた理由)。
120
+ - 0.15.3(継続の指示を最初の指示として渡す)。macOS の端末の会話(2.1.289、Haiku 4.5)で、バイパスは4回、`acceptEdits` も4回、
121
+ 連続で引き継いで完了。Windows 11 の端末の会話(`acceptEdits`)でも4回連続で引き継いで完了した。
122
+ - 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.3",
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,21 +8,21 @@
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
28
  import { claudeHostAdapter } from './hosts/claude.mjs';
@@ -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; }
@@ -476,44 +479,12 @@ export function completeClaudeTurnWithoutHandoff({ sessionId, dir = claudeAutoHa
476
479
 
477
480
  /** 後継へ送る継続の指示。引き継ぎIDを含め、後継の最初の指示がこの配送のものかを照合できるようにする。 */
478
481
  export function claudeContinuationInput(record) {
482
+ // この文は後継の最初の指示(利用者の発言)として届く。止めた道具をやり直さずに「済んだ」と書いて
483
+ // 先へ進む後継が出たので(Haiku 4.5、macOS で実測)、実行されていない道具から始めることを明記する。
479
484
  return `Throughline自動継続 ${record.handoff_id}\n` +
480
485
  '注入された記憶と元のユーザー依頼に従い、未完了の作業をそのまま継続してください。' +
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;
486
+ '記憶の「実行されなかった道具」は、まだ実行されていません。最初にそれを実際に呼び出してから、先へ進んでください。' +
487
+ '「ここまでにしたこと」に載っている完了済みの操作は、重複実行しないでください。';
517
488
  }
518
489
 
519
490
  /**
@@ -526,15 +497,26 @@ export function acceptClaudeAutoContinuation({ predecessorId, successorSessionId
526
497
  dir = claudeAutoHandoffDir(), now = Date.now() }) {
527
498
  if (!validSessionId(predecessorId) || typeof successorSessionId !== 'string') return null;
528
499
  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 });
500
+ if (!record || !ACCEPTABLE_STATES.has(record.state)) return null;
501
+ const carriesInstruction = typeof prompt === 'string' && prompt.includes(`Throughline自動継続 ${record.handoff_id}`);
502
+ // 後継の ID が記録に入っていれば ID で、まだなら指示が運ぶ引き継ぎ ID で、後継と認める。
503
+ const isSuccessor = record.successor?.short_id
504
+ ? successorSessionId.startsWith(record.successor.short_id)
505
+ : carriesInstruction;
506
+ if (!isSuccessor) return null;
507
+ if (carriesInstruction && !record.accepted_at && !existsSync(acceptancePath(predecessorId, dir))) {
508
+ writeJsonPrivate(acceptancePath(predecessorId, dir),
509
+ { handoff_id: record.handoff_id, successor_session_id: successorSessionId, accepted_at: now });
533
510
  }
534
511
  return { handoffId: record.handoff_id, projectPath: record.project_path, inFlight: record.in_flight ?? null,
535
512
  transcriptPath: record.transcript_path ?? null };
536
513
  }
537
514
 
515
+ function readAcceptance(sessionId, handoffId, dir) {
516
+ const acceptance = readJson(acceptancePath(sessionId, dir));
517
+ return acceptance?.handoff_id === handoffId && typeof acceptance.accepted_at === 'number' ? acceptance : null;
518
+ }
519
+
538
520
  function successorArgs(record) {
539
521
  const args = ['--bg', '--name', `tl-${basename(record.project_path)}-${record.handoff_id.slice(0, 8)}`];
540
522
  const { model, effort, permission_mode: permissionMode } = record.settings ?? {};
@@ -543,6 +525,9 @@ function successorArgs(record) {
543
525
  if (permissionMode) args.push('--permission-mode', permissionMode);
544
526
  // 後継は旧い会話の続きなので、同じ作業ツリーを編集する。別の worktree へ移さない。
545
527
  args.push('--settings', JSON.stringify({ worktree: { bgIsolation: 'none' } }));
528
+ // 継続の指示は、起動時の最初の指示として渡す。立てた後で外から送ると、権限のバイパス中の後継は
529
+ // その文を利用者の承認まで止める(Claude Code の cross-session messaging の決まり)。
530
+ args.push(claudeContinuationInput(record));
546
531
  return args;
547
532
  }
548
533
 
@@ -553,17 +538,16 @@ function successorEnv(env) {
553
538
  }
554
539
 
555
540
  /**
556
- * 後継を立てて、継続の指示を1通送る。失敗は固定の理由を記録して止まる。送信の結果が不明な時は再送しない。
541
+ * 継続の指示を付けて後継を立て、後継の最初の指示が受領を残すのを待つ。失敗は固定の理由を記録して止まる。
542
+ * 受領を確かめられない時も、後継を立て直さない(同じ指示を持った会話を2つ作らない)。
557
543
  */
558
544
  export async function runClaudeAutoHandoffWorker(sessionId, {
559
545
  dir = claudeAutoHandoffDir(),
560
546
  env = process.env,
561
547
  spawn = spawnPortableSync,
562
- send = sendClaudeInbox,
563
548
  openDb = null,
564
549
  transcriptTimeoutMs = 5_000,
565
- targetTimeoutMs = 30_000,
566
- sendTimeoutMs = 30_000,
550
+ acceptTimeoutMs = 60_000,
567
551
  pollMs = 200,
568
552
  } = {}) {
569
553
  let record = readClaudeAutoHandoff(sessionId, dir);
@@ -573,7 +557,8 @@ export async function runClaudeAutoHandoffWorker(sessionId, {
573
557
  const fail = code => update({ state: 'failed', error_code: code });
574
558
 
575
559
  // 止めた時点の依頼・ここまでにしたこと・その時のモデルを写し、止めたターンを DB へ取り込む。
576
- // 後継の最初の指示が、これを現在地として受け取る。
560
+ // 後継の最初の指示が、これを現在地として受け取る。前の引き継ぎの受領が残っていれば消す。
561
+ rmSync(acceptancePath(sessionId, dir), { force: true });
577
562
  await waitForStoppedToolUse(record, { timeoutMs: transcriptTimeoutMs, pollMs });
578
563
  const inFlight = record.transcript_path ? snapshotInFlight(record, dir) : null;
579
564
  if (inFlight && openDb) inFlight.turn = captureStoppedTurn(record, openDb);
@@ -597,31 +582,15 @@ export async function runClaudeAutoHandoffWorker(sessionId, {
597
582
  }
598
583
  update({ state: 'launched', successor: { short_id: shortId, session_id: null } });
599
584
 
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);
585
+ // 指示は起動時に渡してある。後継の最初の UserPromptSubmit が受領を残すのを待つ。
586
+ for (const deadline = Date.now() + acceptTimeoutMs; Date.now() < deadline;) {
587
+ const acceptance = readAcceptance(sessionId, record.handoff_id, dir);
588
+ if (acceptance) {
589
+ rmSync(acceptancePath(sessionId, dir), { force: true });
590
+ return update({ state: 'sent', error_code: null, accepted_at: acceptance.accepted_at,
591
+ successor: { short_id: shortId, session_id: acceptance.successor_session_id } });
592
+ }
593
+ await delay(pollMs);
604
594
  }
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}` });
595
+ return update({ state: 'unknown', error_code: 'handoff_delivery_unconfirmed' });
627
596
  }
@@ -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,
@@ -243,64 +242,48 @@ test('Stop: 圧縮を止めた後、道具を呼ばずにターンが終わっ
243
242
  assert.equal(readClaudeAutoHandoff(SESSION, dir).state, 'stopped');
244
243
  }));
245
244
 
246
- /** 止めた直後の記録を作り、後継の SessionStart と配送を差し替えて worker を走らせる。 */
247
- async function runWorker(dir, { spawn, send, onLaunched }) {
245
+ /** 止めた直後の記録を作り、後継の起動を差し替えて worker を走らせる。 */
246
+ async function runWorker(dir, { spawn, onLaunched }) {
248
247
  request(dir);
249
248
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app', permission_mode: 'acceptEdits',
250
249
  effort: { level: 'high' } }, dir, launchWorker: async () => {} });
251
- const calls = { spawn: [], send: [] };
250
+ const calls = { spawn: [] };
252
251
  const record = await runClaudeAutoHandoffWorker(SESSION, {
253
252
  dir, env: { PATH: '/bin', CLAUDECODE: '1', CLAUDE_CODE_ENTRYPOINT: 'claude-desktop', CLAUDE_CODE_MESSAGING_SOCKET: '/old.sock',
254
253
  CLAUDE_CODE_MESSAGING_TOKEN: 'old-token', CLAUDE_PROJECT_DIR: '/work/app', CLAUDE_CODE_USE_BEDROCK: '1' },
255
- targetTimeoutMs: 300, sendTimeoutMs: 300, pollMs: 10,
254
+ acceptTimeoutMs: 300, pollMs: 10,
256
255
  spawn: (command, args, options) => {
257
256
  calls.spawn.push({ command, args, options });
258
257
  const result = spawn(command, args, options);
259
- if (result.status === 0) onLaunched?.();
258
+ if (result.status === 0) onLaunched?.(args);
260
259
  return result;
261
260
  },
262
- send: async (target, text, options) => { calls.send.push({ target, text }); return send(target, text, options); },
263
261
  });
264
262
  return { record, calls };
265
263
  }
266
264
 
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
- });
265
+ const launchedOk = () => ({ status: 0, stdout: 'Starting background service…\nbackgrounded · a41a97ae · tl-app-1234\n', stderr: '' });
266
+ // 後継の最初の UserPromptSubmit。起動時に渡された指示で、受領を残す。worker が後継の ID を記録へ写す前に届く。
267
+ const successorStarts = (dir, predecessorId = SESSION) => args => acceptClaudeAutoContinuation({
268
+ predecessorId, successorSessionId: SUCCESSOR, prompt: args.at(-1), dir, now: 5_000 });
269
+
270
+ test('worker: 継続の指示を最初の指示として付けて後継を同じprojectに立て、後継の受領を待つ', () => withDir(async dir => {
271
+ const { record, calls } = await runWorker(dir, { spawn: launchedOk, onLaunched: successorStarts(dir) });
285
272
  assert.equal(calls.spawn.length, 1);
286
273
  const { command, args, options } = calls.spawn[0];
287
274
  assert.equal(command, 'claude');
288
275
  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 が無いので付かない');
276
+ '--permission-mode', 'acceptEdits', '--settings', '{"worktree":{"bgIsolation":"none"}}', claudeContinuationInput(record)],
277
+ '指示は起動時に渡す(外から送ると、権限のバイパス中の後継が承認まで止める)。モデルは transcript が無いので付かない');
278
+ assert.match(args.at(-1), new RegExp(`^Throughline自動継続 ${record.handoff_id}\\n注入された記憶と元のユーザー依頼に従い、未完了の作業をそのまま継続してください。`));
291
279
  assert.equal(options.cwd, '/work/app');
292
280
  assert.deepEqual(options.env, { PATH: '/bin', CLAUDE_CODE_USE_BEDROCK: '1' }, '会話ごとの環境変数は後継へ渡さない');
281
+ assert.deepEqual(options.stdio, ['ignore', 'pipe', 'pipe'], 'stdin を渡さない(claude は stdin も指示に足す)');
293
282
 
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]);
283
+ assert.deepEqual([record.state, record.error_code, record.accepted_at], ['sent', null, 5_000]);
300
284
  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 は記録に残さない');
285
+ assert.equal(existsSync(join(dir, `${SESSION}.accepted`)), false, '受領の控えは読んだら消す');
286
+ assert.equal(existsSync(join(dir, 'targets')), false, '受け口は控えない');
304
287
 
305
288
  // 引き継ぎ済みの会話の道具は、後継を案内して止める
306
289
  const output = await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app' }, dir,
@@ -309,9 +292,8 @@ test('worker: 指示を待つ後継を同じprojectに立て、後継の受け
309
292
  }));
310
293
 
311
294
  test('worker: 止めた時点の依頼とモデルを transcript から写し、色付きの出力からも後継のIDを読む。後継が止められた時は元の依頼を運ぶ', () => withDir(async dir => {
312
- const sendOk = async () => ({ status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' });
313
295
  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' });
296
+ stdout: 'backgrounded · \u001b[36ma41a97ae\u001b[39m · tl-app-1234\u001b[2m\u001b[22m\n' });
315
297
  const run = async (sessionId, transcriptPath, toolUseId) => {
316
298
  const db = makeBatonDb();
317
299
  requestClaudeAutoHandoff({ payload: { session_id: sessionId, trigger: 'auto', cwd: '/work/app', transcript_path: transcriptPath },
@@ -319,13 +301,12 @@ test('worker: 止めた時点の依頼とモデルを transcript から写し、
319
301
  await stopClaudeTurnForHandoff({ payload: { session_id: sessionId, cwd: '/work/app', transcript_path: transcriptPath,
320
302
  tool_use_id: toolUseId }, dir, launchWorker: async () => {} });
321
303
  const calls = [];
322
- const record = await runClaudeAutoHandoffWorker(sessionId, { dir, env: {}, send: sendOk, pollMs: 10, targetTimeoutMs: 300,
304
+ const record = await runClaudeAutoHandoffWorker(sessionId, { dir, env: {}, pollMs: 10, acceptTimeoutMs: 300,
323
305
  transcriptTimeoutMs: 300,
324
306
  spawn: (command, args) => {
325
307
  calls.push(args);
326
308
  // 止めた道具の呼び出しは、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 });
309
+ successorStarts(dir, sessionId)(args);
329
310
  return colored();
330
311
  } });
331
312
  return { record, calls };
@@ -364,12 +345,10 @@ test('worker: 止めた時点の依頼とモデルを transcript から写し、
364
345
  // 後継 B が止められた時、最後の user 発言は A からの継続の指示。現在地には元の依頼を運ぶ
365
346
  const transcriptB = join(dir, 'b.jsonl');
366
347
  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'),
348
+ user(claudeContinuationInput(first.record), '2026-10-04T03:01:00Z'),
369
349
  assistant('part09 を読みました。次に part10 を読みます。', '2026-10-04T03:01:20Z', 'claude-opus-5'),
370
350
  { type: 'assistant', message: { role: 'assistant', model: 'claude-opus-5', content: [{ type: 'tool_use', id: 'toolu_10', name: 'Read', input: {} }] } },
371
351
  ]));
372
- rmSync(join(dir, 'targets'), { recursive: true, force: true });
373
352
  const second = await run(SUCCESSOR, transcriptB, 'toolu_10');
374
353
  assert.deepEqual(second.record.in_flight, {
375
354
  user: { content: '14個のファイルを順に読んで', timestamp: Date.parse('2026-10-04T03:00:10Z') },
@@ -428,13 +407,11 @@ test('worker: 止めたターンを DB へ取り込み、ここまでにした
428
407
  // hook は並んで走る。記録に残る止めた道具は、応答の中の2つ目のこともある
429
408
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app', transcript_path: transcript, tool_use_id: 't5' },
430
409
  dir, launchWorker: async () => {} });
431
- const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, targetTimeoutMs: 300, transcriptTimeoutMs: 300,
410
+ const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, acceptTimeoutMs: 300, transcriptTimeoutMs: 300,
432
411
  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' };
412
+ spawn: (command, args) => {
413
+ successorStarts(dir)(args);
414
+ return { status: 0, stderr: '', stdout: 'backgrounded · a41a97ae · tl-app\n' };
438
415
  } });
439
416
  assert.equal(record.state, 'sent');
440
417
  assert.deepEqual(record.in_flight.steps, [
@@ -474,13 +451,11 @@ test('worker: 止めたターンを取り込めなくても後継を立て、取
474
451
  env: {}, config: ENABLED, openDb: () => db, dir, platform: 'linux' });
475
452
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app', transcript_path: transcript, tool_use_id: 'toolu_1' },
476
453
  dir, launchWorker: async () => {} });
477
- const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, targetTimeoutMs: 300, transcriptTimeoutMs: 300,
454
+ const record = await runClaudeAutoHandoffWorker(SESSION, { dir, env: {}, pollMs: 10, acceptTimeoutMs: 300, transcriptTimeoutMs: 300,
478
455
  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' };
456
+ spawn: (command, args) => {
457
+ successorStarts(dir)(args);
458
+ return { status: 0, stderr: '', stdout: 'backgrounded · a41a97ae · tl-app\n' };
484
459
  } });
485
460
  assert.equal(record.state, 'sent');
486
461
  assert.equal(record.in_flight.turn, null);
@@ -488,23 +463,19 @@ test('worker: 止めたターンを取り込めなくても後継を立て、取
488
463
  assert.equal(publicClaudeAutoHandoff(record).in_flight_captured, false);
489
464
  }));
490
465
 
491
- test('worker: 立ち上げ・受け口・配送の失敗は固定の理由を残し、結果が不明な配送は再送しない', () => withDir(async dir => {
492
- const sendOk = async () => ({ status: 'accepted', outcome_unknown: false, reason: 'receiver_confirmed' });
466
+ test('worker: 立ち上げの失敗は固定の理由を残し、受領を確かめられない時は後継を立て直さない', () => withDir(async dir => {
493
467
  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],
468
+ [{ spawn: () => ({ error: Object.assign(new Error('not found'), { code: 'ENOENT' }) }) }, 'failed', 'handoff_claude_cli_unavailable'],
469
+ [{ spawn: () => ({ status: 1, stdout: '', stderr: 'Workspace not trusted' }) }, 'failed', 'handoff_successor_launch_failed'],
470
+ [{ spawn: () => ({ status: 0, stdout: 'unexpected output', stderr: '' }) }, 'failed', 'handoff_successor_launch_failed'],
471
+ // 後継は立ったが、最初の指示の受領が期限までに残らない
472
+ [{ spawn: launchedOk }, 'unknown', 'handoff_delivery_unconfirmed'],
502
473
  ];
503
- for (const [deps, state, code, sends] of cases) {
474
+ for (const [deps, state, code] of cases) {
504
475
  rmSync(join(dir, `${SESSION}.json`), { force: true });
505
476
  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);
477
+ const { record } = await runWorker(dir, deps);
478
+ assert.deepEqual([record.state, record.error_code], [state, code], code);
508
479
  }
509
480
  // 結果が不明な引き継ぎは、次の道具でも立ち上げ直さない
510
481
  const launched = [];
@@ -513,52 +484,42 @@ test('worker: 立ち上げ・受け口・配送の失敗は固定の理由を残
513
484
  assert.equal((await runClaudeAutoHandoffWorker(SESSION, { dir, spawn: () => { throw new Error('must not spawn'); } })).state, 'unknown');
514
485
  }));
515
486
 
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 => {
487
+ test('最初の指示: 後継だけが止めた時点の依頼を受け取り、この引き継ぎの指示だけが受領になる', () => withDir(async dir => {
545
488
  request(dir);
546
489
  await stopClaudeTurnForHandoff({ payload: { session_id: SESSION, cwd: '/work/app' }, dir, launchWorker: async () => {} });
547
490
  const accept = (overrides = {}) => acceptClaudeAutoContinuation({ predecessorId: SESSION, successorSessionId: SUCCESSOR, dir, ...overrides });
548
- assert.equal(accept(), null, '後継がまだ立っていない');
491
+ const acceptance = () => existsSync(join(dir, `${SESSION}.accepted`))
492
+ ? JSON.parse(readFileSync(join(dir, `${SESSION}.accepted`), 'utf8')) : null;
549
493
  const record = readClaudeAutoHandoff(SESSION, dir);
494
+ const instruction = claudeContinuationInput(record);
495
+ assert.equal(accept({ prompt: instruction }), null, '後継をまだ立てていない(stopped)');
550
496
  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, '後継ではない会話');
497
+ const expected = { handoffId: record.handoff_id, projectPath: '/work/app', inFlight, transcriptPath: null };
498
+ const write = fields => writeFileSync(join(dir, `${SESSION}.json`), JSON.stringify({ ...record, in_flight: inFlight, ...fields }));
499
+
500
+ // 立ち上げ中(後継の ID はまだ記録に無い): 指示が運ぶ引き継ぎ ID で後継と認める
501
+ write({ state: 'launching' });
502
+ assert.equal(accept(), null, '指示を持たない会話');
503
+ assert.equal(accept({ prompt: '別の指示' }), null, '同じ project で人が始めた別の会話');
504
+ assert.equal(accept({ prompt: 'Throughline自動継続 00000000-0000-4000-8000-000000000000\n…' }), null, '別の引き継ぎの指示');
505
+ assert.equal(acceptance(), null);
506
+ assert.deepEqual(accept({ prompt: instruction, now: 9_000 }), expected);
507
+ assert.deepEqual(acceptance(), { handoff_id: record.handoff_id, successor_session_id: SUCCESSOR, accepted_at: 9_000 });
508
+ assert.equal(readClaudeAutoHandoff(SESSION, dir).accepted_at, null, '記録は worker だけが書き換える');
509
+ accept({ prompt: instruction, now: 9_999 });
510
+ assert.equal(acceptance().accepted_at, 9_000, '受領は1回だけ残す');
511
+ rmSync(join(dir, `${SESSION}.accepted`));
512
+
513
+ // 後継の ID が記録に入った後: ID で後継と認める
514
+ write({ state: 'launched', successor: { short_id: 'a41a97ae', session_id: null } });
515
+ assert.equal(accept({ successorSessionId: 'bbbbbbbb-0000-4000-8000-000000000001', prompt: instruction }), null, '後継ではない会話');
554
516
  assert.equal(accept({ predecessorId: 'aaaaaaaa-0000-4000-8000-000000000009' }), null);
555
517
  assert.equal(accept({ predecessorId: `codex:${SESSION}` }), null);
556
-
557
518
  // 人が先に別の指示を打った時は、依頼は渡すが受領にはしない
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);
519
+ assert.deepEqual(accept({ prompt: '別の指示' }), expected);
520
+ assert.equal(acceptance(), null);
521
+ accept({ prompt: instruction, now: 9_500 });
522
+ assert.equal(acceptance().accepted_at, 9_500);
562
523
  }));
563
524
 
564
525
  test('公開CLI: --host claude は enable・disable・status・worker を受け取る', () => {
@@ -710,19 +671,14 @@ test('hook: 自動圧縮を止め、次の道具を止めて worker を起動し
710
671
  assert.equal(handoff.in_flight_captured, true);
711
672
  assert.equal(record.in_flight.turn.origin_session_id, SESSION);
712
673
  assert.equal(record.in_flight.turn.details, 3);
674
+ // 後継の最初の指示は、worker が後継の ID を記録へ写す前(launching)に届くことがある
713
675
  writeFileSync(recordFile, JSON.stringify({ ...record, state: 'launching', error_code: null }));
714
676
  const started = hook('session-start', { hook_event_name: 'SessionStart', source: 'startup' }, SUCCESSOR);
715
677
  assert.equal(started.status, 0, started.stderr);
716
678
  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)}`;
679
+ assert.equal(existsSync(join(handoffDir, 'targets')), false, '受け口は控えない');
680
+
681
+ const prompt = claudeContinuationInput(record);
726
682
  const first = cli(home, ['prompt-submit'], JSON.stringify({ session_id: SUCCESSOR, cwd: project, hook_event_name: 'UserPromptSubmit', prompt }), extra);
727
683
  assert.equal(first.status, 0, first.stderr);
728
684
  assert.match(first.stdout, /^## Throughline: 自動継続の文脈\n/);
@@ -734,7 +690,9 @@ test('hook: 自動圧縮を止め、次の道具を止めて worker を起動し
734
690
  assert.equal(first.stdout.split('big1.txt と big2.txt を読んで').length, 2, '止めたターンの依頼は現在地に1回だけ');
735
691
  assert.doesNotMatch(first.stdout, /宣言|\/clear/);
736
692
  assert.ok(first.stdout.length <= 9_501);
737
- assert.ok(JSON.parse(readFileSync(recordFile, 'utf8')).accepted_at > 0, '届いた指示で受領を記録する');
693
+ const acceptance = JSON.parse(readFileSync(join(handoffDir, `${SESSION}.accepted`), 'utf8'));
694
+ assert.deepEqual([acceptance.handoff_id, acceptance.successor_session_id], [record.handoff_id, SUCCESSOR], '最初の指示が受領を残す');
695
+ assert.ok(acceptance.accepted_at > 0);
738
696
 
739
697
  // 記憶は後継へ合流している(今の /tl の引き継ぎと同じ)
740
698
  const db = new DatabaseSync(join(home, '.throughline', 'throughline.db'));
@@ -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 = 会話作成のため適用しない。