@christang/keel 5.166.0 → 5.168.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.166.0",
3
+ "version": "5.168.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.166.0 -->
1
+ <!-- keel:start version=5.168.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.166.0",
3
+ "version": "5.168.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.166.0",
9
+ "version": "5.168.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.166.0",
5
+ "version": "5.168.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.166.0",
3
+ "version": "5.168.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.166.0",
3
+ "version": "5.168.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",
@@ -17,6 +17,8 @@ import tempfile
17
17
  import threading
18
18
  import time
19
19
  import ast
20
+ import atexit
21
+ import signal
20
22
  from datetime import datetime, timedelta, timezone
21
23
  from concurrent.futures import ThreadPoolExecutor, as_completed
22
24
  from pathlib import Path
@@ -49,8 +51,8 @@ REQUIRED_SCRIPTS = [
49
51
  "scripts/validate_plugin.py",
50
52
  ]
51
53
 
52
- PACKAGE_VERSION = "5.166.0"
53
- PROTOCOL_VERSION = "5.166.0"
54
+ PACKAGE_VERSION = "5.168.0"
55
+ PROTOCOL_VERSION = "5.168.0"
54
56
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
57
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
58
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8253,33 +8255,34 @@ def validate_shift_cli_self_shift_scenario() -> int:
8253
8255
  calls, agents, fail, norename = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start", base / "no-rename"
8254
8256
  stoplag = base / "stop-lag"
8255
8257
  fake = base / "fake-claude"
8256
- # 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`.
8257
- # `stop` returns before the process exits (#395): with `stop-lag` holding n, the row stops n listings later, never with `never`;
8258
- # and a resume of a session still running starts a copy that takes the name, as measured.
8259
- write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8258
+ # The fake answers with the shapes measured on Claude Code 2.1.303: a live row has `status`, `state` and `pid`; a stopped one has `state: stopped` and neither.
8259
+ # `stop` drops the row's status at once and ends its process later (#397: 0.83 s against 2.68 s measured): about a second
8260
+ # later with `stop-lag` holding `late`, never with `never`, at once otherwise. A resume while the process runs starts a copy that takes the name.
8261
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, subprocess, sys\n"
8260
8262
  f"agents, fail, norename, stoplag = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}, {str(stoplag)!r}\n"
8261
8263
  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"
8262
8264
  "argv = sys.argv[1:]\n"
8265
+ "def running(pid):\n"
8266
+ " try:\n os.kill(pid, 0)\n except OSError:\n return False\n return True\n"
8263
8267
  "rows = json.loads(open(agents).read())\n"
8264
8268
  "if argv[:2] == ['agents', '--json']:\n"
8265
- " for row in rows:\n if '_stop_in' in row:\n row['_stop_in'] -= 1\n"
8266
- " if row['_stop_in'] <= 0:\n row.pop('_stop_in'); row.pop('status', None); row['state'] = 'stopped'\n"
8267
- " open(agents, 'w').write(json.dumps(rows)); print(json.dumps(rows)); sys.exit(0)\n"
8269
+ " print(json.dumps([{k: v for k, v in row.items() if not k.startswith('_')} for row in rows])); sys.exit(0)\n"
8268
8270
  "if argv[:1] == ['stop']:\n"
8269
- " lag = open(stoplag).read().strip() if os.path.exists(stoplag) else '0'\n"
8271
+ " lag = open(stoplag).read().strip() if os.path.exists(stoplag) else 'now'\n"
8270
8272
  " for row in rows:\n if row['id'] == argv[1] and 'status' in row:\n"
8271
- " if lag == '0':\n row.pop('status', None); row['state'] = 'stopped'\n"
8272
- " else:\n row['_stop_in'] = 10 ** 9 if lag == 'never' else int(lag)\n"
8273
+ " pid = row.pop('pid', None); row.pop('status', None); row['state'] = 'stopped'; row['_pid'] = pid\n"
8274
+ " if pid and lag == 'now':\n os.kill(pid, 15)\n"
8275
+ " elif pid and lag == 'late':\n subprocess.Popen(['sh', '-c', f'sleep 1; kill {pid}'], start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n"
8273
8276
  " open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)\n"
8274
8277
  "if argv[:2] == ['--bg', '--resume']:\n"
8275
8278
  " name = argv[3].split(None, 1)[1]\n"
8276
- " running = [row for row in rows if row['sessionId'] == argv[2] and 'status' in row]\n"
8277
- " if running:\n"
8278
- " rows.append({**running[0], 'sessionId': 'c0c0c0c0-0000-0000-0000-000000000000', 'id': 'c0c0c0c0', 'name': name, 'status': 'idle'})\n"
8279
- " rows[-1].pop('_stop_in', None)\n"
8279
+ " live = [row for row in rows if row['sessionId'] == argv[2] and ('status' in row or (row.get('_pid') and running(row['_pid'])))]\n"
8280
+ " if live:\n"
8281
+ " copy = {k: v for k, v in live[0].items() if not k.startswith('_')}\n"
8282
+ " rows.append({**copy, 'sessionId': 'c0c0c0c0-0000-0000-0000-000000000000', 'id': 'c0c0c0c0', 'name': name, 'status': 'idle', 'state': 'working'})\n"
8280
8283
  " print('note: session ' + argv[2][:8] + ' is already running in the background, so this started a copy as c0c0c0c0.')\n"
8281
- " for row in rows:\n if row['sessionId'] == argv[2] and not running and not os.path.exists(norename):\n row['name'] = name\n"
8282
- " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + (rows[-1]['id'] if running else argv[2][:8])); sys.exit(0)\n"
8284
+ " for row in rows:\n if row['sessionId'] == argv[2] and not live and not os.path.exists(norename):\n row['name'] = name\n"
8285
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + ('c0c0c0c0' if live else argv[2][:8])); sys.exit(0)\n"
8283
8286
  "if argv[:1] == ['--bg'] and os.path.exists(fail):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8284
8287
  "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8285
8288
  "print('stopped')\n")
@@ -8291,10 +8294,24 @@ def validate_shift_cli_self_shift_scenario() -> int:
8291
8294
  cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8292
8295
  queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue"
8293
8296
 
8297
+ children: list[int] = []
8298
+
8299
+ def end_children() -> None:
8300
+ for pid in children:
8301
+ with contextlib.suppress(OSError):
8302
+ os.kill(pid, signal.SIGTERM)
8303
+
8304
+ atexit.register(end_children)
8305
+
8294
8306
  def agents_row(status: str | None, state: str, name: str = "verify") -> None:
8295
- row = {"kind": "background", "name": name, "sessionId": OLD, "id": OLD[:8], "pid": os.getpid(), "state": state, "cwd": str(verify)}
8307
+ row = {"kind": "background", "name": name, "sessionId": OLD, "id": OLD[:8], "state": state, "cwd": str(verify)}
8296
8308
  if status:
8309
+ # The session's process: a real one, detached so that once killed it is reaped
8310
+ # rather than left a zombie the hand-over would still see running.
8311
+ started = subprocess.run(["sh", "-c", "sleep 600 >/dev/null 2>&1 & echo $!"], capture_output=True, text=True, check=True)
8312
+ children.append(int(started.stdout.strip()))
8297
8313
  row["status"] = status
8314
+ row["pid"] = children[-1]
8298
8315
  if status == "waiting":
8299
8316
  row["waitingFor"] = "input needed"
8300
8317
  agents.write_text(json.dumps([row]))
@@ -8353,29 +8370,24 @@ def validate_shift_cli_self_shift_scenario() -> int:
8353
8370
  return 1
8354
8371
 
8355
8372
  # Finished: idle, though its state still labels its last message `working` (#393, keel-maint's
8356
- # ended turn). The waiter retires it and starts the next, with no tick.
8373
+ # ended turn). The waiter stops it and starts the next, named for its start, with no tick (#399).
8357
8374
  agents_row("idle", "working")
8358
- write_text(stoplag, "2")
8359
8375
  if not wait_for(lambda: len(starts()) >= 1):
8360
8376
  report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
8361
8377
  return 1
8362
- listed = json.loads(agents.read_text())
8363
- if any(row["sessionId"] != OLD for row in listed):
8364
- report(f"{label} the rename resumed a session that was still running, starting a copy: {listed!r}")
8378
+ order = acted()
8379
+ if any(argv[:2] == ["--bg", "--resume"] for argv in order):
8380
+ report(f"{label} the hand-over woke the old session to rename it: {order!r}")
8365
8381
  return 1
8366
- if not re.match(r"^verify · shifted ", listed[0]["name"]):
8367
- report(f"{label} the old session did not take the shifted name: {listed!r}")
8382
+ if order[:1] != [["stop", OLD[:8]]] or len(order) != 2:
8383
+ report(f"{label} the old session was not retired as one stop before the new start: {order!r}")
8368
8384
  return 1
8369
- stoplag.unlink()
8370
- order = acted()
8371
- shifted = re.compile(r"^/rename verify · shifted \d{4}-\d{2}-\d{2} \d{2}:\d{2}$")
8372
- if (order[0] != ["stop", OLD[:8]] or order[1][:3] != ["--bg", "--resume", OLD] or len(order[1]) != 4
8373
- or not shifted.match(order[1][3]) or order[2] != ["stop", OLD[:8]] or order[3][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]
8374
- or len(order) != 4):
8375
- report(f"{label} the old session was not retired as stop, rename-by-resume, stop, then the new start: {order!r}")
8385
+ named = re.compile(r"^verify · \d{2}-\d{2} \d{2}:\d{2}$")
8386
+ if order[1][:2] != ["--bg", "-n"] or not named.match(order[1][2]) or order[1][3:5] != ["--permission-mode", "auto"]:
8387
+ report(f"{label} the new session is not started as `verify · <MM-DD HH:MM>`: {order[1]!r}")
8376
8388
  return 1
8377
- if "keel shift resume" not in order[3][-1] or "--resume" in order[3]:
8378
- report(f"{label} the new session does not start fresh with a keel shift resume prompt: {order[3]!r}")
8389
+ if "keel shift resume" not in order[1][-1] or "--resume" in order[1]:
8390
+ report(f"{label} the new session does not start fresh with a keel shift resume prompt: {order[1]!r}")
8379
8391
  return 1
8380
8392
  if os.path.realpath(starts()[0]["cwd"]) != os.path.realpath(verify):
8381
8393
  report(f"{label} the new session started in {starts()[0]['cwd']}, not verify's worktree.")
@@ -8385,12 +8397,12 @@ def validate_shift_cli_self_shift_scenario() -> int:
8385
8397
  report(f"{label} a claude the hand-over ran inherited the old session's {leaked[0]['claude_env']!r}.")
8386
8398
  return 1
8387
8399
  text = status_text()
8388
- for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}", "shifted"):
8400
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}", order[1][2]):
8389
8401
  if needle not in text:
8390
8402
  report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {text!r}")
8391
8403
  return 1
8392
8404
  tick()
8393
- if len(starts()) != 1 or len(acted()) != 4:
8405
+ if len(starts()) != 1 or len(acted()) != 2:
8394
8406
  report(f"{label} a tick after the hand-over acted again: {acted()!r}")
8395
8407
  return 1
8396
8408
 
@@ -8414,45 +8426,6 @@ def validate_shift_cli_self_shift_scenario() -> int:
8414
8426
  report(f"{label} a second tick started another session.")
8415
8427
  return 1
8416
8428
 
8417
- # A rename that never shows is recorded, and the new session still starts.
8418
- calls.write_text("")
8419
- agents_row("idle", "done")
8420
- write_text(norename, "x")
8421
- run_keel(verify, "shift", "ready", "--wake", "next: rerun R015", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8422
- ticked = tick()
8423
- text = status_text()
8424
- if len(starts()) != 1:
8425
- report(f"{label} a rename that did not show stopped the new session from starting: {acted()!r} {ticked.stderr!r}")
8426
- return 1
8427
- if "delivered" not in text:
8428
- report(f"{label} a rename that did not show kept the hand-off from being delivered: {text!r}")
8429
- return 1
8430
- if "rename not shown" not in text:
8431
- report(f"{label} shift status does not say the rename did not show: {text!r}")
8432
- return 1
8433
- norename.unlink()
8434
-
8435
- # A session that never shows as stopped is not resumed for its rename (#395), and the new session still starts.
8436
- calls.write_text("")
8437
- agents_row("idle", "done")
8438
- write_text(stoplag, "never")
8439
- run_keel(verify, "shift", "ready", "--wake", "next: rerun R016", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8440
- ticked = run_keel(verify, "tick", "--repo", str(rtl), env={**tick_only, "KEEL_SHIFT_STOP_WAIT_MS": "1000"})
8441
- text = status_text()
8442
- if any(argv[:2] == ["--bg", "--resume"] for argv in acted()):
8443
- report(f"{label} a session that never stopped was resumed for its rename: {acted()!r}")
8444
- return 1
8445
- if len(starts()) != 1:
8446
- report(f"{label} a session that never stopped kept the new session from starting: {acted()!r} {ticked.stderr!r}")
8447
- return 1
8448
- if "delivered" not in text:
8449
- report(f"{label} a session that never stopped kept the hand-off from being delivered: {text!r}")
8450
- return 1
8451
- if "rename not shown" not in text:
8452
- report(f"{label} shift status does not say a session that never stopped was not renamed: {text!r}")
8453
- return 1
8454
- stoplag.unlink()
8455
-
8456
8429
  # A start that fails stays visible and is a patrol risk.
8457
8430
  calls.write_text("")
8458
8431
  agents_row("idle", "done")
@@ -8475,6 +8448,214 @@ def validate_shift_cli_self_shift_scenario() -> int:
8475
8448
  return 0
8476
8449
 
8477
8450
 
8451
+ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
8452
+ """Issue #397 (owner, 2026-10-20): each CLI shift leaves a stopped session, and the list kept growing.
8453
+
8454
+ After a delivered hand-over, the newest `shift: keep_old_sessions:`
8455
+ (default 3) stopped background sessions in the role's bound worktrees stay
8456
+ listed; each older one is removed with `claude rm` once Keel's store holds
8457
+ a copy of its transcript. One whose transcript is nowhere stays, and so do
8458
+ another role's sessions and the new one.
8459
+ """
8460
+ label = "shift-cli-keeps-old-sessions:"
8461
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8462
+ with tempfile.TemporaryDirectory(prefix="keel-shift-397-") as raw:
8463
+ base = Path(raw)
8464
+ rtl, verify, env, _ = shift_scratch(base)
8465
+ calls, agents = base / "claude-calls.jsonl", base / "agents.json"
8466
+ config_dir = base / "claude-config"
8467
+ kept_dir = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "transcripts" / "verify"
8468
+ fake = base / "fake-claude"
8469
+ # Shapes measured on Claude Code 2.1.303: a live row has `status` and `pid`, a stopped one neither (#397 F3);
8470
+ # `rm` drops the row and leaves the transcript (F4). Each `rm` logs whether Keel's copy was there when it ran.
8471
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8472
+ f"agents, kept = {str(agents)!r}, {str(kept_dir)!r}\n"
8473
+ "argv = sys.argv[1:]\n"
8474
+ "rows = json.loads(open(agents).read())\n"
8475
+ "record = {'argv': argv}\n"
8476
+ "if argv[:1] == ['rm']:\n"
8477
+ " gone = [row for row in rows if row['id'] == argv[1]]\n"
8478
+ " record['kept'] = bool(gone) and os.path.exists(os.path.join(kept, gone[0]['sessionId'] + '.jsonl.gz'))\n"
8479
+ " rows = [row for row in rows if row['id'] != argv[1]]\n"
8480
+ f"open({str(calls)!r}, 'a').write(json.dumps(record) + '\\n')\n"
8481
+ "if argv[:2] == ['agents', '--json']:\n print(json.dumps(rows)); sys.exit(0)\n"
8482
+ "if argv[:1] == ['stop']:\n"
8483
+ " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row.pop('pid', None); row['state'] = 'stopped'\n"
8484
+ "if argv[:1] == ['--bg'] and '--resume' not in argv:\n"
8485
+ " rows.append({'kind': 'background', 'name': 'verify', 'sessionId': 'newsess1-0000-0000-0000-000000000000', 'id': 'newsess1',\n"
8486
+ " 'status': 'busy', 'state': 'working', 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': 1792500000000})\n"
8487
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8488
+ "open(agents, 'w').write(json.dumps(rows)); print('ok'); sys.exit(0)\n")
8489
+ fake.chmod(0o755)
8490
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
8491
+ "KEEL_SHIFT_RENAME_WAIT_MS": "200", "KEEL_SHIFT_STOP_WAIT_MS": "200"}
8492
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8493
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
8494
+ bound = {role: path for path, role in roles.items()}
8495
+
8496
+ def transcript(cwd: str, session: str, said: str) -> None:
8497
+ project = config_dir / "projects" / re.sub(r"[^A-Za-z0-9]", "-", cwd)
8498
+ project.mkdir(parents=True, exist_ok=True)
8499
+ (project / f"{session}.jsonl").write_text("\n".join(json.dumps(record) for record in (
8500
+ {"type": "user", "timestamp": "2026-10-19T01:00:00.000Z", "cwd": cwd, "message": {"role": "user", "content": "carry on"}},
8501
+ {"type": "assistant", "timestamp": "2026-10-19T01:00:05.000Z", "cwd": cwd,
8502
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
8503
+ )) + "\n", encoding="utf-8")
8504
+
8505
+ def old_row(n: int, cwd: str, with_transcript: bool = True) -> dict:
8506
+ session = f"0{n}0{n}0{n}0{n}-0000-0000-0000-00000000000{n}"
8507
+ if with_transcript:
8508
+ transcript(cwd, session, f"old shift {n}")
8509
+ return {"kind": "background", "name": "verify", "sessionId": session, "id": session[:8], "state": "stopped",
8510
+ "cwd": cwd, "startedAt": 1792400000000 + n * 1000}
8511
+
8512
+ def setup(keep: str | None, olds: list[dict]) -> None:
8513
+ calls.write_text("")
8514
+ config = verify / "keel" / "config.yaml"
8515
+ config.parent.mkdir(parents=True, exist_ok=True)
8516
+ config.write_text(f"shift:\n keep_old_sessions: {keep}\n" if keep is not None else "", encoding="utf-8")
8517
+ subprocess.run(["git", "add", "keel/config.yaml"], cwd=verify, check=True, capture_output=True)
8518
+ subprocess.run(["git", "commit", "-q", "--allow-empty", "-m", f"keep {keep}"], cwd=verify, check=True, capture_output=True)
8519
+ subprocess.run(["git", "push", "-q", "origin", "HEAD"], cwd=verify, check=True, capture_output=True)
8520
+ transcript(bound["verify"], OLD, "the shift handing over")
8521
+ live = {"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8], "status": "idle", "state": "working",
8522
+ "cwd": bound["verify"], "startedAt": 1792490000000}
8523
+ agents.write_text(json.dumps([*olds, live]))
8524
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R020", env=cli_env)
8525
+ if readied.returncode != 0:
8526
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
8527
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
8528
+
8529
+ def removed() -> list[dict]:
8530
+ return [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
8531
+
8532
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(3, bound["verify"], with_transcript=False),
8533
+ old_row(4, bound["verify"]), old_row(5, bound["rtl"])]
8534
+ setup("2", olds)
8535
+ gone = removed()
8536
+ if not gone:
8537
+ report(f"{label} the hand-over removed no old session: {calls.read_text()!r}")
8538
+ return 1
8539
+ ids = sorted(r["argv"][1] for r in gone)
8540
+ if ids != ["01010101", "02020202"]:
8541
+ report(f"{label} with keep_old_sessions 2 the removed sessions are {ids!r}, not the two oldest with a transcript.")
8542
+ return 1
8543
+ if not all(r["kept"] for r in gone):
8544
+ report(f"{label} a session was removed before Keel's store held its transcript: {gone!r}")
8545
+ return 1
8546
+ left = {row["id"] for row in json.loads(agents.read_text())}
8547
+ for keep_id, why in (("03030303", "the session with no transcript"), ("05050505", "rtl's session"),
8548
+ ("newsess1", "the new session"), (OLD[:8], "the shift just handed over"), ("04040404", "the second newest old session")):
8549
+ if keep_id not in left:
8550
+ report(f"{label} {why} ({keep_id}) was removed: {sorted(left)!r}")
8551
+ return 1
8552
+ text = run_keel(rtl, "shift", "status", env=env).stdout
8553
+ if "01010101" not in text or "02020202" not in text:
8554
+ report(f"{label} shift status does not name the removed sessions: {text!r}")
8555
+ return 1
8556
+
8557
+ # No declaration keeps three; a value that is not a whole number is named and three applies.
8558
+ for keep in (None, "many"):
8559
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"])]
8560
+ setup(keep, olds)
8561
+ ids = sorted(r["argv"][1] for r in removed())
8562
+ if ids != ["01010101"]:
8563
+ report(f"{label} the default keeps the wrong number of old sessions (keep_old_sessions {keep!r}): removed {ids!r}")
8564
+ return 1
8565
+ if keep == "many" and "keep_old_sessions" not in run_keel(rtl, "shift", "status", env=env).stdout:
8566
+ report(f"{label} an unreadable keep_old_sessions is not named: {run_keel(rtl, 'shift', 'status', env=env).stdout!r}")
8567
+ return 1
8568
+ if "shift-cli-keeps-old-sessions" not in {name for name, _ in SCENARIOS}:
8569
+ report(f"{label} scenario is not registered.")
8570
+ return 1
8571
+ report("shift-cli-keeps-old-sessions scenario passed.")
8572
+ return 0
8573
+
8574
+
8575
+ def validate_shift_history_show_scenario() -> int:
8576
+ """Issue #397 (owner, 2026-10-20): a shift no longer in `claude agents` can be read in full.
8577
+
8578
+ `keel shift history <role> --show <id>` prints the whole conversation of the
8579
+ segment whose transcript name starts with the id — prompts, replies, tool
8580
+ calls and results, in order and in full — from the host's file or, once that
8581
+ is gone, Keel's kept copy. An id that names no segment exits 1.
8582
+ """
8583
+ label = "shift-history-show:"
8584
+ with tempfile.TemporaryDirectory(prefix="keel-shift-show-") as raw:
8585
+ base = Path(raw)
8586
+ rtl, verify, env, _ = shift_scratch(base)
8587
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
8588
+ bound = next(path for path, role in roles.items() if role == "verify")
8589
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
8590
+ project.mkdir(parents=True)
8591
+ env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
8592
+ session = "4162aee5-7549-4801-b52f-871d553bdb5a"
8593
+ long_reply = "The arbiter keeps read priority over refresh. " * 12 + "End of the long reply."
8594
+ records = (
8595
+ {"type": "user", "timestamp": "2026-10-14T15:35:29.000Z", "cwd": bound, "message": {"role": "user", "content": "rerun R012 and report"}},
8596
+ {"type": "assistant", "timestamp": "2026-10-14T15:35:40.000Z", "cwd": bound,
8597
+ "message": {"role": "assistant", "content": [{"type": "text", "text": long_reply},
8598
+ {"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {"command": "make sim R012"}}]}},
8599
+ {"type": "user", "timestamp": "2026-10-14T15:36:02.000Z", "cwd": bound,
8600
+ "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "R012 PASS 4096/4096 vectors"}]}},
8601
+ )
8602
+ old = project / f"{session}.jsonl"
8603
+ old.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
8604
+
8605
+ def hook(path: Path) -> None:
8606
+ for event, name in (("session-start", "SessionStart"), ("user-prompt-submit", "UserPromptSubmit")):
8607
+ subprocess.run(
8608
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
8609
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
8610
+ input=json.dumps({"cwd": str(verify), "hook_event_name": name, "session_id": "s1",
8611
+ "prompt": "go", "source": "startup", "transcript_path": str(path)}),
8612
+ )
8613
+
8614
+ # The next shift's segments make Keel keep the old transcript; then the host's file goes.
8615
+ for name in ("a", "b"):
8616
+ path = project / f"{name}.jsonl"
8617
+ path.write_text(json.dumps({"type": "user", "timestamp": "2026-10-15T01:00:00.000Z", "cwd": bound,
8618
+ "message": {"role": "user", "content": "carry on"}}) + "\n", encoding="utf-8")
8619
+ hook(path)
8620
+ old.unlink()
8621
+ shown = run_keel(verify, "shift", "history", "verify", "--show", session[:8], env=env)
8622
+ if shown.returncode != 0:
8623
+ report(f"{label} --show of a kept shift exited {shown.returncode}: {shown.stdout!r} {shown.stderr!r}")
8624
+ return 1
8625
+ if "rerun R012 and report" not in shown.stdout:
8626
+ report(f"{label} --show printed no conversation: {shown.stdout!r} {shown.stderr!r}")
8627
+ return 1
8628
+ if session not in shown.stdout or "2026-10-14" not in shown.stdout.splitlines()[0]:
8629
+ report(f"{label} --show's header does not name the transcript and its time span: {shown.stdout.splitlines()[:2]!r}")
8630
+ return 1
8631
+ if long_reply not in shown.stdout:
8632
+ report(f"{label} --show cut the assistant's reply short: {shown.stdout!r}")
8633
+ return 1
8634
+ order = [shown.stdout.find(text) for text in ("rerun R012 and report", long_reply, "make sim R012", "R012 PASS 4096/4096 vectors")]
8635
+ if -1 in order:
8636
+ report(f"{label} --show leaves out the prompt, reply, tool call or result: {order!r} {shown.stdout!r}")
8637
+ return 1
8638
+ if order != sorted(order):
8639
+ report(f"{label} --show does not print the prompt, reply, tool call and result in order: {order!r} {shown.stdout!r}")
8640
+ return 1
8641
+ if "Bash" not in shown.stdout:
8642
+ report(f"{label} --show does not name the tool called: {shown.stdout!r}")
8643
+ return 1
8644
+
8645
+ unknown = run_keel(verify, "shift", "history", "verify", "--show", "00000000", env=env)
8646
+ if unknown.returncode != 1:
8647
+ report(f"{label} --show of an unknown id did not exit 1: {unknown.returncode} {unknown.stdout!r} {unknown.stderr!r}")
8648
+ return 1
8649
+ if "no segment" not in (unknown.stdout + unknown.stderr).lower():
8650
+ report(f"{label} --show of an unknown id does not say no segment matches: {unknown.stdout!r} {unknown.stderr!r}")
8651
+ return 1
8652
+ if "shift-history-show" not in {name for name, _ in SCENARIOS}:
8653
+ report(f"{label} scenario is not registered.")
8654
+ return 1
8655
+ report("shift-history-show scenario passed.")
8656
+ return 0
8657
+
8658
+
8478
8659
  def validate_shift_desktop_wake_overdue_scenario() -> int:
8479
8660
  """`keel shift status` flags a desktop note whose wake is overdue.
8480
8661
 
@@ -42968,9 +43149,11 @@ SCENARIOS: tuple = (
42968
43149
  ("shift-self", validate_shift_self_scenario),
42969
43150
  ("shift-self-wake", validate_shift_self_wake_scenario),
42970
43151
  ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
43152
+ ("shift-cli-keeps-old-sessions", validate_shift_cli_keeps_old_sessions_scenario),
42971
43153
  ("owner-language", validate_owner_language_scenario),
42972
43154
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42973
43155
  ("shift-history", validate_shift_history_scenario),
43156
+ ("shift-history-show", validate_shift_history_show_scenario),
42974
43157
  ("shift-resume-checks-commits", validate_shift_resume_checks_commits_scenario),
42975
43158
  ("shift-keeps-transcripts", validate_shift_keeps_transcripts_scenario),
42976
43159
  ("shift-keeps-found-transcripts", validate_shift_keeps_found_transcripts_scenario),
@@ -1023,12 +1023,20 @@ function readPatrolDeclaration(repo) {
1023
1023
 
1024
1024
  // `shift: permission_mode:` for the session a CLI hand-off starts (#357 D5).
1025
1025
  const PERMISSION_MODES = ["default", "acceptEdits", "auto", "plan", "bypassPermissions"];
1026
+ // `shift: keep_old_sessions:`, how many stopped old shift sessions a hand-over
1027
+ // leaves listed per role (#397 D2): a whole number, 3 when absent or unreadable.
1026
1028
  function readShiftDeclaration(repo) {
1027
1029
  const block = configMap(repo, "shift");
1028
1030
  const mode = block.permission_mode;
1029
- if (mode === undefined) return { permissionMode: "auto", message: null };
1030
- if (PERMISSION_MODES.includes(mode)) return { permissionMode: mode, message: null };
1031
- return { permissionMode: "auto", message: `keel/config.yaml shift: permission_mode \`${mode}\` is not one of ${PERMISSION_MODES.join(", ")}, so it is ignored.` };
1031
+ const messages = [];
1032
+ let permissionMode = "auto";
1033
+ if (PERMISSION_MODES.includes(mode)) permissionMode = mode;
1034
+ else if (mode !== undefined) messages.push(`keel/config.yaml shift: permission_mode \`${mode}\` is not one of ${PERMISSION_MODES.join(", ")}, so it is ignored.`);
1035
+ const keep = block.keep_old_sessions;
1036
+ let keepOldSessions = 3;
1037
+ if (keep !== undefined && /^\d+$/.test(String(keep).trim())) keepOldSessions = Number(String(keep).trim());
1038
+ else if (keep !== undefined) messages.push(`keel/config.yaml shift: keep_old_sessions \`${keep}\` is not a whole number, so 3 apply.`);
1039
+ return { permissionMode, keepOldSessions, message: messages.length ? messages.join(" ") : null };
1032
1040
  }
1033
1041
 
1034
1042
  function durationSeconds(value) {
package/src/core/shift.js CHANGED
@@ -32,6 +32,7 @@ const USAGE = [
32
32
  "keel shift status [--json] each role's shift state",
33
33
  "keel shift await-clear --pid <pid> wait until a desktop session's process has exited (its clear); exit 1 after --timeout-ms",
34
34
  "keel shift history [role] [--grep t] a role's past transcripts and notes; --grep searches them (#304)",
35
+ " [--show <id>] ...or print one past shift's whole conversation, listed in claude agents or not (#397)",
35
36
  "Options: --repo <path>. See docs/shift-change.md.",
36
37
  ].join("\n");
37
38
 
@@ -522,40 +523,65 @@ function listAgents(claude) {
522
523
  }
523
524
  }
524
525
 
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
- // `claude stop` returns before the process exits, and a resume of a session still
529
- // running starts a copy of it (#395), so the resume waits for the stop to show.
526
+ // Stop the old session; `claude stop` keeps its conversation. It is not resumed:
527
+ // renaming it took a resume, and a session running with Remote Control writes
528
+ // its claude.ai title back over a rename (#399 F1, F2). The new session carries
529
+ // a name of its own instead.
530
530
  function retire(claude, entry, row) {
531
- const id = row.id || entry.session.slice(0, 8);
532
- const pause = new Int32Array(new SharedArrayBuffer(4));
533
- if (row.state !== "stopped") spawnSync(claude, ["stop", id], { encoding: "utf8" });
534
- const stopBy = Date.now() + envMs("KEEL_SHIFT_STOP_WAIT_MS", 30000);
535
- for (;;) {
536
- // A listing that failed says nothing about the session: keep waiting.
537
- const listed = listAgents(claude);
538
- const now = listed && listed.find((item) => item && item.sessionId === entry.session);
539
- if (listed && (!now || !now.status)) break;
540
- if (Date.now() >= stopBy) {
541
- spawnSync(claude, ["stop", id], { encoding: "utf8" });
542
- return null;
531
+ if (row.state !== "stopped") spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8" });
532
+ }
533
+
534
+ // The new session's name: the role and its local start time (#399 D1), which
535
+ // reaches claude.ai at creation, so each shift has a name of its own.
536
+ function sessionName(role, now = new Date()) {
537
+ return `${role} · ${store.isoLocal(now).slice(5, 16).replace("T", " ")}`;
538
+ }
539
+
540
+ // The host's transcript of a session in `cwd`, under either spelling of the path.
541
+ function hostTranscript(cwd, session) {
542
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
543
+ return [cwd, realpath(cwd)].map((dir) => path.join(config, "projects", dir.replace(/[^A-Za-z0-9]/g, "-"), `${session}.jsonl`))
544
+ .find((file) => fs.existsSync(file)) || null;
545
+ }
546
+
547
+ // Keel's copy of a transcript, written now when it is missing or older (#343).
548
+ function keptCopyOf(where, role, transcript) {
549
+ const { keptFile } = require("./chat/notice");
550
+ const target = keptFile(where, role, transcript);
551
+ try {
552
+ if (!fs.existsSync(target) || fs.statSync(target).mtimeMs < fs.statSync(transcript).mtimeMs) {
553
+ fs.mkdirSync(path.dirname(target), { recursive: true });
554
+ const temporary = `${target}.${process.pid}.tmp`;
555
+ fs.writeFileSync(temporary, zlib.gzipSync(fs.readFileSync(transcript)));
556
+ fs.renameSync(temporary, target);
543
557
  }
544
- Atomics.wait(pause, 0, 0, 500);
558
+ return target;
559
+ } catch {
560
+ return null;
545
561
  }
546
- const stamp = store.isoLocal(new Date()).slice(0, 16).replace("T", " ");
547
- const name = `${entry.role} · shifted ${stamp}`;
548
- spawnSync(claude, ["--bg", "--resume", entry.session, `/rename ${name}`], { encoding: "utf8", cwd: row.cwd || entry.worktree });
549
- const deadline = Date.now() + envMs("KEEL_SHIFT_RENAME_WAIT_MS", 30000);
550
- let shown = false;
551
- for (;;) {
552
- const now = (listAgents(claude) || []).find((item) => item && item.sessionId === entry.session);
553
- shown = Boolean(now && now.name === name);
554
- if (shown || Date.now() >= deadline) break;
555
- Atomics.wait(pause, 0, 0, 500);
562
+ }
563
+
564
+ // After a delivered hand-over, the newest `keep` stopped background sessions in
565
+ // the role's bound worktrees stay listed; each older one is removed with
566
+ // `claude rm` once Keel's store holds its transcript, and one whose transcript
567
+ // is nowhere stays (#397 D2). `claude rm` leaves the host's transcript (F4).
568
+ function removeOldSessions(claude, where, entry, keep) {
569
+ const bound = new Set(Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
570
+ .filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
571
+ const listed = listAgents(claude);
572
+ if (!listed) return [];
573
+ const old = listed
574
+ .filter((row) => row && row.kind === "background" && !row.status && row.cwd && bound.has(realpath(row.cwd))
575
+ && row.sessionId && row.id !== entry.new_session)
576
+ .sort((a, b) => (Number(b.startedAt) || 0) - (Number(a.startedAt) || 0));
577
+ const removed = [];
578
+ for (const row of old.slice(keep)) {
579
+ const transcript = hostTranscript(row.cwd, row.sessionId);
580
+ if (!transcript || !keptCopyOf(where, entry.role, transcript)) continue;
581
+ const gone = spawnSync(claude, ["rm", row.id || row.sessionId.slice(0, 8)], { encoding: "utf8" });
582
+ if (!gone.error && gone.status === 0) removed.push(row.id || row.sessionId.slice(0, 8));
556
583
  }
557
- spawnSync(claude, ["stop", id], { encoding: "utf8" });
558
- return shown ? name : null;
584
+ return removed;
559
585
  }
560
586
 
561
587
  // One runner at a time per role (#388 D2): the waiter and the tick both carry
@@ -605,15 +631,19 @@ function handOver(where, only = null) {
605
631
  if (!finished(row)) return null;
606
632
  // `stop`, `attach` and `logs` take the 8-character job id, not the full
607
633
  // session id (`No job matching`, measured 2026-10-19).
608
- if (row) entry.renamed = retire(claude, entry, row);
609
- const mode = readShiftDeclaration(entry.worktree).permissionMode;
610
- const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
634
+ if (row) retire(claude, entry, row);
635
+ const declared = readShiftDeclaration(entry.worktree);
636
+ const mode = declared.permissionMode;
637
+ const name = sessionName(entry.role);
638
+ const started = spawnSync(claude, ["--bg", "-n", name, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
611
639
  cwd: entry.worktree, encoding: "utf8",
612
640
  });
613
641
  const output = `${started.stdout || ""}`;
614
642
  if (!started.error && started.status === 0) {
615
643
  const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
616
- Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
644
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
645
+ entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
646
+ if (declared.message) entry.notice = declared.message;
617
647
  } else {
618
648
  const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
619
649
  Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
@@ -653,10 +683,17 @@ function waitForHandOver(where, role) {
653
683
 
654
684
  function describeHandOff(entry) {
655
685
  const tail = entry.state === "delivered"
656
- ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
686
+ ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}`
657
687
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
658
- const renamed = entry.state === "delivered" ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
659
- return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
688
+ // An entry from before #399 recorded whether the old session's rename showed.
689
+ const renamed = entry.state === "delivered" && "renamed" in entry ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
690
+ const removed = (entry.removed || []).length ? `; older sessions removed from \`claude agents\` (transcripts kept by Keel): ${entry.removed.join(", ")}` : "";
691
+ const notice = entry.notice ? `; ${entry.notice}` : "";
692
+ const own = entry.session.slice(0, 8);
693
+ const reopen = (entry.removed || []).includes(own)
694
+ ? `old session removed, its conversation kept: \`keel shift history ${entry.role} --show ${own}\``
695
+ : `old session kept, reopen it with \`claude attach ${own}\``;
696
+ return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; ${reopen}${removed}${notice}`;
660
697
  }
661
698
 
662
699
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
@@ -1047,6 +1084,61 @@ function history(where, named, grep) {
1047
1084
  return { role, segments, notes };
1048
1085
  }
1049
1086
 
1087
+ // One past shift in full (#397 D3): the segment whose transcript name starts
1088
+ // with `id`, read from the host's file or Keel's kept copy, every conversation
1089
+ // record in file order with tool calls and results, nothing cut.
1090
+ function showSegment(where, named, id) {
1091
+ const wanted = String(id || "").trim();
1092
+ if (!wanted) throw new ShiftError("keel shift history --show needs a session id or its first 8 characters.");
1093
+ const { role, segments } = history(where, named, null);
1094
+ const matches = segments.filter((segment) => path.basename(segment.transcript).startsWith(wanted));
1095
+ if (!matches.length) throw new ShiftError(`no segment of ${role} matches ${JSON.stringify(wanted)}; \`keel shift history ${role}\` lists them.`);
1096
+ if (matches.length > 1) {
1097
+ throw new ShiftError(`${matches.length} segments of ${role} match ${JSON.stringify(wanted)}: ${matches.map((segment) => path.basename(segment.transcript)).join(", ")}.`);
1098
+ }
1099
+ const segment = matches[0];
1100
+ const source = segment.exists ? segment.transcript : segment.kept;
1101
+ if (!source) throw new ShiftError(`${segment.transcript} is gone and Keel kept no copy of it.`);
1102
+ const entries = [];
1103
+ for (const line of readTranscript(source).split("\n")) {
1104
+ if (!line.trim()) continue;
1105
+ let record;
1106
+ try {
1107
+ record = JSON.parse(line);
1108
+ } catch {
1109
+ continue;
1110
+ }
1111
+ entries.push(...shownEntries(record));
1112
+ }
1113
+ return { role, transcript: segment.transcript, source, started: segment.started, ended: segment.ended || null, entries };
1114
+ }
1115
+
1116
+ function shownEntries(record) {
1117
+ const at = record.timestamp || null;
1118
+ const content = record.message ? record.message.content : null;
1119
+ if ((record.type === "user" || record.type === "assistant") && Array.isArray(content)) {
1120
+ const shown = [];
1121
+ for (const part of content) {
1122
+ if (!part) continue;
1123
+ if (part.type === "text" && part.text) shown.push({ at, speaker: record.type, text: part.text });
1124
+ else if (part.type === "tool_use") shown.push({ at, speaker: `tool ${part.name}`, text: JSON.stringify(part.input) });
1125
+ else if (part.type === "tool_result") {
1126
+ const text = typeof part.content === "string" ? part.content
1127
+ : Array.isArray(part.content) ? part.content.filter((item) => item && item.type === "text").map((item) => item.text).join("\n") : "";
1128
+ shown.push({ at, speaker: "result", text });
1129
+ }
1130
+ }
1131
+ return shown;
1132
+ }
1133
+ const said = conversationLine(record);
1134
+ return said && said.text ? [{ at, speaker: said.speaker, text: said.text }] : [];
1135
+ }
1136
+
1137
+ function renderShown(shown) {
1138
+ const head = `${shown.started} → ${shown.ended || "now"} ${shown.transcript}${shown.source === shown.transcript ? "" : ` (kept: ${shown.source})`}`;
1139
+ return [head, ...shown.entries.map((entry) => `\n[${entry.at || "?"}] ${entry.speaker}:\n${entry.text}`)].join("\n");
1140
+ }
1141
+
1050
1142
  function renderHistory(result, grep) {
1051
1143
  const lines = [];
1052
1144
  for (const segment of result.segments) {
@@ -1108,8 +1200,8 @@ const CLEAR_HINT = [
1108
1200
  function clearHint(result) {
1109
1201
  if (result.queued) {
1110
1202
  return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session has finished, "
1111
- + `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 `
1112
- + `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.`;
1203
+ + `a waiter stops it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1204
+ + `named for its start, \`${result.role} · <MM-DD HH:MM>\`, 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.`;
1113
1205
  }
1114
1206
  let last;
1115
1207
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
@@ -1177,6 +1269,7 @@ function runShift(argv) {
1177
1269
  else if (arg === "--pid") options.pid = Number(argv[++index]);
1178
1270
  else if (arg === "--timeout-ms") options.timeoutMs = Number(argv[++index]);
1179
1271
  else if (arg === "--grep") options.grep = argv[++index] || "";
1272
+ else if (arg === "--show") options.show = argv[++index] || "";
1180
1273
  else if (arg === "--help" || arg === "-h") {
1181
1274
  process.stdout.write(`${USAGE}\n`);
1182
1275
  return 0;
@@ -1268,6 +1361,11 @@ function runShift(argv) {
1268
1361
  return 0;
1269
1362
  }
1270
1363
  case "history": {
1364
+ if (options.show !== undefined) {
1365
+ const shown = showSegment(where, rest[0] || null, options.show);
1366
+ out(shown, renderShown(shown));
1367
+ return 0;
1368
+ }
1271
1369
  const result = history(where, rest[0] || null, options.grep);
1272
1370
  out(result, renderHistory(result, options.grep));
1273
1371
  return options.grep && !result.segments.some((segment) => segment.matches.length) ? 1 : 0;