@christang/keel 5.165.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.165.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.165.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.165.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.165.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.165.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.165.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.165.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.165.0"
53
- PROTOCOL_VERSION = "5.165.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
@@ -8251,20 +8253,36 @@ def validate_shift_cli_self_shift_scenario() -> int:
8251
8253
  base = Path(raw)
8252
8254
  rtl, verify, env, _ = shift_scratch(base)
8253
8255
  calls, agents, fail, norename = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start", base / "no-rename"
8256
+ stoplag = base / "stop-lag"
8254
8257
  fake = base / "fake-claude"
8255
- # 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`.
8256
- write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8257
- f"agents, fail, norename = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}\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"
8262
+ f"agents, fail, norename, stoplag = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}, {str(stoplag)!r}\n"
8258
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"
8259
8264
  "argv = sys.argv[1:]\n"
8260
- "if argv[:2] == ['agents', '--json']:\n print(open(agents).read()); sys.exit(0)\n"
8265
+ "def running(pid):\n"
8266
+ " try:\n os.kill(pid, 0)\n except OSError:\n return False\n return True\n"
8261
8267
  "rows = json.loads(open(agents).read())\n"
8268
+ "if argv[:2] == ['agents', '--json']:\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"
8262
8270
  "if argv[:1] == ['stop']:\n"
8263
- " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row['state'] = 'stopped'\n"
8271
+ " lag = open(stoplag).read().strip() if os.path.exists(stoplag) else 'now'\n"
8272
+ " for row in rows:\n if row['id'] == argv[1] and 'status' in row:\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"
8264
8276
  " open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)\n"
8265
8277
  "if argv[:2] == ['--bg', '--resume']:\n"
8266
- " 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"
8267
- " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + argv[2][:8]); sys.exit(0)\n"
8278
+ " name = argv[3].split(None, 1)[1]\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"
8283
+ " print('note: session ' + argv[2][:8] + ' is already running in the background, so this started a copy as c0c0c0c0.')\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"
8268
8286
  "if argv[:1] == ['--bg'] and os.path.exists(fail):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8269
8287
  "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8270
8288
  "print('stopped')\n")
@@ -8276,10 +8294,24 @@ def validate_shift_cli_self_shift_scenario() -> int:
8276
8294
  cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8277
8295
  queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue"
8278
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
+
8279
8306
  def agents_row(status: str | None, state: str, name: str = "verify") -> None:
8280
- 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)}
8281
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()))
8282
8313
  row["status"] = status
8314
+ row["pid"] = children[-1]
8283
8315
  if status == "waiting":
8284
8316
  row["waitingFor"] = "input needed"
8285
8317
  agents.write_text(json.dumps([row]))
@@ -8339,10 +8371,19 @@ def validate_shift_cli_self_shift_scenario() -> int:
8339
8371
 
8340
8372
  # Finished: idle, though its state still labels its last message `working` (#393, keel-maint's
8341
8373
  # ended turn). The waiter retires it and starts the next, with no tick.
8374
+ write_text(stoplag, "late")
8342
8375
  agents_row("idle", "working")
8343
8376
  if not wait_for(lambda: len(starts()) >= 1):
8344
8377
  report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
8345
8378
  return 1
8379
+ listed = json.loads(agents.read_text())
8380
+ if any(row["sessionId"] != OLD for row in listed):
8381
+ report(f"{label} the rename resumed a session that was still running, starting a copy: {listed!r}")
8382
+ return 1
8383
+ if not re.match(r"^verify · shifted ", listed[0]["name"]):
8384
+ report(f"{label} the old session did not take the shifted name: {listed!r}")
8385
+ return 1
8386
+ stoplag.unlink()
8346
8387
  order = acted()
8347
8388
  shifted = re.compile(r"^/rename verify · shifted \d{4}-\d{2}-\d{2} \d{2}:\d{2}$")
8348
8389
  if (order[0] != ["stop", OLD[:8]] or order[1][:3] != ["--bg", "--resume", OLD] or len(order[1]) != 4
@@ -8408,6 +8449,27 @@ def validate_shift_cli_self_shift_scenario() -> int:
8408
8449
  return 1
8409
8450
  norename.unlink()
8410
8451
 
8452
+ # A session that never shows as stopped is not resumed for its rename (#395), and the new session still starts.
8453
+ calls.write_text("")
8454
+ agents_row("idle", "done")
8455
+ write_text(stoplag, "never")
8456
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R016", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8457
+ ticked = run_keel(verify, "tick", "--repo", str(rtl), env={**tick_only, "KEEL_SHIFT_STOP_WAIT_MS": "1000"})
8458
+ text = status_text()
8459
+ if any(argv[:2] == ["--bg", "--resume"] for argv in acted()):
8460
+ report(f"{label} a session that never stopped was resumed for its rename: {acted()!r}")
8461
+ return 1
8462
+ if len(starts()) != 1:
8463
+ report(f"{label} a session that never stopped kept the new session from starting: {acted()!r} {ticked.stderr!r}")
8464
+ return 1
8465
+ if "delivered" not in text:
8466
+ report(f"{label} a session that never stopped kept the hand-off from being delivered: {text!r}")
8467
+ return 1
8468
+ if "rename not shown" not in text:
8469
+ report(f"{label} shift status does not say a session that never stopped was not renamed: {text!r}")
8470
+ return 1
8471
+ stoplag.unlink()
8472
+
8411
8473
  # A start that fails stays visible and is a patrol risk.
8412
8474
  calls.write_text("")
8413
8475
  agents_row("idle", "done")
@@ -8430,6 +8492,214 @@ def validate_shift_cli_self_shift_scenario() -> int:
8430
8492
  return 0
8431
8493
 
8432
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
+
8433
8703
  def validate_shift_desktop_wake_overdue_scenario() -> int:
8434
8704
  """`keel shift status` flags a desktop note whose wake is overdue.
8435
8705
 
@@ -42923,9 +43193,11 @@ SCENARIOS: tuple = (
42923
43193
  ("shift-self", validate_shift_self_scenario),
42924
43194
  ("shift-self-wake", validate_shift_self_wake_scenario),
42925
43195
  ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
43196
+ ("shift-cli-keeps-old-sessions", validate_shift_cli_keeps_old_sessions_scenario),
42926
43197
  ("owner-language", validate_owner_language_scenario),
42927
43198
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42928
43199
  ("shift-history", validate_shift_history_scenario),
43200
+ ("shift-history-show", validate_shift_history_show_scenario),
42929
43201
  ("shift-resume-checks-commits", validate_shift_resume_checks_commits_scenario),
42930
43202
  ("shift-keeps-transcripts", validate_shift_keeps_transcripts_scenario),
42931
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
 
@@ -525,14 +526,31 @@ function listAgents(claude) {
525
526
  // Stop the old session, give it a name that says it shifted, stop it again. The
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).
529
+ // `claude stop` returns before the process exits, and a resume of a session still
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.
528
533
  function retire(claude, entry, row) {
529
534
  const id = row.id || entry.session.slice(0, 8);
535
+ const pause = new Int32Array(new SharedArrayBuffer(4));
536
+ const pid = Number.isInteger(row.pid) && row.pid > 1 ? row.pid : null;
530
537
  if (row.state !== "stopped") spawnSync(claude, ["stop", id], { encoding: "utf8" });
538
+ const stopBy = Date.now() + envMs("KEEL_SHIFT_STOP_WAIT_MS", 30000);
539
+ for (;;) {
540
+ // A listing that failed says nothing about the session: keep waiting.
541
+ const listed = pid ? null : listAgents(claude);
542
+ const now = listed && listed.find((item) => item && item.sessionId === entry.session);
543
+ if (pid ? !alive(pid) : listed && (!now || !now.status)) break;
544
+ if (Date.now() >= stopBy) {
545
+ spawnSync(claude, ["stop", id], { encoding: "utf8" });
546
+ return null;
547
+ }
548
+ Atomics.wait(pause, 0, 0, 500);
549
+ }
531
550
  const stamp = store.isoLocal(new Date()).slice(0, 16).replace("T", " ");
532
551
  const name = `${entry.role} · shifted ${stamp}`;
533
552
  spawnSync(claude, ["--bg", "--resume", entry.session, `/rename ${name}`], { encoding: "utf8", cwd: row.cwd || entry.worktree });
534
553
  const deadline = Date.now() + envMs("KEEL_SHIFT_RENAME_WAIT_MS", 30000);
535
- const pause = new Int32Array(new SharedArrayBuffer(4));
536
554
  let shown = false;
537
555
  for (;;) {
538
556
  const now = (listAgents(claude) || []).find((item) => item && item.sessionId === entry.session);
@@ -544,6 +562,53 @@ function retire(claude, entry, row) {
544
562
  return shown ? name : null;
545
563
  }
546
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
+
547
612
  // One runner at a time per role (#388 D2): the waiter and the tick both carry
548
613
  // hand-overs out, and a lock younger than two minutes is the other's.
549
614
  function withHandOverLock(where, role, fn) {
@@ -592,7 +657,8 @@ function handOver(where, only = null) {
592
657
  // `stop`, `attach` and `logs` take the 8-character job id, not the full
593
658
  // session id (`No job matching`, measured 2026-10-19).
594
659
  if (row) entry.renamed = retire(claude, entry, row);
595
- const mode = readShiftDeclaration(entry.worktree).permissionMode;
660
+ const declared = readShiftDeclaration(entry.worktree);
661
+ const mode = declared.permissionMode;
596
662
  const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
597
663
  cwd: entry.worktree, encoding: "utf8",
598
664
  });
@@ -600,6 +666,8 @@ function handOver(where, only = null) {
600
666
  if (!started.error && started.status === 0) {
601
667
  const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
602
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;
603
671
  } else {
604
672
  const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
605
673
  Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
@@ -642,7 +710,13 @@ function describeHandOff(entry) {
642
710
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
643
711
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
644
712
  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)}\``;
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}`;
646
720
  }
647
721
 
648
722
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
@@ -1033,6 +1107,61 @@ function history(where, named, grep) {
1033
1107
  return { role, segments, notes };
1034
1108
  }
1035
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
+
1036
1165
  function renderHistory(result, grep) {
1037
1166
  const lines = [];
1038
1167
  for (const segment of result.segments) {
@@ -1163,6 +1292,7 @@ function runShift(argv) {
1163
1292
  else if (arg === "--pid") options.pid = Number(argv[++index]);
1164
1293
  else if (arg === "--timeout-ms") options.timeoutMs = Number(argv[++index]);
1165
1294
  else if (arg === "--grep") options.grep = argv[++index] || "";
1295
+ else if (arg === "--show") options.show = argv[++index] || "";
1166
1296
  else if (arg === "--help" || arg === "-h") {
1167
1297
  process.stdout.write(`${USAGE}\n`);
1168
1298
  return 0;
@@ -1254,6 +1384,11 @@ function runShift(argv) {
1254
1384
  return 0;
1255
1385
  }
1256
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
+ }
1257
1392
  const result = history(where, rest[0] || null, options.grep);
1258
1393
  out(result, renderHistory(result, options.grep));
1259
1394
  return options.grep && !result.segments.some((segment) => segment.matches.length) ? 1 : 0;