@christang/keel 5.161.0 → 5.162.0

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.161.0",
3
+ "version": "5.162.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.161.0 -->
1
+ <!-- keel:start version=5.162.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.161.0",
3
+ "version": "5.162.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.161.0",
9
+ "version": "5.162.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.161.0",
5
+ "version": "5.162.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.161.0",
3
+ "version": "5.162.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.161.0",
3
+ "version": "5.162.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.161.0"
53
- PROTOCOL_VERSION = "5.161.0"
52
+ PACKAGE_VERSION = "5.162.0"
53
+ PROTOCOL_VERSION = "5.162.0"
54
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8077,49 +8077,84 @@ def validate_shift_start_desktop_scenario() -> int:
8077
8077
 
8078
8078
 
8079
8079
  def validate_shift_cli_self_shift_scenario() -> int:
8080
- """Issue #357 on the CLI (owner, 2026-10-19): stop the old session, start a new one.
8080
+ """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
8081
8081
 
8082
8082
  A CLI session cannot clear itself. `keel shift ready --wake` there queues
8083
- the hand-off; `keel tick` waits until the old session is idle, stops it
8084
- (kept: `claude attach` reopens it), and starts a new session in the role's
8085
- worktree that runs `keel shift resume`. `keel shift status` shows the
8086
- queue, and a failed start is a patrol risk.
8083
+ the hand-off and leaves a waiter that, once the old session has finished,
8084
+ retires it (stop, rename by resuming it with `/rename`, stop) and starts a
8085
+ new session in the role's worktree that runs `keel shift resume`. `keel
8086
+ tick` carries out a queued hand-off too, and the two start one session. A
8087
+ session that is busy, or blocked on a question (idle, but its job state is
8088
+ still `working`), is left alone. `keel shift status` shows the queue, and a
8089
+ failed start is a patrol risk.
8087
8090
  """
8088
8091
  label = "shift-cli-self-shift:"
8089
8092
  OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8090
8093
  with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
8091
8094
  base = Path(raw)
8092
8095
  rtl, verify, env, _ = shift_scratch(base)
8093
- calls, agents, fail = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start"
8096
+ calls, agents, fail, norename = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start", base / "no-rename"
8094
8097
  fake = base / "fake-claude"
8098
+ # The fake answers with the shapes measured on Claude Code 2.1.303: a live row has `status` and `state`; a stopped one has `state: stopped` and no `status`.
8095
8099
  write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8096
- f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
8097
- f"if sys.argv[1:3] == ['agents', '--json']:\n print(open({str(agents)!r}).read()); sys.exit(0)\n"
8098
- f"if sys.argv[1:2] == ['--bg'] and os.path.exists({str(fail)!r}):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8099
- "if sys.argv[1:2] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8100
+ f"agents, fail, norename = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}\n"
8101
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd(), 'claude_env': sorted(k for k in os.environ if k.startswith('CLAUDE'))}}) + '\\n')\n"
8102
+ "argv = sys.argv[1:]\n"
8103
+ "if argv[:2] == ['agents', '--json']:\n print(open(agents).read()); sys.exit(0)\n"
8104
+ "rows = json.loads(open(agents).read())\n"
8105
+ "if argv[:1] == ['stop']:\n"
8106
+ " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row['state'] = 'stopped'\n"
8107
+ " open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)\n"
8108
+ "if argv[:2] == ['--bg', '--resume']:\n"
8109
+ " for row in rows:\n if row['sessionId'] == argv[2] and not os.path.exists(norename):\n row['name'] = argv[3].split(None, 1)[1]\n"
8110
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + argv[2][:8]); sys.exit(0)\n"
8111
+ "if argv[:1] == ['--bg'] and os.path.exists(fail):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8112
+ "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8100
8113
  "print('stopped')\n")
8101
8114
  fake.chmod(0o755)
8102
- env = {**env, "KEEL_CLAUDE": str(fake)}
8115
+ env = {**env, "KEEL_CLAUDE": str(fake), "KEEL_SHIFT_HANDOVER_POLL_MS": "200", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "20000",
8116
+ "KEEL_SHIFT_RENAME_WAIT_MS": "1500"}
8117
+ # With the waiter given no time, a hand-over is the tick's alone.
8118
+ tick_only = {**env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
8103
8119
  cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8120
+ queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue"
8104
8121
 
8105
- def agents_status(status: str) -> None:
8106
- # The measured shape: `sessionId` is the full id, `id` the job id `stop` and `attach` take.
8107
- agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
8108
- "pid": os.getpid(), "status": status, "cwd": str(verify)}]))
8122
+ def agents_row(status: str | None, state: str, name: str = "verify") -> None:
8123
+ row = {"kind": "background", "name": name, "sessionId": OLD, "id": OLD[:8], "pid": os.getpid(), "state": state, "cwd": str(verify)}
8124
+ if status:
8125
+ row["status"] = status
8126
+ agents.write_text(json.dumps([row]))
8127
+
8128
+ def rows() -> list[dict]:
8129
+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8109
8130
 
8110
- def made(kind: str) -> list[dict]:
8111
- rows = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8112
- return [r for r in rows if (r["argv"][:1] == ["stop"] if kind == "stop" else r["argv"][:1] == ["--bg"])]
8131
+ def acted() -> list[list[str]]:
8132
+ return [r["argv"] for r in rows() if r["argv"][:2] != ["agents", "--json"]]
8133
+
8134
+ def starts() -> list[dict]:
8135
+ return [r for r in rows() if r["argv"][:1] == ["--bg"] and "--resume" not in r["argv"]]
8113
8136
 
8114
8137
  def tick() -> subprocess.CompletedProcess[str]:
8115
- return run_keel(verify, "tick", "--repo", str(rtl), env=env)
8138
+ return run_keel(verify, "tick", "--repo", str(rtl), env=tick_only)
8139
+
8140
+ def status_text() -> str:
8141
+ return run_keel(rtl, "shift", "status", env=env).stdout
8142
+
8143
+ def wait_for(condition, seconds: float = 10.0) -> bool:
8144
+ deadline = time.time() + seconds
8145
+ while time.time() < deadline:
8146
+ if condition():
8147
+ return True
8148
+ time.sleep(0.2)
8149
+ return condition()
8116
8150
 
8151
+ agents_row("busy", "working")
8117
8152
  readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
8118
8153
  if readied.returncode != 0:
8119
8154
  report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
8120
8155
  return 1
8121
- if "keel tick" not in readied.stdout:
8122
- report(f"{label} ready --wake in a CLI session does not say keel tick will hand over: {readied.stdout!r}")
8156
+ if "claude attach" not in readied.stdout or "--wake" in readied.stderr:
8157
+ report(f"{label} ready --wake in a CLI session does not say how the old session is reopened: {readied.stdout!r}")
8123
8158
  return 1
8124
8159
  note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
8125
8160
  if not note:
@@ -8129,58 +8164,100 @@ def validate_shift_cli_self_shift_scenario() -> int:
8129
8164
  report(f"{label} the note does not record the CLI session.")
8130
8165
  return 1
8131
8166
 
8132
- agents_status("busy")
8133
- tick()
8134
- if made("stop"):
8135
- report(f"{label} a tick stopped the old session while it was busy: {made('stop')!r}")
8167
+ # A busy session, and one blocked on a question, are left alone.
8168
+ time.sleep(1.0)
8169
+ if acted():
8170
+ report(f"{label} the hand-over acted while the old session was busy: {acted()!r}")
8136
8171
  return 1
8137
- if made("start"):
8138
- report(f"{label} a tick started a session while the old one was busy: {made('start')!r}")
8172
+ if "pending" not in status_text():
8173
+ report(f"{label} shift status does not show the pending hand-off: {status_text()!r}")
8139
8174
  return 1
8140
- status = run_keel(rtl, "shift", "status", env=env).stdout
8141
- if "pending" not in status:
8142
- report(f"{label} shift status does not show the pending hand-off: {status!r}")
8175
+ agents_row("idle", "working")
8176
+ time.sleep(1.0)
8177
+ if acted():
8178
+ report(f"{label} the hand-over cut off a session blocked on a question (idle, state working): {acted()!r}")
8143
8179
  return 1
8144
8180
 
8145
- agents_status("idle")
8146
- tick()
8147
- stops, starts = made("stop"), made("start")
8148
- if [s["argv"] for s in stops] != [["stop", OLD[:8]]]:
8149
- report(f"{label} the idle old session was not stopped once: {stops!r}")
8150
- return 1
8151
- if len(starts) != 1:
8152
- report(f"{label} the new session was not started once: {starts!r}")
8181
+ # Finished: the waiter retires it and starts the next, with no tick.
8182
+ agents_row("idle", "done")
8183
+ if not wait_for(lambda: len(starts()) >= 1):
8184
+ report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
8153
8185
  return 1
8154
- if starts[0]["argv"][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]:
8155
- report(f"{label} the new session was not started as --bg -n verify --permission-mode auto: {starts!r}")
8186
+ order = acted()
8187
+ shifted = re.compile(r"^/rename verify · shifted \d{4}-\d{2}-\d{2} \d{2}:\d{2}$")
8188
+ if (order[0] != ["stop", OLD[:8]] or order[1][:3] != ["--bg", "--resume", OLD] or len(order[1]) != 4
8189
+ or not shifted.match(order[1][3]) or order[2] != ["stop", OLD[:8]] or order[3][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]
8190
+ or len(order) != 4):
8191
+ report(f"{label} the old session was not retired as stop, rename-by-resume, stop, then the new start: {order!r}")
8156
8192
  return 1
8157
- if "keel shift resume" not in starts[0]["argv"][-1]:
8158
- report(f"{label} the new session's prompt does not name keel shift resume: {starts[0]['argv']!r}")
8193
+ if "keel shift resume" not in order[3][-1] or "--resume" in order[3]:
8194
+ report(f"{label} the new session does not start fresh with a keel shift resume prompt: {order[3]!r}")
8159
8195
  return 1
8160
- if "--resume" in starts[0]["argv"]:
8161
- report(f"{label} the new session resumes an old one instead of starting fresh: {starts[0]['argv']!r}")
8196
+ if os.path.realpath(starts()[0]["cwd"]) != os.path.realpath(verify):
8197
+ report(f"{label} the new session started in {starts()[0]['cwd']}, not verify's worktree.")
8162
8198
  return 1
8163
- if os.path.realpath(starts[0]["cwd"]) != os.path.realpath(verify):
8164
- report(f"{label} the new session started in {starts[0]['cwd']}, not verify's worktree.")
8199
+ leaked = [r for r in rows() if r["claude_env"]]
8200
+ if leaked:
8201
+ report(f"{label} a claude the hand-over ran inherited the old session's {leaked[0]['claude_env']!r}.")
8165
8202
  return 1
8166
- status = run_keel(rtl, "shift", "status", env=env).stdout
8167
- for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}"):
8168
- if needle not in status:
8169
- report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {status!r}")
8203
+ text = status_text()
8204
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}", "shifted"):
8205
+ if needle not in text:
8206
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {text!r}")
8170
8207
  return 1
8171
8208
  tick()
8172
- if len(made("start")) != 1:
8209
+ if len(starts()) != 1 or len(acted()) != 4:
8210
+ report(f"{label} a tick after the hand-over acted again: {acted()!r}")
8211
+ return 1
8212
+
8213
+ # The tick and the waiter start one session: a fresh lock holds the tick off.
8214
+ calls.write_text("")
8215
+ agents_row("idle", "done")
8216
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R014", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8217
+ lock = queue / "verify.lock"
8218
+ write_text(lock, "held")
8219
+ tick()
8220
+ if acted():
8221
+ report(f"{label} a tick acted while another hand-over held the lock: {acted()!r}")
8222
+ return 1
8223
+ lock.unlink()
8224
+ tick()
8225
+ if len(starts()) != 1:
8226
+ report(f"{label} the tick did not start one session once the lock was gone: {acted()!r}")
8227
+ return 1
8228
+ tick()
8229
+ if len(starts()) != 1:
8173
8230
  report(f"{label} a second tick started another session.")
8174
8231
  return 1
8175
8232
 
8233
+ # A rename that never shows is recorded, and the new session still starts.
8234
+ calls.write_text("")
8235
+ agents_row("idle", "done")
8236
+ write_text(norename, "x")
8237
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R015", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8238
+ ticked = tick()
8239
+ text = status_text()
8240
+ if len(starts()) != 1:
8241
+ report(f"{label} a rename that did not show stopped the new session from starting: {acted()!r} {ticked.stderr!r}")
8242
+ return 1
8243
+ if "delivered" not in text:
8244
+ report(f"{label} a rename that did not show kept the hand-off from being delivered: {text!r}")
8245
+ return 1
8246
+ if "rename not shown" not in text:
8247
+ report(f"{label} shift status does not say the rename did not show: {text!r}")
8248
+ return 1
8249
+ norename.unlink()
8250
+
8176
8251
  # A start that fails stays visible and is a patrol risk.
8177
- fail.write_text("x")
8178
- run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env=cli_env)
8252
+ calls.write_text("")
8253
+ agents_row("idle", "done")
8254
+ write_text(fail, "x")
8255
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8179
8256
  tick()
8180
- status = run_keel(rtl, "shift", "status", env=env).stdout
8257
+ text = status_text()
8181
8258
  for needle in ("failed", "Workspace not trusted"):
8182
- if needle not in status:
8183
- report(f"{label} a failed start does not show {needle!r}: {status!r}")
8259
+ if needle not in text:
8260
+ report(f"{label} a failed start does not show {needle!r}: {text!r}")
8184
8261
  return 1
8185
8262
  patrolled = run_keel(rtl, "patrol", env=env).stdout
8186
8263
  if not re.search(r"risk: .*verify.*hand-off", patrolled):
package/src/core/shift.js CHANGED
@@ -475,14 +475,16 @@ function ready(where, options) {
475
475
  store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
476
476
  }
477
477
  }
478
- // A CLI session cannot clear itself: `keel tick` stops it once idle and
479
- // starts the next (#357 D1), so nothing waits for a clear.
478
+ // A CLI session cannot clear itself: its hand-over stops it once it has
479
+ // finished and starts the next (#357 D1), so nothing waits for a clear. A
480
+ // waiter carries it out within seconds; `keel tick` stays as the fallback (#388 D1).
480
481
  const queued = options.wake && cli ? queueHandOff(where, role, cli) : null;
481
- const waiter = options.wake && !queued ? armWake(where, role, since) : null;
482
+ const waiter = options.wake && !queued ? armWake(where, role, since) : queued ? armHandOver(where, role) : null;
482
483
  return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, queued, startedBy: role ? null : options.forceReason, desktop, pid, cli, worktree: where.worktree };
483
484
  }
484
485
 
485
486
  // --- the CLI hand-off queue (#357) --------------------------------------------------
487
+ // `ready --wake` queues an entry; the waiter it leaves and `keel tick` both carry it out (#388).
486
488
 
487
489
  function queueFile(where, role) {
488
490
  return path.join(shiftDir(where), "queue", `${role}.json`);
@@ -501,50 +503,146 @@ function handOffs(where) {
501
503
 
502
504
  const SHIFT_START_TEXT = (role) => `${role}: your new shift starts now. Run keel context, then keel shift resume.`;
503
505
 
504
- // One step of the waker (#357 D2): a busy old session waits; an idle or gone
505
- // one is stopped (kept: \`claude attach\` reopens it) and a new session starts.
506
- function handOver(where) {
507
- const { readShiftDeclaration } = require("./config");
508
- const claude = process.env.KEEL_CLAUDE || "claude";
509
- const pending = handOffs(where).filter((entry) => entry.state === "pending");
510
- if (!pending.length) return [];
511
- const listed = spawnSync(claude, ["agents", "--json"], { encoding: "utf8" });
512
- let sessions = [];
506
+ // The old session has finished when it is gone, or is not busy and its job
507
+ // state is not a turn in progress: a session blocked on a question to the owner
508
+ // reads `idle` with state `working`, and stopping it cuts the conversation off (#388).
509
+ function finished(row) {
510
+ if (!row) return true;
511
+ if (row.status === "busy") return false;
512
+ return !row.state || ["done", "idle", "stopped"].includes(row.state);
513
+ }
514
+
515
+ function listAgents(claude) {
516
+ const listed = spawnSync(claude, ["agents", "--json", "--all"], { encoding: "utf8" });
517
+ try {
518
+ const parsed = JSON.parse(listed.stdout);
519
+ return listed.status === 0 && Array.isArray(parsed) ? parsed : null;
520
+ } catch {
521
+ return null;
522
+ }
523
+ }
524
+
525
+ // Stop the old session, give it a name that says it shifted, stop it again. The
526
+ // rename is a resume with `/rename` and no other flag, which keeps the session id
527
+ // and shows in `claude agents` (measured 2026-10-19); it is best effort (#388 D4).
528
+ function retire(claude, entry, row) {
529
+ const id = row.id || entry.session.slice(0, 8);
530
+ if (row.state !== "stopped") spawnSync(claude, ["stop", id], { encoding: "utf8" });
531
+ const stamp = store.isoLocal(new Date()).slice(0, 16).replace("T", " ");
532
+ const name = `${entry.role} · shifted ${stamp}`;
533
+ spawnSync(claude, ["--bg", "--resume", entry.session, `/rename ${name}`], { encoding: "utf8", cwd: row.cwd || entry.worktree });
534
+ const deadline = Date.now() + envMs("KEEL_SHIFT_RENAME_WAIT_MS", 30000);
535
+ const pause = new Int32Array(new SharedArrayBuffer(4));
536
+ let shown = false;
537
+ for (;;) {
538
+ const now = (listAgents(claude) || []).find((item) => item && item.sessionId === entry.session);
539
+ shown = Boolean(now && now.name === name);
540
+ if (shown || Date.now() >= deadline) break;
541
+ Atomics.wait(pause, 0, 0, 500);
542
+ }
543
+ spawnSync(claude, ["stop", id], { encoding: "utf8" });
544
+ return shown ? name : null;
545
+ }
546
+
547
+ // One runner at a time per role (#388 D2): the waiter and the tick both carry
548
+ // hand-overs out, and a lock younger than two minutes is the other's.
549
+ function withHandOverLock(where, role, fn) {
550
+ const file = path.join(shiftDir(where), "queue", `${role}.lock`);
513
551
  try {
514
- sessions = JSON.parse(listed.stdout);
552
+ if (Date.now() - fs.statSync(file).mtimeMs > 2 * 60 * 1000) fs.unlinkSync(file);
515
553
  } catch {
516
- sessions = [];
554
+ // no lock yet
555
+ }
556
+ let fd;
557
+ try {
558
+ fd = fs.openSync(file, "wx");
559
+ } catch {
560
+ return null;
561
+ }
562
+ try {
563
+ return fn();
564
+ } finally {
565
+ fs.closeSync(fd);
566
+ try {
567
+ fs.unlinkSync(file);
568
+ } catch {
569
+ // already gone
570
+ }
517
571
  }
572
+ }
573
+
574
+ // One step of the waker (#357 D2): a busy or unfinished old session waits; a
575
+ // finished or gone one is retired (kept: \`claude attach\` reopens it) and a new
576
+ // session starts. `only` limits the step to one role (the waiter's).
577
+ function handOver(where, only = null) {
578
+ const { readShiftDeclaration } = require("./config");
579
+ const claude = process.env.KEEL_CLAUDE || "claude";
580
+ const pending = handOffs(where).filter((entry) => entry.state === "pending" && (!only || entry.role === only));
581
+ if (!pending.length) return [];
582
+ const sessions = listAgents(claude);
583
+ // A listing that failed says nothing about the old session: wait for the next step.
584
+ if (!sessions) return [];
518
585
  const done = [];
519
- for (const entry of pending) {
520
- const row = (Array.isArray(sessions) ? sessions : []).find((item) => item && item.sessionId === entry.session);
521
- if (row && row.status === "busy") continue;
522
- // `stop`, `attach` and `logs` take the 8-character job id, not the full
523
- // session id (`No job matching`, measured 2026-10-19).
524
- if (row) spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8" });
525
- const mode = readShiftDeclaration(entry.worktree).permissionMode;
526
- const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
527
- cwd: entry.worktree, encoding: "utf8",
586
+ for (const queued of pending) {
587
+ const ran = withHandOverLock(where, queued.role, () => {
588
+ const entry = store.readJsonFile(queueFile(where, queued.role));
589
+ if (!entry || entry.state !== "pending") return null;
590
+ const row = sessions.find((item) => item && item.sessionId === entry.session);
591
+ if (!finished(row)) return null;
592
+ // `stop`, `attach` and `logs` take the 8-character job id, not the full
593
+ // session id (`No job matching`, measured 2026-10-19).
594
+ if (row) entry.renamed = retire(claude, entry, row);
595
+ const mode = readShiftDeclaration(entry.worktree).permissionMode;
596
+ const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
597
+ cwd: entry.worktree, encoding: "utf8",
598
+ });
599
+ const output = `${started.stdout || ""}`;
600
+ if (!started.error && started.status === 0) {
601
+ const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
602
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
603
+ } else {
604
+ const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
605
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
606
+ }
607
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
608
+ return entry;
528
609
  });
529
- const output = `${started.stdout || ""}`;
530
- if (!started.error && started.status === 0) {
531
- const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
532
- Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
533
- } else {
534
- const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
535
- Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
536
- }
537
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
538
- done.push(entry);
610
+ if (ran) done.push(ran);
539
611
  }
540
612
  return done;
541
613
  }
542
614
 
615
+ // `ready --wake` on the CLI leaves this waiter (#388 D1). Its working directory
616
+ // is `/`, so `check` never counts it, and its environment has none of the old
617
+ // session's `CLAUDE*` variables, which the claude it starts must not inherit.
618
+ function armHandOver(where, role) {
619
+ const keel = path.resolve(__dirname, "..", "..", "bin", "keel.js");
620
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("CLAUDE")));
621
+ const child = spawn(process.execPath, [keel, "shift", "handover-wait", "--role", role, "--repo", where.worktree],
622
+ { detached: true, stdio: "ignore", cwd: path.parse(where.worktree).root, env });
623
+ child.unref();
624
+ return child.pid;
625
+ }
626
+
627
+ function waitForHandOver(where, role) {
628
+ const poll = envMs("KEEL_SHIFT_HANDOVER_POLL_MS", 3000);
629
+ const deadline = Date.now() + envMs("KEEL_SHIFT_HANDOVER_TIMEOUT_MS", 2 * 60 * 60 * 1000);
630
+ const step = () => {
631
+ const entry = store.readJsonFile(queueFile(where, role));
632
+ if (!entry || entry.state !== "pending" || Date.now() > deadline) return;
633
+ handOver(where, role);
634
+ setTimeout(step, poll);
635
+ };
636
+ // `ready` has just run, so the session is still finishing its turn: look first after one interval.
637
+ setTimeout(step, poll);
638
+ }
639
+
543
640
  function describeHandOff(entry) {
544
641
  const tail = entry.state === "delivered"
545
642
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
546
643
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
547
- return `- ${entry.role}: ${tail}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
644
+ const renamed = entry.state === "delivered" ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
645
+ return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
548
646
  }
549
647
 
550
648
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
@@ -995,9 +1093,9 @@ const CLEAR_HINT = [
995
1093
  // or — without a chat role — the person who opens it.
996
1094
  function clearHint(result) {
997
1095
  if (result.queued) {
998
- return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session is idle, "
999
- + `\`keel tick\` stops it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1000
- + `in ${result.worktree} that runs \`keel shift resume\`. \`keel shift status\` shows the hand-off.`;
1096
+ return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session has finished, "
1097
+ + `a waiter stops it and renames it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1098
+ + `in ${result.worktree} that runs \`keel shift resume\`; \`keel tick\` does the same if the waiter is gone. \`keel shift status\` shows the hand-off.`;
1001
1099
  }
1002
1100
  let last;
1003
1101
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
@@ -1100,6 +1198,13 @@ function runShift(argv) {
1100
1198
  waitForWake(where, options.role, options.since);
1101
1199
  return 0;
1102
1200
  }
1201
+ case "handover-wait": {
1202
+ // Internal: the detached waiter `ready --wake` spawns in a CLI session.
1203
+ if (!options.role) throw new ShiftError("keel shift handover-wait needs --role.");
1204
+ store.checkName(options.role, "Role");
1205
+ waitForHandOver(where, options.role);
1206
+ return 0;
1207
+ }
1103
1208
  case "start": {
1104
1209
  if (!rest[0]) throw new ShiftError("keel shift start needs the role.");
1105
1210
  const { record, body, desktop } = start(where, rest[0], rest.slice(1).join(" "));