@christang/keel 5.155.0 → 5.157.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.155.0",
3
+ "version": "5.157.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.155.0 -->
1
+ <!-- keel:start version=5.157.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.155.0",
3
+ "version": "5.157.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.155.0",
9
+ "version": "5.157.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.155.0",
5
+ "version": "5.157.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.155.0",
3
+ "version": "5.157.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.155.0",
3
+ "version": "5.157.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.155.0"
53
- PROTOCOL_VERSION = "5.155.0"
52
+ PACKAGE_VERSION = "5.157.0"
53
+ PROTOCOL_VERSION = "5.157.0"
54
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -2502,6 +2502,102 @@ def validate_chat_mention_skips_code_scenario() -> int:
2502
2502
  return 0
2503
2503
 
2504
2504
 
2505
+ def validate_chat_wake_now_cli_scenario() -> int:
2506
+ """Issue #348 on the CLI (owner's CLI waker, 2026-10-19): one step wakes a role.
2507
+
2508
+ A background CLI session's hooks record its session id and process. When
2509
+ that process has exited, `keel chat wake now <role>` resumes it with
2510
+ `claude --bg --resume <id> "<pointer>"` in its worktree — no other flag, so
2511
+ the id is kept — and `keel tick` does the same once per new addressed
2512
+ record. A running session is left to the record itself, which wakes it.
2513
+ """
2514
+ label = "chat-wake-now-cli:"
2515
+ with tempfile.TemporaryDirectory(prefix="keel-wake-348-") as raw:
2516
+ base = Path(raw)
2517
+ rtl, verify, env, _ = shift_scratch(base)
2518
+ calls = base / "claude-calls.jsonl"
2519
+ fake = base / "fake-claude"
2520
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
2521
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
2522
+ "print('backgrounded · fake')\n")
2523
+ fake.chmod(0o755)
2524
+ env = {**env, "KEEL_CLAUDE": str(fake)}
2525
+ dead = subprocess.Popen(["true"])
2526
+ dead.wait()
2527
+
2528
+ def start(pid: int) -> None:
2529
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify, text=True,
2530
+ capture_output=True, check=False,
2531
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-verify-1", "CLAUDE_PID": str(pid)},
2532
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": "sess-verify-1", "source": "startup"}))
2533
+
2534
+ def made() -> list[dict]:
2535
+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2536
+
2537
+ start(dead.pid)
2538
+ posted = run_keel(rtl, "chat", "dm", "verify", "rerun R009", env=env)
2539
+ if "keel chat wake now verify" not in posted.stdout:
2540
+ report(f"{label} a dm to a role whose CLI process exited does not name `keel chat wake now verify`: {posted.stdout!r}")
2541
+ return 1
2542
+ if "get_session" in posted.stdout:
2543
+ report(f"{label} a CLI role is given the desktop wake step: {posted.stdout!r}")
2544
+ return 1
2545
+ woke = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
2546
+ if woke.returncode != 0:
2547
+ report(f"{label} keel chat wake now failed: {woke.stdout!r} {woke.stderr!r}")
2548
+ return 1
2549
+ if len(made()) != 1:
2550
+ report(f"{label} wake now did not run claude once: {made()!r}")
2551
+ return 1
2552
+ call = made()[0]
2553
+ if call["argv"][:3] != ["--bg", "--resume", "sess-verify-1"] or len(call["argv"]) != 4:
2554
+ report(f"{label} wake now ran claude with {call['argv']!r}, not --bg --resume <id> <prompt> and nothing else.")
2555
+ return 1
2556
+ if "keel chat unread" not in call["argv"][3]:
2557
+ report(f"{label} the resume prompt does not point at keel chat unread: {call['argv'][3]!r}")
2558
+ return 1
2559
+ if os.path.realpath(call["cwd"]) != os.path.realpath(verify):
2560
+ report(f"{label} claude was resumed in {call['cwd']}, not verify's worktree.")
2561
+ return 1
2562
+
2563
+ start(os.getpid())
2564
+ alive = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
2565
+ if len(made()) != 1:
2566
+ report(f"{label} wake now resumed a role whose process is running: {made()!r}")
2567
+ return 1
2568
+ if "running" not in alive.stdout:
2569
+ report(f"{label} wake now does not say the session is running: {alive.stdout!r}")
2570
+ return 1
2571
+
2572
+ start(dead.pid)
2573
+ run_keel(rtl, "chat", "dm", "verify", "rerun R010", env=env)
2574
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2575
+ if len(made()) != 2:
2576
+ report(f"{label} keel tick did not wake the exited role for its new record: {made()!r}")
2577
+ return 1
2578
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2579
+ if len(made()) != 2:
2580
+ report(f"{label} a second tick woke the role again for the same record: {made()!r}")
2581
+ return 1
2582
+ time.sleep(2)
2583
+ nudged = run_keel(rtl, "patrol", "--nudge", "--idle", "1s", env=env).stdout
2584
+ escalation = next((l for l in nudged.splitlines() if "verify" in l and "wakes nothing" in l), "")
2585
+ if "keel chat wake now verify" not in escalation or "get_session" in escalation:
2586
+ report(f"{label} the patrol's nudge escalation for an ended CLI session is not `keel chat wake now verify`: {nudged!r}")
2587
+ return 1
2588
+ run_keel(rtl, "chat", "role", "--park", "verify", "--reason", "held for review", env=env)
2589
+ run_keel(rtl, "chat", "dm", "verify", "rerun R011", env=env)
2590
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2591
+ if len(made()) != 2:
2592
+ report(f"{label} keel tick woke a parked role: {made()!r}")
2593
+ return 1
2594
+ if "chat-wake-now-cli" not in {name for name, _ in SCENARIOS}:
2595
+ report(f"{label} scenario is not registered.")
2596
+ return 1
2597
+ report("chat-wake-now-cli scenario passed.")
2598
+ return 0
2599
+
2600
+
2505
2601
  def validate_chat_supersedes_scenario() -> int:
2506
2602
  """Issue #252: a record supersedes its author's earlier one.
2507
2603
 
@@ -7811,6 +7907,123 @@ def validate_shift_start_desktop_scenario() -> int:
7811
7907
  return 0
7812
7908
 
7813
7909
 
7910
+ def validate_shift_cli_self_shift_scenario() -> int:
7911
+ """Issue #357 on the CLI (owner, 2026-10-19): stop the old session, start a new one.
7912
+
7913
+ A CLI session cannot clear itself. `keel shift ready --wake` there queues
7914
+ the hand-off; `keel tick` waits until the old session is idle, stops it
7915
+ (kept: `claude attach` reopens it), and starts a new session in the role's
7916
+ worktree that runs `keel shift resume`. `keel shift status` shows the
7917
+ queue, and a failed start is a patrol risk.
7918
+ """
7919
+ label = "shift-cli-self-shift:"
7920
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
7921
+ with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
7922
+ base = Path(raw)
7923
+ rtl, verify, env, _ = shift_scratch(base)
7924
+ calls, agents, fail = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start"
7925
+ fake = base / "fake-claude"
7926
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
7927
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
7928
+ f"if sys.argv[1:3] == ['agents', '--json']:\n print(open({str(agents)!r}).read()); sys.exit(0)\n"
7929
+ f"if sys.argv[1:2] == ['--bg'] and os.path.exists({str(fail)!r}):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
7930
+ "if sys.argv[1:2] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
7931
+ "print('stopped')\n")
7932
+ fake.chmod(0o755)
7933
+ env = {**env, "KEEL_CLAUDE": str(fake)}
7934
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
7935
+
7936
+ def agents_status(status: str) -> None:
7937
+ # The measured shape: `sessionId` is the full id, `id` the job id `stop` and `attach` take.
7938
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
7939
+ "pid": os.getpid(), "status": status, "cwd": str(verify)}]))
7940
+
7941
+ def made(kind: str) -> list[dict]:
7942
+ rows = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
7943
+ return [r for r in rows if (r["argv"][:1] == ["stop"] if kind == "stop" else r["argv"][:1] == ["--bg"])]
7944
+
7945
+ def tick() -> subprocess.CompletedProcess[str]:
7946
+ return run_keel(verify, "tick", "--repo", str(rtl), env=env)
7947
+
7948
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
7949
+ if readied.returncode != 0:
7950
+ report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
7951
+ return 1
7952
+ if "keel tick" not in readied.stdout:
7953
+ report(f"{label} ready --wake in a CLI session does not say keel tick will hand over: {readied.stdout!r}")
7954
+ return 1
7955
+ note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
7956
+ if not note:
7957
+ report(f"{label} ready --wake stored no note for verify.")
7958
+ return 1
7959
+ if f"CLI session: {OLD}." not in note.read_text(encoding="utf-8"):
7960
+ report(f"{label} the note does not record the CLI session.")
7961
+ return 1
7962
+
7963
+ agents_status("busy")
7964
+ tick()
7965
+ if made("stop"):
7966
+ report(f"{label} a tick stopped the old session while it was busy: {made('stop')!r}")
7967
+ return 1
7968
+ if made("start"):
7969
+ report(f"{label} a tick started a session while the old one was busy: {made('start')!r}")
7970
+ return 1
7971
+ status = run_keel(rtl, "shift", "status", env=env).stdout
7972
+ if "pending" not in status:
7973
+ report(f"{label} shift status does not show the pending hand-off: {status!r}")
7974
+ return 1
7975
+
7976
+ agents_status("idle")
7977
+ tick()
7978
+ stops, starts = made("stop"), made("start")
7979
+ if [s["argv"] for s in stops] != [["stop", OLD[:8]]]:
7980
+ report(f"{label} the idle old session was not stopped once: {stops!r}")
7981
+ return 1
7982
+ if len(starts) != 1:
7983
+ report(f"{label} the new session was not started once: {starts!r}")
7984
+ return 1
7985
+ if starts[0]["argv"][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]:
7986
+ report(f"{label} the new session was not started as --bg -n verify --permission-mode auto: {starts!r}")
7987
+ return 1
7988
+ if "keel shift resume" not in starts[0]["argv"][-1]:
7989
+ report(f"{label} the new session's prompt does not name keel shift resume: {starts[0]['argv']!r}")
7990
+ return 1
7991
+ if "--resume" in starts[0]["argv"]:
7992
+ report(f"{label} the new session resumes an old one instead of starting fresh: {starts[0]['argv']!r}")
7993
+ return 1
7994
+ if os.path.realpath(starts[0]["cwd"]) != os.path.realpath(verify):
7995
+ report(f"{label} the new session started in {starts[0]['cwd']}, not verify's worktree.")
7996
+ return 1
7997
+ status = run_keel(rtl, "shift", "status", env=env).stdout
7998
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}"):
7999
+ if needle not in status:
8000
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {status!r}")
8001
+ return 1
8002
+ tick()
8003
+ if len(made("start")) != 1:
8004
+ report(f"{label} a second tick started another session.")
8005
+ return 1
8006
+
8007
+ # A start that fails stays visible and is a patrol risk.
8008
+ fail.write_text("x")
8009
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env=cli_env)
8010
+ tick()
8011
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8012
+ for needle in ("failed", "Workspace not trusted"):
8013
+ if needle not in status:
8014
+ report(f"{label} a failed start does not show {needle!r}: {status!r}")
8015
+ return 1
8016
+ patrolled = run_keel(rtl, "patrol", env=env).stdout
8017
+ if not re.search(r"risk: .*verify.*hand-off", patrolled):
8018
+ report(f"{label} the patrol does not report the failed hand-off as a risk: {patrolled!r}")
8019
+ return 1
8020
+ if "shift-cli-self-shift" not in {name for name, _ in SCENARIOS}:
8021
+ report(f"{label} scenario is not registered.")
8022
+ return 1
8023
+ report("shift-cli-self-shift scenario passed.")
8024
+ return 0
8025
+
8026
+
7814
8027
  def validate_shift_desktop_wake_overdue_scenario() -> int:
7815
8028
  """`keel shift status` flags a desktop note whose wake is overdue.
7816
8029
 
@@ -24514,7 +24727,7 @@ def validate_update_host_query_timeout_scenario() -> int:
24514
24727
  "KEEL_UPDATE_NPM": str(launchers["npm"]),
24515
24728
  "KEEL_UPDATE_CLAUDE": str(launchers["claude"]),
24516
24729
  "KEEL_UPDATE_CODEX": str(launchers["codex"]),
24517
- "KEEL_UPDATE_QUERY_TIMEOUT_MS": "1500",
24730
+ "KEEL_UPDATE_QUERY_TIMEOUT_MS": "30000",
24518
24731
  "CODEX_HOME": str(tmp / "codex-home"),
24519
24732
  "FAKE_LOG": str(log), "FAKE_STATE": str(state),
24520
24733
  "FAKE_CODEX_SOURCE": str(source),
@@ -24539,12 +24752,13 @@ def validate_update_host_query_timeout_scenario() -> int:
24539
24752
  report(f"{label} a claude plugin list --json that exited 3 does not read failed with exited 3: {claude!r}")
24540
24753
  return 1
24541
24754
 
24542
- result, calls, took = update(env_extra={"FAKE_LIST_SLEEP_CODEX": "10"})
24755
+ # Only the hung case needs a short limit; the others keep 30 s, so load cannot trip them.
24756
+ result, calls, took = update(env_extra={"FAKE_LIST_SLEEP_CODEX": "15", "KEEL_UPDATE_QUERY_TIMEOUT_MS": "4000"})
24543
24757
  codex = line(result.stdout, "codex plugin")
24544
24758
  if "absent" in codex:
24545
24759
  report(f"{label} a hung codex plugin list --json was reported absent: {codex!r}")
24546
24760
  return 1
24547
- for needle in ("failed", "codex plugin list --json", "1.5 s"):
24761
+ for needle in ("failed", "codex plugin list --json", "4 s"):
24548
24762
  if needle not in codex:
24549
24763
  report(f"{label} the hung-query line does not name {needle!r}: {codex!r}")
24550
24764
  return 1
@@ -24557,8 +24771,8 @@ def validate_update_host_query_timeout_scenario() -> int:
24557
24771
  if result.returncode == 0:
24558
24772
  report(f"{label} a failed query left keel --update exiting 0.")
24559
24773
  return 1
24560
- if took > 9:
24561
- report(f"{label} the hung query held keel --update for {took:.1f} s, past its 1.5 s limit.")
24774
+ if took > 20:
24775
+ report(f"{label} the hung query held keel --update for {took:.1f} s, past two 4 s attempts.")
24562
24776
  return 1
24563
24777
 
24564
24778
  result, _, _ = update(env_extra={"KEEL_UPDATE_CODEX": str(tmp / "no-such-codex")})
@@ -24566,7 +24780,7 @@ def validate_update_host_query_timeout_scenario() -> int:
24566
24780
  report(f"{label} a missing codex executable no longer reads absent: {result.stdout!r}")
24567
24781
  return 1
24568
24782
 
24569
- result, _, _ = update("--dry-run", env_extra={"FAKE_LIST_SLEEP_CODEX": "10"})
24783
+ result, _, _ = update("--dry-run", env_extra={"FAKE_LIST_SLEEP_CODEX": "15", "KEEL_UPDATE_QUERY_TIMEOUT_MS": "4000"})
24570
24784
  if result.returncode != 0:
24571
24785
  report(f"{label} --dry-run with a hung query exited {result.returncode}: {result.stdout!r}")
24572
24786
  return 1
@@ -42207,6 +42421,7 @@ SCENARIOS: tuple = (
42207
42421
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
42208
42422
  ("shift-self", validate_shift_self_scenario),
42209
42423
  ("shift-self-wake", validate_shift_self_wake_scenario),
42424
+ ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
42210
42425
  ("owner-language", validate_owner_language_scenario),
42211
42426
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42212
42427
  ("shift-history", validate_shift_history_scenario),
@@ -42227,6 +42442,7 @@ SCENARIOS: tuple = (
42227
42442
  ("resource-lock", validate_resource_lock_scenario),
42228
42443
  ("chat-supersedes", validate_chat_supersedes_scenario),
42229
42444
  ("chat-mention-skips-code", validate_chat_mention_skips_code_scenario),
42445
+ ("chat-wake-now-cli", validate_chat_wake_now_cli_scenario),
42230
42446
  ("chat-ack", validate_chat_ack_scenario),
42231
42447
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
42232
42448
  ("patrol-since-last", validate_patrol_since_last_scenario),
@@ -52,6 +52,7 @@ const USAGE = [
52
52
  "keel chat wake remove (stop waking this worktree's role on this machine)",
53
53
  "keel chat wake status [--json]",
54
54
  "keel chat wake run --once [--worktree <path>] (what the waker's LaunchAgent runs)",
55
+ "keel chat wake now <role> (resume a role whose Claude Code CLI session has ended: claude --bg --resume <its id>)",
55
56
  "Every command takes --repo <path> to act on another repository.",
56
57
  ];
57
58
 
@@ -248,7 +249,11 @@ function postResult(where, record, json) {
248
249
  + "this waits until it is unparked or its session runs again — route anything urgent through the coordinator.");
249
250
  }
250
251
  for (const role of offline) lines.push(`Queued for ${role}: offline; it will see this when its session next starts.`);
251
- for (const entry of asleep) {
252
+ for (const entry of asleep.filter((item) => item.cli)) {
253
+ lines.push(`${entry.role}'s CLI session ${entry.session} has no running process, so this record alone wakes nothing; `
254
+ + `resume it with \`keel chat wake now ${entry.role}\` (#348).`);
255
+ }
256
+ for (const entry of asleep.filter((item) => !item.cli)) {
252
257
  lines.push(`${entry.role}'s desktop session ${entry.session} has no running process, so this record alone wakes nothing (#331). `
253
258
  + notice.wakeStep(entry.session, "You have unread keel chat records; run `keel chat unread`."));
254
259
  }
@@ -676,8 +681,25 @@ function runWake(cwd, options) {
676
681
  if (options.json) out(JSON.stringify(result));
677
682
  return 0;
678
683
  }
684
+ case "now": {
685
+ // One step for a role whose CLI session ended (#348 D3).
686
+ const role = options.positionals[2];
687
+ if (!role) throw new ChatError("keel chat wake now needs a role.");
688
+ store.checkName(role, "Role");
689
+ const where = store.requireLocation(cwd);
690
+ const presence = store.readJsonFile(path.join(where.root, "presence", `${role}.json`));
691
+ if (!presence.cli_session) throw new ChatError(`${role} has recorded no Claude Code CLI session, so there is nothing to resume.`);
692
+ const entry = notice.asleep(where, role);
693
+ if (!entry || !entry.cli) {
694
+ out(`${role}'s CLI session ${presence.cli_session} is running; a record addressed to it wakes it, so nothing was resumed.`);
695
+ return 0;
696
+ }
697
+ const resumed = notice.resumeCli(entry);
698
+ out(`${resumed.ok ? "Resumed" : "Could not resume"} ${role}'s CLI session ${entry.session} in ${entry.worktree}.${resumed.output ? `\n${resumed.output}` : ""}`);
699
+ return resumed.ok ? 0 : 1;
700
+ }
679
701
  default:
680
- throw new ChatError(`Unknown keel chat wake action ${JSON.stringify(action)}: use add, remove, status, or run.`);
702
+ throw new ChatError(`Unknown keel chat wake action ${JSON.stringify(action)}: use add, remove, status, run, or now.`);
681
703
  }
682
704
  }
683
705
 
@@ -97,6 +97,10 @@ function touchPresence(where, role, state = "online", host = null, started = nul
97
97
  ...(state === "offline"
98
98
  ? { desktop_session: previous.desktop_session || null, desktop_pid: previous.desktop_pid || null }
99
99
  : desktopFields()),
100
+ // A Claude Code CLI session and its process, for the same reason (#348 D1).
101
+ ...(state === "offline"
102
+ ? { cli_session: previous.cli_session || null, cli_pid: previous.cli_pid || null, cli_worktree: previous.cli_worktree || null }
103
+ : cliFields(where)),
100
104
  };
101
105
  try {
102
106
  store.writeJsonAtomic(where, presenceFile(where, role), record);
@@ -111,6 +115,13 @@ function desktopFields() {
111
115
  return { desktop_session: id, desktop_pid: require("../shift").desktopProcess() };
112
116
  }
113
117
 
118
+ function cliFields(where) {
119
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
120
+ if (process.env.CLAUDE_CODE_ENTRYPOINT !== "cli" || !id) return { cli_session: null, cli_pid: null, cli_worktree: null };
121
+ const pid = Number(process.env.CLAUDE_PID);
122
+ return { cli_session: id, cli_pid: Number.isInteger(pid) && pid > 1 ? pid : null, cli_worktree: where.worktree };
123
+ }
124
+
114
125
  function running(pid) {
115
126
  try {
116
127
  process.kill(pid, 0);
@@ -124,6 +135,13 @@ function running(pid) {
124
135
  // record until something resumes it (#331 D2, measured in #320).
125
136
  function asleep(where, role) {
126
137
  const record = store.readJsonFile(presenceFile(where, role));
138
+ // An ended CLI session is resumed by `keel chat wake now` (#348 D2).
139
+ if (!record.desktop_session && record.cli_session) {
140
+ const cliPid = Number(record.cli_pid);
141
+ return Number.isInteger(cliPid) && cliPid > 1 && !running(cliPid)
142
+ ? { role, session: record.cli_session, cli: true, worktree: record.cli_worktree || null }
143
+ : null;
144
+ }
127
145
  if (!record.desktop_session) return null;
128
146
  // With no process found when it was recorded, Keel cannot tell, and says nothing.
129
147
  const pid = Number(record.desktop_pid);
@@ -136,6 +154,20 @@ function wakeStep(session, text) {
136
154
  + `then call \`send_message\` to \`${session}\` with ${JSON.stringify(text)}.`;
137
155
  }
138
156
 
157
+ // The prompt an ended CLI session resumes with: a pointer, never the work.
158
+ const CLI_WAKE_PROMPT = "You have unread keel chat records; run keel context, then keel chat unread.";
159
+
160
+ // Resumes a role's recorded CLI session (#348 D3). Only `--bg --resume <id>`
161
+ // and the prompt: any other flag starts a copy with a new session id.
162
+ function resumeCli(entry) {
163
+ const claude = process.env.KEEL_CLAUDE || "claude";
164
+ const result = require("child_process").spawnSync(claude, ["--bg", "--resume", entry.session, CLI_WAKE_PROMPT], {
165
+ cwd: entry.worktree || undefined, encoding: "utf8",
166
+ });
167
+ const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
168
+ return { ok: !result.error && result.status === 0, output: result.error ? result.error.message : output };
169
+ }
170
+
139
171
  // --- parked roles (#316) ------------------------------------------------------------
140
172
 
141
173
  function parkFile(where, role) {
@@ -519,6 +551,7 @@ module.exports = {
519
551
  parkOf,
520
552
  unpark,
521
553
  wakeStep,
554
+ resumeCli,
522
555
  check,
523
556
  bridgeLine,
524
557
  keptFile,
@@ -965,6 +965,16 @@ function readPatrolDeclaration(repo) {
965
965
  return { declared: true, role: block.role, every: block.every, hostTask, model, message, cadence, runner };
966
966
  }
967
967
 
968
+ // `shift: permission_mode:` for the session a CLI hand-off starts (#357 D5).
969
+ const PERMISSION_MODES = ["default", "acceptEdits", "auto", "plan", "bypassPermissions"];
970
+ function readShiftDeclaration(repo) {
971
+ const block = configMap(repo, "shift");
972
+ const mode = block.permission_mode;
973
+ if (mode === undefined) return { permissionMode: "auto", message: null };
974
+ if (PERMISSION_MODES.includes(mode)) return { permissionMode: mode, message: null };
975
+ return { permissionMode: "auto", message: `keel/config.yaml shift: permission_mode \`${mode}\` is not one of ${PERMISSION_MODES.join(", ")}, so it is ignored.` };
976
+ }
977
+
968
978
  function durationSeconds(value) {
969
979
  const match = String(value || "").match(/^(\d+)([smhd])$/);
970
980
  return match ? Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2]] : null;
@@ -987,6 +997,7 @@ module.exports = {
987
997
  readOwnerLanguage,
988
998
  ownerLanguageRule,
989
999
  readPatrolDeclaration,
1000
+ readShiftDeclaration,
990
1001
  durationSeconds,
991
1002
  patrolReminder,
992
1003
  readIssueRoles,
@@ -308,7 +308,11 @@ function nudgeRoles(where, patroller, options) {
308
308
  // A nudge to a desktop session with no running process wakes nothing,
309
309
  // so the coordinator hears it on the first one (#331 D4).
310
310
  const sleeping = sent.some((entry) => entry.role === role) ? notice.asleep(where, role) : null;
311
- if (sleeping) {
311
+ if (sleeping && sleeping.cli) {
312
+ // An ended CLI session is resumed in one step (#348 D5).
313
+ escalations.push(`${role}'s CLI session ${sleeping.session} has no running process, so the nudge wakes nothing: `
314
+ + `resume it with \`keel chat wake now ${role}\`.`);
315
+ } else if (sleeping) {
312
316
  escalations.push(`${role}'s desktop session ${sleeping.session} has no running process, so the nudge wakes nothing: `
313
317
  + notice.wakeStep(sleeping.session, "You have unread keel chat records; run `keel chat unread`."));
314
318
  }
@@ -493,6 +497,8 @@ function runPatrol(argv) {
493
497
  result.risks = [];
494
498
  const quota = quotaRisk(where, options);
495
499
  if (quota) result.risks.push(quota);
500
+ // A CLI hand-off that failed or hangs (#357 D4).
501
+ result.risks.push(...require("./shift").handOffRisks(where));
496
502
  // Near the limit nudges stop, since each wakes a large session (D3).
497
503
  const quiet = options.quota !== null && options.quota >= options.quotaQuietAt;
498
504
  if (options.nudge && quiet) result.paused = `nudges paused: quota at ${options.quota}%`;
package/src/core/shift.js CHANGED
@@ -375,6 +375,14 @@ function desktopSession() {
375
375
  return process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" && id ? id : null;
376
376
  }
377
377
 
378
+ // The Claude Code CLI session's id and process, or null elsewhere (#357 D1).
379
+ function cliSession() {
380
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
381
+ if (process.env.CLAUDE_CODE_ENTRYPOINT !== "cli" || !id) return null;
382
+ const pid = Number(process.env.CLAUDE_PID);
383
+ return { session: id, pid: Number.isInteger(pid) && pid > 1 ? pid : null };
384
+ }
385
+
378
386
  // The desktop session's Claude process: the nearest ancestor whose command's
379
387
  // basename is `claude`. The app's clear stops it, which is what the wake
380
388
  // waits for (D1 of shift-desktop-wake-in-a-minute).
@@ -437,12 +445,15 @@ function ready(where, options) {
437
445
  const stamp = store.isoLocal(new Date());
438
446
  const desktop = desktopSession();
439
447
  const pid = desktop ? desktopProcess() : null;
448
+ const cli = desktop ? null : cliSession();
440
449
  const head = [
441
450
  `# Shift note: ${role || path.basename(where.worktree)}`,
442
451
  "",
443
452
  `Written ${stamp} in ${result.worktree}.`,
444
453
  desktop ? `Desktop session: ${desktop}.` : "",
445
454
  desktop && pid ? `Desktop process: ${pid}.` : "",
455
+ cli ? `CLI session: ${cli.session}.` : "",
456
+ cli && cli.pid ? `CLI process: ${cli.pid}.` : "",
446
457
  // A shift the role started itself; the patrol may nudge it to resume (#307 D4).
447
458
  options.wake ? "Self-initiated: this shift armed `keel shift ready --wake`." : "",
448
459
  !role ? `Started by hand: ${options.forceReason}.` : "",
@@ -464,8 +475,83 @@ function ready(where, options) {
464
475
  store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
465
476
  }
466
477
  }
467
- const waiter = options.wake ? armWake(where, role, since) : null;
468
- return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, startedBy: role ? null : options.forceReason, desktop, pid, worktree: where.worktree };
478
+ // A CLI session cannot clear itself: `keel tick` stops it once idle and
479
+ // starts the next (#357 D1), so nothing waits for a clear.
480
+ const queued = options.wake && cli ? queueHandOff(where, role, cli) : null;
481
+ const waiter = options.wake && !queued ? armWake(where, role, since) : null;
482
+ return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, queued, startedBy: role ? null : options.forceReason, desktop, pid, cli, worktree: where.worktree };
483
+ }
484
+
485
+ // --- the CLI hand-off queue (#357) --------------------------------------------------
486
+
487
+ function queueFile(where, role) {
488
+ return path.join(shiftDir(where), "queue", `${role}.json`);
489
+ }
490
+
491
+ function queueHandOff(where, role, cli) {
492
+ const entry = { role, session: cli.session, pid: cli.pid, worktree: where.worktree, requested_at: store.isoLocal(new Date()), state: "pending" };
493
+ store.writeJsonAtomic(where, queueFile(where, role), entry);
494
+ return entry;
495
+ }
496
+
497
+ function handOffs(where) {
498
+ return safeList(path.join(shiftDir(where), "queue")).filter((name) => name.endsWith(".json")).sort()
499
+ .map((name) => store.readJsonFile(path.join(shiftDir(where), "queue", name))).filter((entry) => entry && entry.role);
500
+ }
501
+
502
+ const SHIFT_START_TEXT = (role) => `${role}: your new shift starts now. Run keel context, then keel shift resume.`;
503
+
504
+ // One step of the waker (#357 D2): a busy old session waits; an idle or gone
505
+ // one is stopped (kept: \`claude attach\` reopens it) and a new session starts.
506
+ function handOver(where) {
507
+ const { readShiftDeclaration } = require("./config");
508
+ const claude = process.env.KEEL_CLAUDE || "claude";
509
+ const pending = handOffs(where).filter((entry) => entry.state === "pending");
510
+ if (!pending.length) return [];
511
+ const listed = spawnSync(claude, ["agents", "--json"], { encoding: "utf8" });
512
+ let sessions = [];
513
+ try {
514
+ sessions = JSON.parse(listed.stdout);
515
+ } catch {
516
+ sessions = [];
517
+ }
518
+ const done = [];
519
+ for (const entry of pending) {
520
+ const row = (Array.isArray(sessions) ? sessions : []).find((item) => item && item.sessionId === entry.session);
521
+ if (row && row.status === "busy") continue;
522
+ // `stop`, `attach` and `logs` take the 8-character job id, not the full
523
+ // session id (`No job matching`, measured 2026-10-19).
524
+ if (row) spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8" });
525
+ const mode = readShiftDeclaration(entry.worktree).permissionMode;
526
+ const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
527
+ cwd: entry.worktree, encoding: "utf8",
528
+ });
529
+ const output = `${started.stdout || ""}`;
530
+ if (!started.error && started.status === 0) {
531
+ const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
532
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
533
+ } else {
534
+ const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
535
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
536
+ }
537
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
538
+ done.push(entry);
539
+ }
540
+ return done;
541
+ }
542
+
543
+ function describeHandOff(entry) {
544
+ const tail = entry.state === "delivered"
545
+ ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
546
+ : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
547
+ return `- ${entry.role}: ${tail}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
548
+ }
549
+
550
+ // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
551
+ function handOffRisks(where, now = Date.now()) {
552
+ return handOffs(where).filter((entry) => entry.state === "failed"
553
+ || (entry.state === "pending" && now - Date.parse(entry.requested_at) > 15 * 60 * 1000))
554
+ .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}` : ` since ${entry.requested_at}`}; see \`keel shift status\``);
469
555
  }
470
556
 
471
557
  // --- the one-shot wake (#293) -------------------------------------------------------
@@ -908,6 +994,11 @@ const CLEAR_HINT = [
908
994
  // Who starts the new session (#293 D3): the coordinator that asked, nobody,
909
995
  // or — without a chat role — the person who opens it.
910
996
  function clearHint(result) {
997
+ if (result.queued) {
998
+ return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session is idle, "
999
+ + `\`keel tick\` stops it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1000
+ + `in ${result.worktree} that runs \`keel shift resume\`. \`keel shift status\` shows the hand-off.`;
1001
+ }
911
1002
  let last;
912
1003
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
913
1004
  else if (result.waiter && result.desktop) {
@@ -1073,7 +1164,10 @@ function runShift(argv) {
1073
1164
  }
1074
1165
  case "status": {
1075
1166
  const rows = status(where);
1076
- out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");
1167
+ const queue = handOffs(where);
1168
+ const text = [rows.length ? rows.map(describe).join("\n") : "No shift change recorded.",
1169
+ ...(queue.length ? ["", "Hand-offs (CLI, run by `keel tick`):", ...queue.map(describeHandOff)] : [])].join("\n");
1170
+ out({ roles: rows, handOffs: queue }, text);
1077
1171
  return 0;
1078
1172
  }
1079
1173
  default:
@@ -1100,4 +1194,4 @@ function waitingFor(repo) {
1100
1194
  }
1101
1195
 
1102
1196
  module.exports = {
1103
- desktopProcess, foundTranscripts, check, describe, runShift, shiftStatus: status, waitingFor };
1197
+ desktopProcess, foundTranscripts, handOver, handOffRisks, check, describe, runShift, shiftStatus: status, waitingFor };
package/src/core/tick.js CHANGED
@@ -41,8 +41,33 @@ function patrolWorktree(where) {
41
41
  return { declaration, worktree: bound[0], why: null };
42
42
  }
43
43
 
44
+ // Roles whose CLI session ended while a record addressed to them waits are
45
+ // resumed once per new record (#348 D4); a parked role is left alone.
46
+ function wakeEnded(where, state) {
47
+ const notice = require("./chat/notice");
48
+ const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))].sort();
49
+ state.woken = state.woken || {};
50
+ const woken = [];
51
+ for (const role of roles) {
52
+ if (notice.parkOf(where, role)) continue;
53
+ const entry = notice.asleep(where, role);
54
+ if (!entry || !entry.cli) continue;
55
+ const waiting = store.unread(where, role).filter((record) => store.wakes(record, role)).map((record) => record.id).sort();
56
+ const newest = waiting[waiting.length - 1];
57
+ if (!newest || (state.woken[role] && state.woken[role] >= newest)) continue;
58
+ const resumed = notice.resumeCli(entry);
59
+ state.woken[role] = newest;
60
+ woken.push({ role, session: entry.session, record: newest, ok: resumed.ok, output: resumed.output });
61
+ }
62
+ return woken;
63
+ }
64
+
44
65
  function tick(where, now = new Date()) {
45
- const result = { patrol: null };
66
+ const result = { patrol: null, woken: [] };
67
+ const wakeState = readState(where);
68
+ result.woken = wakeEnded(where, wakeState);
69
+ result.handedOver = require("./shift").handOver(where);
70
+ if (result.woken.length) store.writeJsonAtomic(where, stateFile(where), { ...readState(where), woken: wakeState.woken });
46
71
  const found = patrolWorktree(where);
47
72
  if (!found.worktree) {
48
73
  result.patrol = { ran: false, why: found.why };
@@ -78,6 +103,12 @@ function tick(where, now = new Date()) {
78
103
  }
79
104
 
80
105
  function render(result) {
106
+ const woke = (result.woken || []).map((w) => `keel tick: ${w.ok ? "resumed" : "could not resume"} ${w.role}'s CLI session ${w.session} for ${w.record}`);
107
+ const handed = (result.handedOver || []).map((h) => `keel tick: ${h.role}'s hand-off ${h.state}${h.new_session ? ` as session ${h.new_session}` : ""}${h.error ? `: ${h.error}` : ""}`);
108
+ return [...handed, ...woke, renderPatrol(result)].join("\n");
109
+ }
110
+
111
+ function renderPatrol(result) {
81
112
  const p = result.patrol;
82
113
  if (!p.ran) return `keel tick: ${p.why}`;
83
114
  const lines = [`keel tick: ran the patrol (exit ${p.exit})${p.next_at ? `; next ${p.next_at} (${p.rule})` : ""}`];