@christang/keel 5.166.0 → 5.167.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.167.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.167.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.167.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.167.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.167.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.167.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.167.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.167.0"
55
+ PROTOCOL_VERSION = "5.167.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]))
@@ -8354,8 +8371,8 @@ def validate_shift_cli_self_shift_scenario() -> int:
8354
8371
 
8355
8372
  # Finished: idle, though its state still labels its last message `working` (#393, keel-maint's
8356
8373
  # ended turn). The waiter retires it and starts the next, with no tick.
8374
+ write_text(stoplag, "late")
8357
8375
  agents_row("idle", "working")
8358
- write_text(stoplag, "2")
8359
8376
  if not wait_for(lambda: len(starts()) >= 1):
8360
8377
  report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
8361
8378
  return 1
@@ -8475,6 +8492,214 @@ def validate_shift_cli_self_shift_scenario() -> int:
8475
8492
  return 0
8476
8493
 
8477
8494
 
8495
+ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
8496
+ """Issue #397 (owner, 2026-10-20): each CLI shift leaves a stopped session, and the list kept growing.
8497
+
8498
+ After a delivered hand-over, the newest `shift: keep_old_sessions:`
8499
+ (default 3) stopped background sessions in the role's bound worktrees stay
8500
+ listed; each older one is removed with `claude rm` once Keel's store holds
8501
+ a copy of its transcript. One whose transcript is nowhere stays, and so do
8502
+ another role's sessions and the new one.
8503
+ """
8504
+ label = "shift-cli-keeps-old-sessions:"
8505
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8506
+ with tempfile.TemporaryDirectory(prefix="keel-shift-397-") as raw:
8507
+ base = Path(raw)
8508
+ rtl, verify, env, _ = shift_scratch(base)
8509
+ calls, agents = base / "claude-calls.jsonl", base / "agents.json"
8510
+ config_dir = base / "claude-config"
8511
+ kept_dir = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "transcripts" / "verify"
8512
+ fake = base / "fake-claude"
8513
+ # Shapes measured on Claude Code 2.1.303: a live row has `status` and `pid`, a stopped one neither (#397 F3);
8514
+ # `rm` drops the row and leaves the transcript (F4). Each `rm` logs whether Keel's copy was there when it ran.
8515
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8516
+ f"agents, kept = {str(agents)!r}, {str(kept_dir)!r}\n"
8517
+ "argv = sys.argv[1:]\n"
8518
+ "rows = json.loads(open(agents).read())\n"
8519
+ "record = {'argv': argv}\n"
8520
+ "if argv[:1] == ['rm']:\n"
8521
+ " gone = [row for row in rows if row['id'] == argv[1]]\n"
8522
+ " record['kept'] = bool(gone) and os.path.exists(os.path.join(kept, gone[0]['sessionId'] + '.jsonl.gz'))\n"
8523
+ " rows = [row for row in rows if row['id'] != argv[1]]\n"
8524
+ f"open({str(calls)!r}, 'a').write(json.dumps(record) + '\\n')\n"
8525
+ "if argv[:2] == ['agents', '--json']:\n print(json.dumps(rows)); sys.exit(0)\n"
8526
+ "if argv[:1] == ['stop']:\n"
8527
+ " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row.pop('pid', None); row['state'] = 'stopped'\n"
8528
+ "if argv[:1] == ['--bg'] and '--resume' not in argv:\n"
8529
+ " rows.append({'kind': 'background', 'name': 'verify', 'sessionId': 'newsess1-0000-0000-0000-000000000000', 'id': 'newsess1',\n"
8530
+ " 'status': 'busy', 'state': 'working', 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': 1792500000000})\n"
8531
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8532
+ "open(agents, 'w').write(json.dumps(rows)); print('ok'); sys.exit(0)\n")
8533
+ fake.chmod(0o755)
8534
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
8535
+ "KEEL_SHIFT_RENAME_WAIT_MS": "200", "KEEL_SHIFT_STOP_WAIT_MS": "200"}
8536
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8537
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
8538
+ bound = {role: path for path, role in roles.items()}
8539
+
8540
+ def transcript(cwd: str, session: str, said: str) -> None:
8541
+ project = config_dir / "projects" / re.sub(r"[^A-Za-z0-9]", "-", cwd)
8542
+ project.mkdir(parents=True, exist_ok=True)
8543
+ (project / f"{session}.jsonl").write_text("\n".join(json.dumps(record) for record in (
8544
+ {"type": "user", "timestamp": "2026-10-19T01:00:00.000Z", "cwd": cwd, "message": {"role": "user", "content": "carry on"}},
8545
+ {"type": "assistant", "timestamp": "2026-10-19T01:00:05.000Z", "cwd": cwd,
8546
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
8547
+ )) + "\n", encoding="utf-8")
8548
+
8549
+ def old_row(n: int, cwd: str, with_transcript: bool = True) -> dict:
8550
+ session = f"0{n}0{n}0{n}0{n}-0000-0000-0000-00000000000{n}"
8551
+ if with_transcript:
8552
+ transcript(cwd, session, f"old shift {n}")
8553
+ return {"kind": "background", "name": "verify", "sessionId": session, "id": session[:8], "state": "stopped",
8554
+ "cwd": cwd, "startedAt": 1792400000000 + n * 1000}
8555
+
8556
+ def setup(keep: str | None, olds: list[dict]) -> None:
8557
+ calls.write_text("")
8558
+ config = verify / "keel" / "config.yaml"
8559
+ config.parent.mkdir(parents=True, exist_ok=True)
8560
+ config.write_text(f"shift:\n keep_old_sessions: {keep}\n" if keep is not None else "", encoding="utf-8")
8561
+ subprocess.run(["git", "add", "keel/config.yaml"], cwd=verify, check=True, capture_output=True)
8562
+ subprocess.run(["git", "commit", "-q", "--allow-empty", "-m", f"keep {keep}"], cwd=verify, check=True, capture_output=True)
8563
+ subprocess.run(["git", "push", "-q", "origin", "HEAD"], cwd=verify, check=True, capture_output=True)
8564
+ transcript(bound["verify"], OLD, "the shift handing over")
8565
+ live = {"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8], "status": "idle", "state": "working",
8566
+ "cwd": bound["verify"], "startedAt": 1792490000000}
8567
+ agents.write_text(json.dumps([*olds, live]))
8568
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R020", env=cli_env)
8569
+ if readied.returncode != 0:
8570
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
8571
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
8572
+
8573
+ def removed() -> list[dict]:
8574
+ return [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
8575
+
8576
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(3, bound["verify"], with_transcript=False),
8577
+ old_row(4, bound["verify"]), old_row(5, bound["rtl"])]
8578
+ setup("2", olds)
8579
+ gone = removed()
8580
+ if not gone:
8581
+ report(f"{label} the hand-over removed no old session: {calls.read_text()!r}")
8582
+ return 1
8583
+ ids = sorted(r["argv"][1] for r in gone)
8584
+ if ids != ["01010101", "02020202"]:
8585
+ report(f"{label} with keep_old_sessions 2 the removed sessions are {ids!r}, not the two oldest with a transcript.")
8586
+ return 1
8587
+ if not all(r["kept"] for r in gone):
8588
+ report(f"{label} a session was removed before Keel's store held its transcript: {gone!r}")
8589
+ return 1
8590
+ left = {row["id"] for row in json.loads(agents.read_text())}
8591
+ for keep_id, why in (("03030303", "the session with no transcript"), ("05050505", "rtl's session"),
8592
+ ("newsess1", "the new session"), (OLD[:8], "the shift just handed over"), ("04040404", "the second newest old session")):
8593
+ if keep_id not in left:
8594
+ report(f"{label} {why} ({keep_id}) was removed: {sorted(left)!r}")
8595
+ return 1
8596
+ text = run_keel(rtl, "shift", "status", env=env).stdout
8597
+ if "01010101" not in text or "02020202" not in text:
8598
+ report(f"{label} shift status does not name the removed sessions: {text!r}")
8599
+ return 1
8600
+
8601
+ # No declaration keeps three; a value that is not a whole number is named and three applies.
8602
+ for keep in (None, "many"):
8603
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"])]
8604
+ setup(keep, olds)
8605
+ ids = sorted(r["argv"][1] for r in removed())
8606
+ if ids != ["01010101"]:
8607
+ report(f"{label} the default keeps the wrong number of old sessions (keep_old_sessions {keep!r}): removed {ids!r}")
8608
+ return 1
8609
+ if keep == "many" and "keep_old_sessions" not in run_keel(rtl, "shift", "status", env=env).stdout:
8610
+ report(f"{label} an unreadable keep_old_sessions is not named: {run_keel(rtl, 'shift', 'status', env=env).stdout!r}")
8611
+ return 1
8612
+ if "shift-cli-keeps-old-sessions" not in {name for name, _ in SCENARIOS}:
8613
+ report(f"{label} scenario is not registered.")
8614
+ return 1
8615
+ report("shift-cli-keeps-old-sessions scenario passed.")
8616
+ return 0
8617
+
8618
+
8619
+ def validate_shift_history_show_scenario() -> int:
8620
+ """Issue #397 (owner, 2026-10-20): a shift no longer in `claude agents` can be read in full.
8621
+
8622
+ `keel shift history <role> --show <id>` prints the whole conversation of the
8623
+ segment whose transcript name starts with the id — prompts, replies, tool
8624
+ calls and results, in order and in full — from the host's file or, once that
8625
+ is gone, Keel's kept copy. An id that names no segment exits 1.
8626
+ """
8627
+ label = "shift-history-show:"
8628
+ with tempfile.TemporaryDirectory(prefix="keel-shift-show-") as raw:
8629
+ base = Path(raw)
8630
+ rtl, verify, env, _ = shift_scratch(base)
8631
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
8632
+ bound = next(path for path, role in roles.items() if role == "verify")
8633
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
8634
+ project.mkdir(parents=True)
8635
+ env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
8636
+ session = "4162aee5-7549-4801-b52f-871d553bdb5a"
8637
+ long_reply = "The arbiter keeps read priority over refresh. " * 12 + "End of the long reply."
8638
+ records = (
8639
+ {"type": "user", "timestamp": "2026-10-14T15:35:29.000Z", "cwd": bound, "message": {"role": "user", "content": "rerun R012 and report"}},
8640
+ {"type": "assistant", "timestamp": "2026-10-14T15:35:40.000Z", "cwd": bound,
8641
+ "message": {"role": "assistant", "content": [{"type": "text", "text": long_reply},
8642
+ {"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {"command": "make sim R012"}}]}},
8643
+ {"type": "user", "timestamp": "2026-10-14T15:36:02.000Z", "cwd": bound,
8644
+ "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "R012 PASS 4096/4096 vectors"}]}},
8645
+ )
8646
+ old = project / f"{session}.jsonl"
8647
+ old.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
8648
+
8649
+ def hook(path: Path) -> None:
8650
+ for event, name in (("session-start", "SessionStart"), ("user-prompt-submit", "UserPromptSubmit")):
8651
+ subprocess.run(
8652
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
8653
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
8654
+ input=json.dumps({"cwd": str(verify), "hook_event_name": name, "session_id": "s1",
8655
+ "prompt": "go", "source": "startup", "transcript_path": str(path)}),
8656
+ )
8657
+
8658
+ # The next shift's segments make Keel keep the old transcript; then the host's file goes.
8659
+ for name in ("a", "b"):
8660
+ path = project / f"{name}.jsonl"
8661
+ path.write_text(json.dumps({"type": "user", "timestamp": "2026-10-15T01:00:00.000Z", "cwd": bound,
8662
+ "message": {"role": "user", "content": "carry on"}}) + "\n", encoding="utf-8")
8663
+ hook(path)
8664
+ old.unlink()
8665
+ shown = run_keel(verify, "shift", "history", "verify", "--show", session[:8], env=env)
8666
+ if shown.returncode != 0:
8667
+ report(f"{label} --show of a kept shift exited {shown.returncode}: {shown.stdout!r} {shown.stderr!r}")
8668
+ return 1
8669
+ if "rerun R012 and report" not in shown.stdout:
8670
+ report(f"{label} --show printed no conversation: {shown.stdout!r} {shown.stderr!r}")
8671
+ return 1
8672
+ if session not in shown.stdout or "2026-10-14" not in shown.stdout.splitlines()[0]:
8673
+ report(f"{label} --show's header does not name the transcript and its time span: {shown.stdout.splitlines()[:2]!r}")
8674
+ return 1
8675
+ if long_reply not in shown.stdout:
8676
+ report(f"{label} --show cut the assistant's reply short: {shown.stdout!r}")
8677
+ return 1
8678
+ order = [shown.stdout.find(text) for text in ("rerun R012 and report", long_reply, "make sim R012", "R012 PASS 4096/4096 vectors")]
8679
+ if -1 in order:
8680
+ report(f"{label} --show leaves out the prompt, reply, tool call or result: {order!r} {shown.stdout!r}")
8681
+ return 1
8682
+ if order != sorted(order):
8683
+ report(f"{label} --show does not print the prompt, reply, tool call and result in order: {order!r} {shown.stdout!r}")
8684
+ return 1
8685
+ if "Bash" not in shown.stdout:
8686
+ report(f"{label} --show does not name the tool called: {shown.stdout!r}")
8687
+ return 1
8688
+
8689
+ unknown = run_keel(verify, "shift", "history", "verify", "--show", "00000000", env=env)
8690
+ if unknown.returncode != 1:
8691
+ report(f"{label} --show of an unknown id did not exit 1: {unknown.returncode} {unknown.stdout!r} {unknown.stderr!r}")
8692
+ return 1
8693
+ if "no segment" not in (unknown.stdout + unknown.stderr).lower():
8694
+ report(f"{label} --show of an unknown id does not say no segment matches: {unknown.stdout!r} {unknown.stderr!r}")
8695
+ return 1
8696
+ if "shift-history-show" not in {name for name, _ in SCENARIOS}:
8697
+ report(f"{label} scenario is not registered.")
8698
+ return 1
8699
+ report("shift-history-show scenario passed.")
8700
+ return 0
8701
+
8702
+
8478
8703
  def validate_shift_desktop_wake_overdue_scenario() -> int:
8479
8704
  """`keel shift status` flags a desktop note whose wake is overdue.
8480
8705
 
@@ -42968,9 +43193,11 @@ SCENARIOS: tuple = (
42968
43193
  ("shift-self", validate_shift_self_scenario),
42969
43194
  ("shift-self-wake", validate_shift_self_wake_scenario),
42970
43195
  ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
43196
+ ("shift-cli-keeps-old-sessions", validate_shift_cli_keeps_old_sessions_scenario),
42971
43197
  ("owner-language", validate_owner_language_scenario),
42972
43198
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42973
43199
  ("shift-history", validate_shift_history_scenario),
43200
+ ("shift-history-show", validate_shift_history_show_scenario),
42974
43201
  ("shift-resume-checks-commits", validate_shift_resume_checks_commits_scenario),
42975
43202
  ("shift-keeps-transcripts", validate_shift_keeps_transcripts_scenario),
42976
43203
  ("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
 
@@ -526,17 +527,20 @@ function listAgents(claude) {
526
527
  // rename is a resume with `/rename` and no other flag, which keeps the session id
527
528
  // and shows in `claude agents` (measured 2026-10-19); it is best effort (#388 D4).
528
529
  // `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.
530
+ // running starts a copy of it (#395). The row loses its status before the process
531
+ // exits too (0.83 s against 2.68 s, measured), so the resume waits for the process
532
+ // the row showed before the stop (#397 D1); a row with no pid was already stopped.
530
533
  function retire(claude, entry, row) {
531
534
  const id = row.id || entry.session.slice(0, 8);
532
535
  const pause = new Int32Array(new SharedArrayBuffer(4));
536
+ const pid = Number.isInteger(row.pid) && row.pid > 1 ? row.pid : null;
533
537
  if (row.state !== "stopped") spawnSync(claude, ["stop", id], { encoding: "utf8" });
534
538
  const stopBy = Date.now() + envMs("KEEL_SHIFT_STOP_WAIT_MS", 30000);
535
539
  for (;;) {
536
540
  // A listing that failed says nothing about the session: keep waiting.
537
- const listed = listAgents(claude);
541
+ const listed = pid ? null : listAgents(claude);
538
542
  const now = listed && listed.find((item) => item && item.sessionId === entry.session);
539
- if (listed && (!now || !now.status)) break;
543
+ if (pid ? !alive(pid) : listed && (!now || !now.status)) break;
540
544
  if (Date.now() >= stopBy) {
541
545
  spawnSync(claude, ["stop", id], { encoding: "utf8" });
542
546
  return null;
@@ -558,6 +562,53 @@ function retire(claude, entry, row) {
558
562
  return shown ? name : null;
559
563
  }
560
564
 
565
+ // The host's transcript of a session in `cwd`, under either spelling of the path.
566
+ function hostTranscript(cwd, session) {
567
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
568
+ return [cwd, realpath(cwd)].map((dir) => path.join(config, "projects", dir.replace(/[^A-Za-z0-9]/g, "-"), `${session}.jsonl`))
569
+ .find((file) => fs.existsSync(file)) || null;
570
+ }
571
+
572
+ // Keel's copy of a transcript, written now when it is missing or older (#343).
573
+ function keptCopyOf(where, role, transcript) {
574
+ const { keptFile } = require("./chat/notice");
575
+ const target = keptFile(where, role, transcript);
576
+ try {
577
+ if (!fs.existsSync(target) || fs.statSync(target).mtimeMs < fs.statSync(transcript).mtimeMs) {
578
+ fs.mkdirSync(path.dirname(target), { recursive: true });
579
+ const temporary = `${target}.${process.pid}.tmp`;
580
+ fs.writeFileSync(temporary, zlib.gzipSync(fs.readFileSync(transcript)));
581
+ fs.renameSync(temporary, target);
582
+ }
583
+ return target;
584
+ } catch {
585
+ return null;
586
+ }
587
+ }
588
+
589
+ // After a delivered hand-over, the newest `keep` stopped background sessions in
590
+ // the role's bound worktrees stay listed; each older one is removed with
591
+ // `claude rm` once Keel's store holds its transcript, and one whose transcript
592
+ // is nowhere stays (#397 D2). `claude rm` leaves the host's transcript (F4).
593
+ function removeOldSessions(claude, where, entry, keep) {
594
+ const bound = new Set(Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
595
+ .filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
596
+ const listed = listAgents(claude);
597
+ if (!listed) return [];
598
+ const old = listed
599
+ .filter((row) => row && row.kind === "background" && !row.status && row.cwd && bound.has(realpath(row.cwd))
600
+ && row.sessionId && row.id !== entry.new_session)
601
+ .sort((a, b) => (Number(b.startedAt) || 0) - (Number(a.startedAt) || 0));
602
+ const removed = [];
603
+ for (const row of old.slice(keep)) {
604
+ const transcript = hostTranscript(row.cwd, row.sessionId);
605
+ if (!transcript || !keptCopyOf(where, entry.role, transcript)) continue;
606
+ const gone = spawnSync(claude, ["rm", row.id || row.sessionId.slice(0, 8)], { encoding: "utf8" });
607
+ if (!gone.error && gone.status === 0) removed.push(row.id || row.sessionId.slice(0, 8));
608
+ }
609
+ return removed;
610
+ }
611
+
561
612
  // One runner at a time per role (#388 D2): the waiter and the tick both carry
562
613
  // hand-overs out, and a lock younger than two minutes is the other's.
563
614
  function withHandOverLock(where, role, fn) {
@@ -606,7 +657,8 @@ function handOver(where, only = null) {
606
657
  // `stop`, `attach` and `logs` take the 8-character job id, not the full
607
658
  // session id (`No job matching`, measured 2026-10-19).
608
659
  if (row) entry.renamed = retire(claude, entry, row);
609
- const mode = readShiftDeclaration(entry.worktree).permissionMode;
660
+ const declared = readShiftDeclaration(entry.worktree);
661
+ const mode = declared.permissionMode;
610
662
  const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
611
663
  cwd: entry.worktree, encoding: "utf8",
612
664
  });
@@ -614,6 +666,8 @@ function handOver(where, only = null) {
614
666
  if (!started.error && started.status === 0) {
615
667
  const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
616
668
  Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
669
+ entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
670
+ if (declared.message) entry.notice = declared.message;
617
671
  } else {
618
672
  const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
619
673
  Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
@@ -656,7 +710,13 @@ function describeHandOff(entry) {
656
710
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
657
711
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
658
712
  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)}\``;
713
+ const removed = (entry.removed || []).length ? `; older sessions removed from \`claude agents\` (transcripts kept by Keel): ${entry.removed.join(", ")}` : "";
714
+ const notice = entry.notice ? `; ${entry.notice}` : "";
715
+ const own = entry.session.slice(0, 8);
716
+ const reopen = (entry.removed || []).includes(own)
717
+ ? `old session removed, its conversation kept: \`keel shift history ${entry.role} --show ${own}\``
718
+ : `old session kept, reopen it with \`claude attach ${own}\``;
719
+ return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; ${reopen}${removed}${notice}`;
660
720
  }
661
721
 
662
722
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
@@ -1047,6 +1107,61 @@ function history(where, named, grep) {
1047
1107
  return { role, segments, notes };
1048
1108
  }
1049
1109
 
1110
+ // One past shift in full (#397 D3): the segment whose transcript name starts
1111
+ // with `id`, read from the host's file or Keel's kept copy, every conversation
1112
+ // record in file order with tool calls and results, nothing cut.
1113
+ function showSegment(where, named, id) {
1114
+ const wanted = String(id || "").trim();
1115
+ if (!wanted) throw new ShiftError("keel shift history --show needs a session id or its first 8 characters.");
1116
+ const { role, segments } = history(where, named, null);
1117
+ const matches = segments.filter((segment) => path.basename(segment.transcript).startsWith(wanted));
1118
+ if (!matches.length) throw new ShiftError(`no segment of ${role} matches ${JSON.stringify(wanted)}; \`keel shift history ${role}\` lists them.`);
1119
+ if (matches.length > 1) {
1120
+ throw new ShiftError(`${matches.length} segments of ${role} match ${JSON.stringify(wanted)}: ${matches.map((segment) => path.basename(segment.transcript)).join(", ")}.`);
1121
+ }
1122
+ const segment = matches[0];
1123
+ const source = segment.exists ? segment.transcript : segment.kept;
1124
+ if (!source) throw new ShiftError(`${segment.transcript} is gone and Keel kept no copy of it.`);
1125
+ const entries = [];
1126
+ for (const line of readTranscript(source).split("\n")) {
1127
+ if (!line.trim()) continue;
1128
+ let record;
1129
+ try {
1130
+ record = JSON.parse(line);
1131
+ } catch {
1132
+ continue;
1133
+ }
1134
+ entries.push(...shownEntries(record));
1135
+ }
1136
+ return { role, transcript: segment.transcript, source, started: segment.started, ended: segment.ended || null, entries };
1137
+ }
1138
+
1139
+ function shownEntries(record) {
1140
+ const at = record.timestamp || null;
1141
+ const content = record.message ? record.message.content : null;
1142
+ if ((record.type === "user" || record.type === "assistant") && Array.isArray(content)) {
1143
+ const shown = [];
1144
+ for (const part of content) {
1145
+ if (!part) continue;
1146
+ if (part.type === "text" && part.text) shown.push({ at, speaker: record.type, text: part.text });
1147
+ else if (part.type === "tool_use") shown.push({ at, speaker: `tool ${part.name}`, text: JSON.stringify(part.input) });
1148
+ else if (part.type === "tool_result") {
1149
+ const text = typeof part.content === "string" ? part.content
1150
+ : Array.isArray(part.content) ? part.content.filter((item) => item && item.type === "text").map((item) => item.text).join("\n") : "";
1151
+ shown.push({ at, speaker: "result", text });
1152
+ }
1153
+ }
1154
+ return shown;
1155
+ }
1156
+ const said = conversationLine(record);
1157
+ return said && said.text ? [{ at, speaker: said.speaker, text: said.text }] : [];
1158
+ }
1159
+
1160
+ function renderShown(shown) {
1161
+ const head = `${shown.started} → ${shown.ended || "now"} ${shown.transcript}${shown.source === shown.transcript ? "" : ` (kept: ${shown.source})`}`;
1162
+ return [head, ...shown.entries.map((entry) => `\n[${entry.at || "?"}] ${entry.speaker}:\n${entry.text}`)].join("\n");
1163
+ }
1164
+
1050
1165
  function renderHistory(result, grep) {
1051
1166
  const lines = [];
1052
1167
  for (const segment of result.segments) {
@@ -1177,6 +1292,7 @@ function runShift(argv) {
1177
1292
  else if (arg === "--pid") options.pid = Number(argv[++index]);
1178
1293
  else if (arg === "--timeout-ms") options.timeoutMs = Number(argv[++index]);
1179
1294
  else if (arg === "--grep") options.grep = argv[++index] || "";
1295
+ else if (arg === "--show") options.show = argv[++index] || "";
1180
1296
  else if (arg === "--help" || arg === "-h") {
1181
1297
  process.stdout.write(`${USAGE}\n`);
1182
1298
  return 0;
@@ -1268,6 +1384,11 @@ function runShift(argv) {
1268
1384
  return 0;
1269
1385
  }
1270
1386
  case "history": {
1387
+ if (options.show !== undefined) {
1388
+ const shown = showSegment(where, rest[0] || null, options.show);
1389
+ out(shown, renderShown(shown));
1390
+ return 0;
1391
+ }
1271
1392
  const result = history(where, rest[0] || null, options.grep);
1272
1393
  out(result, renderHistory(result, options.grep));
1273
1394
  return options.grep && !result.segments.some((segment) => segment.matches.length) ? 1 : 0;