@christang/keel 5.156.0 → 5.158.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.156.0",
3
+ "version": "5.158.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.156.0 -->
1
+ <!-- keel:start version=5.158.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.156.0",
3
+ "version": "5.158.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.156.0",
9
+ "version": "5.158.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.156.0",
5
+ "version": "5.158.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.156.0",
3
+ "version": "5.158.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.156.0",
3
+ "version": "5.158.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.156.0"
53
- PROTOCOL_VERSION = "5.156.0"
52
+ PACKAGE_VERSION = "5.158.0"
53
+ PROTOCOL_VERSION = "5.158.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
@@ -2598,6 +2598,67 @@ def validate_chat_wake_now_cli_scenario() -> int:
2598
2598
  return 0
2599
2599
 
2600
2600
 
2601
+ def validate_two_live_sessions_on_one_role_scenario() -> int:
2602
+ """Issue #369 point 4: two live sessions bound to one role are reported.
2603
+
2604
+ On 2026-10-18 a desktop PM session and its CLI copy both ran as `iecc-pm`
2605
+ in one worktree: both posted under the one name and shared one read
2606
+ cursor, and neither knew. Each session now records itself under the role;
2607
+ with two live ones `keel context`, `keel chat post` and `keel chat unread`
2608
+ say so, and the warning goes once one has ended.
2609
+ """
2610
+ label = "two-live-sessions-on-one-role:"
2611
+ with tempfile.TemporaryDirectory(prefix="keel-twins-369-") as raw:
2612
+ base = Path(raw)
2613
+ rtl, verify, env, _ = shift_scratch(base)
2614
+ write_text(verify / "openspec/specs/.keep", "")
2615
+ other = subprocess.Popen(["sleep", "300"])
2616
+ try:
2617
+ def as_session(sid: str, pid: int) -> dict:
2618
+ return {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": sid, "CLAUDE_PID": str(pid)}
2619
+
2620
+ def start(sid: str, pid: int) -> None:
2621
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify,
2622
+ env=as_session(sid, pid), text=True, capture_output=True, check=False,
2623
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": sid, "source": "startup"}))
2624
+
2625
+ start("sess-a", os.getpid())
2626
+ alone = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
2627
+ if any("live sessions" in w for w in alone.get("warnings", [])):
2628
+ report(f"{label} one session was reported as two: {alone.get('warnings')!r}")
2629
+ return 1
2630
+ start("sess-b", other.pid)
2631
+ context = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
2632
+ warning = next((w for w in context.get("warnings", []) if "live sessions" in w), "")
2633
+ for needle in ("verify", "sess-a", "sess-b", "read cursor"):
2634
+ if needle not in warning:
2635
+ report(f"{label} keel context's warning does not name {needle!r}: {context.get('warnings')!r}")
2636
+ return 1
2637
+ posted = run_keel(verify, "chat", "post", "soc", "hello", env=as_session("sess-a", os.getpid()))
2638
+ if "live sessions" not in posted.stderr:
2639
+ report(f"{label} keel chat post does not warn: {posted.stdout!r} {posted.stderr!r}")
2640
+ return 1
2641
+ read = run_keel(verify, "chat", "unread", "--json", env=as_session("sess-a", os.getpid()))
2642
+ if "live sessions" not in read.stderr:
2643
+ report(f"{label} keel chat unread does not warn: {read.stderr!r}")
2644
+ return 1
2645
+ json.loads(read.stdout)
2646
+ other.kill()
2647
+ other.wait()
2648
+ after = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
2649
+ if any("live sessions" in w for w in after.get("warnings", [])):
2650
+ report(f"{label} the warning stayed after one session ended: {after.get('warnings')!r}")
2651
+ return 1
2652
+ finally:
2653
+ if other.poll() is None:
2654
+ other.kill()
2655
+ if "two-live-sessions-on-one-role" not in {name for name, _ in SCENARIOS}:
2656
+ report(f"{label} scenario is not registered.")
2657
+ return 1
2658
+ report("two-live-sessions-on-one-role scenario passed.")
2659
+ return 0
2660
+
2661
+
2601
2662
  def validate_chat_supersedes_scenario() -> int:
2602
2663
  """Issue #252: a record supersedes its author's earlier one.
2603
2664
 
@@ -7907,6 +7968,123 @@ def validate_shift_start_desktop_scenario() -> int:
7907
7968
  return 0
7908
7969
 
7909
7970
 
7971
+ def validate_shift_cli_self_shift_scenario() -> int:
7972
+ """Issue #357 on the CLI (owner, 2026-10-19): stop the old session, start a new one.
7973
+
7974
+ A CLI session cannot clear itself. `keel shift ready --wake` there queues
7975
+ the hand-off; `keel tick` waits until the old session is idle, stops it
7976
+ (kept: `claude attach` reopens it), and starts a new session in the role's
7977
+ worktree that runs `keel shift resume`. `keel shift status` shows the
7978
+ queue, and a failed start is a patrol risk.
7979
+ """
7980
+ label = "shift-cli-self-shift:"
7981
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
7982
+ with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
7983
+ base = Path(raw)
7984
+ rtl, verify, env, _ = shift_scratch(base)
7985
+ calls, agents, fail = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start"
7986
+ fake = base / "fake-claude"
7987
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
7988
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
7989
+ f"if sys.argv[1:3] == ['agents', '--json']:\n print(open({str(agents)!r}).read()); sys.exit(0)\n"
7990
+ 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"
7991
+ "if sys.argv[1:2] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
7992
+ "print('stopped')\n")
7993
+ fake.chmod(0o755)
7994
+ env = {**env, "KEEL_CLAUDE": str(fake)}
7995
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
7996
+
7997
+ def agents_status(status: str) -> None:
7998
+ # The measured shape: `sessionId` is the full id, `id` the job id `stop` and `attach` take.
7999
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
8000
+ "pid": os.getpid(), "status": status, "cwd": str(verify)}]))
8001
+
8002
+ def made(kind: str) -> list[dict]:
8003
+ rows = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8004
+ return [r for r in rows if (r["argv"][:1] == ["stop"] if kind == "stop" else r["argv"][:1] == ["--bg"])]
8005
+
8006
+ def tick() -> subprocess.CompletedProcess[str]:
8007
+ return run_keel(verify, "tick", "--repo", str(rtl), env=env)
8008
+
8009
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
8010
+ if readied.returncode != 0:
8011
+ report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
8012
+ return 1
8013
+ if "keel tick" not in readied.stdout:
8014
+ report(f"{label} ready --wake in a CLI session does not say keel tick will hand over: {readied.stdout!r}")
8015
+ return 1
8016
+ note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
8017
+ if not note:
8018
+ report(f"{label} ready --wake stored no note for verify.")
8019
+ return 1
8020
+ if f"CLI session: {OLD}." not in note.read_text(encoding="utf-8"):
8021
+ report(f"{label} the note does not record the CLI session.")
8022
+ return 1
8023
+
8024
+ agents_status("busy")
8025
+ tick()
8026
+ if made("stop"):
8027
+ report(f"{label} a tick stopped the old session while it was busy: {made('stop')!r}")
8028
+ return 1
8029
+ if made("start"):
8030
+ report(f"{label} a tick started a session while the old one was busy: {made('start')!r}")
8031
+ return 1
8032
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8033
+ if "pending" not in status:
8034
+ report(f"{label} shift status does not show the pending hand-off: {status!r}")
8035
+ return 1
8036
+
8037
+ agents_status("idle")
8038
+ tick()
8039
+ stops, starts = made("stop"), made("start")
8040
+ if [s["argv"] for s in stops] != [["stop", OLD[:8]]]:
8041
+ report(f"{label} the idle old session was not stopped once: {stops!r}")
8042
+ return 1
8043
+ if len(starts) != 1:
8044
+ report(f"{label} the new session was not started once: {starts!r}")
8045
+ return 1
8046
+ if starts[0]["argv"][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]:
8047
+ report(f"{label} the new session was not started as --bg -n verify --permission-mode auto: {starts!r}")
8048
+ return 1
8049
+ if "keel shift resume" not in starts[0]["argv"][-1]:
8050
+ report(f"{label} the new session's prompt does not name keel shift resume: {starts[0]['argv']!r}")
8051
+ return 1
8052
+ if "--resume" in starts[0]["argv"]:
8053
+ report(f"{label} the new session resumes an old one instead of starting fresh: {starts[0]['argv']!r}")
8054
+ return 1
8055
+ if os.path.realpath(starts[0]["cwd"]) != os.path.realpath(verify):
8056
+ report(f"{label} the new session started in {starts[0]['cwd']}, not verify's worktree.")
8057
+ return 1
8058
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8059
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}"):
8060
+ if needle not in status:
8061
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {status!r}")
8062
+ return 1
8063
+ tick()
8064
+ if len(made("start")) != 1:
8065
+ report(f"{label} a second tick started another session.")
8066
+ return 1
8067
+
8068
+ # A start that fails stays visible and is a patrol risk.
8069
+ fail.write_text("x")
8070
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env=cli_env)
8071
+ tick()
8072
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8073
+ for needle in ("failed", "Workspace not trusted"):
8074
+ if needle not in status:
8075
+ report(f"{label} a failed start does not show {needle!r}: {status!r}")
8076
+ return 1
8077
+ patrolled = run_keel(rtl, "patrol", env=env).stdout
8078
+ if not re.search(r"risk: .*verify.*hand-off", patrolled):
8079
+ report(f"{label} the patrol does not report the failed hand-off as a risk: {patrolled!r}")
8080
+ return 1
8081
+ if "shift-cli-self-shift" not in {name for name, _ in SCENARIOS}:
8082
+ report(f"{label} scenario is not registered.")
8083
+ return 1
8084
+ report("shift-cli-self-shift scenario passed.")
8085
+ return 0
8086
+
8087
+
7910
8088
  def validate_shift_desktop_wake_overdue_scenario() -> int:
7911
8089
  """`keel shift status` flags a desktop note whose wake is overdue.
7912
8090
 
@@ -42304,6 +42482,7 @@ SCENARIOS: tuple = (
42304
42482
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
42305
42483
  ("shift-self", validate_shift_self_scenario),
42306
42484
  ("shift-self-wake", validate_shift_self_wake_scenario),
42485
+ ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
42307
42486
  ("owner-language", validate_owner_language_scenario),
42308
42487
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42309
42488
  ("shift-history", validate_shift_history_scenario),
@@ -42324,6 +42503,7 @@ SCENARIOS: tuple = (
42324
42503
  ("resource-lock", validate_resource_lock_scenario),
42325
42504
  ("chat-supersedes", validate_chat_supersedes_scenario),
42326
42505
  ("chat-mention-skips-code", validate_chat_mention_skips_code_scenario),
42506
+ ("two-live-sessions-on-one-role", validate_two_live_sessions_on_one_role_scenario),
42327
42507
  ("chat-wake-now-cli", validate_chat_wake_now_cli_scenario),
42328
42508
  ("chat-ack", validate_chat_ack_scenario),
42329
42509
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
@@ -738,6 +738,11 @@ function runChat(argv) {
738
738
  migrateIfNeeded(where);
739
739
  const role = store.currentRole(where);
740
740
  if (role) notice.touchPresence(where, role);
741
+ // Two live sessions on one role share its name and cursor (#369 D3).
742
+ if (role && ["post", "dm", "todo", "unread", "read"].includes(options.positionals[0])) {
743
+ const twins = notice.twinWarning(where, role);
744
+ if (twins) process.stderr.write(`keel chat: ${twins}\n`);
745
+ }
741
746
  return dispatch(where, options);
742
747
  } catch (error) {
743
748
  if (!(error instanceof ChatError)) throw error;
@@ -104,11 +104,65 @@ function touchPresence(where, role, state = "online", host = null, started = nul
104
104
  };
105
105
  try {
106
106
  store.writeJsonAtomic(where, presenceFile(where, role), record);
107
+ touchSession(where, role, state);
107
108
  } catch {
108
109
  // Presence is a convenience: failing to record it must not fail a command.
109
110
  }
110
111
  }
111
112
 
113
+ // --- one role, several sessions (#369 point 4) ------------------------------------
114
+
115
+ function sessionsFile(where, role) {
116
+ return path.join(where.root, "presence", `${role}.sessions.json`);
117
+ }
118
+
119
+ function thisSession() {
120
+ if (process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" && process.env.CLAUDE_CODE_HOST_SESSION_ID) {
121
+ return { id: process.env.CLAUDE_CODE_HOST_SESSION_ID, pid: require("../shift").desktopProcess(), host: "claude-desktop" };
122
+ }
123
+ if (process.env.CLAUDE_CODE_SESSION_ID) {
124
+ const pid = Number(process.env.CLAUDE_PID);
125
+ return { id: process.env.CLAUDE_CODE_SESSION_ID, pid: Number.isInteger(pid) && pid > 1 ? pid : null, host: "claude-code" };
126
+ }
127
+ return null;
128
+ }
129
+
130
+ const SESSION_STALE_MS = 24 * 60 * 60 * 1000;
131
+ const SESSION_RECENT_MS = 30 * 60 * 1000;
132
+
133
+ function sessionLive(entry, now) {
134
+ const pid = Number(entry.pid);
135
+ if (Number.isInteger(pid) && pid > 1) return running(pid);
136
+ return now - Date.parse(entry.last_active || "") < SESSION_RECENT_MS;
137
+ }
138
+
139
+ // Each session records itself, so two on one role are visible (D1); an
140
+ // ended or stale one is dropped.
141
+ function touchSession(where, role, state) {
142
+ const self = thisSession();
143
+ const file = sessionsFile(where, role);
144
+ const sessions = store.readJsonFile(file);
145
+ const now = Date.now();
146
+ for (const [id, entry] of Object.entries(sessions)) {
147
+ const pid = Number(entry.pid);
148
+ const ended = Number.isInteger(pid) && pid > 1 && !running(pid);
149
+ if (ended || now - Date.parse(entry.last_active || "") > SESSION_STALE_MS) delete sessions[id];
150
+ }
151
+ if (self && state === "offline") delete sessions[self.id];
152
+ else if (self) sessions[self.id] = { pid: self.pid, worktree: where.worktree, host: self.host, last_active: store.isoLocal(new Date()) };
153
+ if (!self && !Object.keys(sessions).length && !fs.existsSync(file)) return;
154
+ store.writeJsonAtomic(where, file, sessions);
155
+ }
156
+
157
+ // The warning for two or more live sessions on a role (D3), or null.
158
+ function twinWarning(where, role, now = Date.now()) {
159
+ const live = Object.entries(store.readJsonFile(sessionsFile(where, role))).filter(([, entry]) => sessionLive(entry, now));
160
+ if (live.length < 2) return null;
161
+ const named = live.map(([id, entry]) => `${id} (pid ${entry.pid || "unknown"}, ${entry.worktree || "unknown worktree"})`).join(", ");
162
+ return `${live.length} live sessions are bound to role ${role}: ${named}. They post under one name and share one read cursor, `
163
+ + "so one can hide unread records from the other; stop one, or bind it to another role with `keel chat role --set`.";
164
+ }
165
+
112
166
  function desktopFields() {
113
167
  const id = process.env.CLAUDE_CODE_HOST_SESSION_ID;
114
168
  if (process.env.CLAUDE_CODE_ENTRYPOINT !== "claude-desktop" || !id) return { desktop_session: null, desktop_pid: null };
@@ -552,6 +606,7 @@ module.exports = {
552
606
  unpark,
553
607
  wakeStep,
554
608
  resumeCli,
609
+ twinWarning,
555
610
  check,
556
611
  bridgeLine,
557
612
  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,
@@ -871,6 +871,12 @@ function resolveContext(repo, options) {
871
871
  context.ownerLanguage = language.tag;
872
872
  context.ownerLanguageRule = ownerLanguageRule(language.tag);
873
873
  }
874
+ // Two live sessions on one role post as one and share a cursor (#369).
875
+ if (context.role) {
876
+ const chatWhere = require("./chat/store").locate(repo);
877
+ const twins = chatWhere ? require("./chat/notice").twinWarning(chatWhere, context.role) : null;
878
+ if (twins) context.warnings.push(twins);
879
+ }
874
880
  // The patrolling role is reminded to re-arm its schedule (#260).
875
881
  const patrol = readPatrolDeclaration(repo);
876
882
  if (patrol.message) context.warnings.push(patrol.message);
@@ -497,6 +497,8 @@ function runPatrol(argv) {
497
497
  result.risks = [];
498
498
  const quota = quotaRisk(where, options);
499
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));
500
502
  // Near the limit nudges stop, since each wakes a large session (D3).
501
503
  const quiet = options.quota !== null && options.quota >= options.quotaQuietAt;
502
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
@@ -66,6 +66,7 @@ function tick(where, now = new Date()) {
66
66
  const result = { patrol: null, woken: [] };
67
67
  const wakeState = readState(where);
68
68
  result.woken = wakeEnded(where, wakeState);
69
+ result.handedOver = require("./shift").handOver(where);
69
70
  if (result.woken.length) store.writeJsonAtomic(where, stateFile(where), { ...readState(where), woken: wakeState.woken });
70
71
  const found = patrolWorktree(where);
71
72
  if (!found.worktree) {
@@ -103,7 +104,8 @@ function tick(where, now = new Date()) {
103
104
 
104
105
  function render(result) {
105
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}`);
106
- return [...woke, renderPatrol(result)].join("\n");
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");
107
109
  }
108
110
 
109
111
  function renderPatrol(result) {