@christang/keel 5.212.0 → 5.214.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.212.0",
3
+ "version": "5.214.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.212.0 -->
1
+ <!-- keel:start version=5.214.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.212.0",
3
+ "version": "5.214.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.212.0",
9
+ "version": "5.214.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.212.0",
5
+ "version": "5.214.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.212.0",
3
+ "version": "5.214.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.212.0",
3
+ "version": "5.214.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",
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.212.0"
38
+ PACKAGE_VERSION = "5.214.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.212.0"
41
+ PROTOCOL_VERSION = "5.214.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -425,6 +425,8 @@ SCENARIOS: tuple = (
425
425
  ("shift-cli-keeps-old-sessions", shift.validate_shift_cli_keeps_old_sessions_scenario),
426
426
  ("shift-resume-removes-old-sessions", shift.validate_shift_resume_removes_old_sessions_scenario),
427
427
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
428
+ ("shift-cli-keeps-worktree-in-use", shift.validate_shift_cli_keeps_worktree_in_use_scenario),
429
+ ("shift-cli-names-failed-removal", shift.validate_shift_cli_names_failed_removal_scenario),
428
430
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
429
431
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
430
432
  ("shift-cli-handover-claims-once", shift.validate_shift_cli_handover_claims_once_scenario),
@@ -459,6 +461,7 @@ SCENARIOS: tuple = (
459
461
  ("chat-supersedes", chat.validate_chat_supersedes_scenario),
460
462
  ("chat-mention-skips-code", chat.validate_chat_mention_skips_code_scenario),
461
463
  ("two-live-sessions-on-one-role", shift.validate_two_live_sessions_on_one_role_scenario),
464
+ ("moved-session-is-not-a-twin", shift.validate_moved_session_is_not_a_twin_scenario),
462
465
  ("chat-role-rename", chat.validate_chat_role_rename_scenario),
463
466
  ("chat-wake-now-cli", chat.validate_chat_wake_now_cli_scenario),
464
467
  ("chat-hook-follows-session-worktree", chat.validate_chat_hook_follows_session_worktree_scenario),
@@ -112,6 +112,66 @@ def validate_two_live_sessions_on_one_role_scenario() -> int:
112
112
  return 0
113
113
 
114
114
 
115
+ def validate_moved_session_is_not_a_twin_scenario() -> int:
116
+ """Issue #490: a session that bound another role is not a twin of the first.
117
+
118
+ In ChipSTRIDE three sessions started in the main checkout, bound to
119
+ `chipstride`; two then entered their own worktrees and ran `keel chat role
120
+ --set`. `chipstride.sessions.json` kept all three, so every command warned
121
+ of three live `chipstride` sessions when there was one.
122
+ """
123
+ label = "moved-session-is-not-a-twin:"
124
+ with tempfile.TemporaryDirectory(prefix="keel-twins-490-") as raw:
125
+ base = Path(raw)
126
+ rtl, verify, env, _ = shift_scratch(base)
127
+ write_text(verify / "openspec/specs/.keep", "")
128
+ fe = base / "fe"
129
+ subprocess.run(["git", "worktree", "add", "-q", "-b", "fe", str(fe)], cwd=rtl, check=True, capture_output=True)
130
+ # Each session's transcript starts in the worktree it started in;
131
+ # `EnterWorktree` later gives sess-b one in fe as well.
132
+ config = base / "claude-config"
133
+ for sid in ("sess-a", "sess-b"):
134
+ write_text(config / "projects" / host_project_name(verify) / f"{sid}.jsonl", "{}\n")
135
+ other = subprocess.Popen(["sleep", "300"])
136
+ try:
137
+ def as_session(sid: str, pid: int) -> dict:
138
+ return {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": sid, "CLAUDE_PID": str(pid),
139
+ "CLAUDE_CONFIG_DIR": str(config)}
140
+
141
+ for sid, pid in (("sess-a", os.getpid()), ("sess-b", other.pid)):
142
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify,
143
+ env=as_session(sid, pid), text=True, capture_output=True, check=False,
144
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": sid, "source": "startup"}))
145
+ before = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
146
+ if not any("live sessions" in w for w in before.get("warnings", [])):
147
+ report(f"{label} the fixture does not list two live verify sessions before sess-b moves: {before.get('warnings')!r}")
148
+ return 1
149
+ write_text(config / "projects" / host_project_name(fe) / "sess-b.jsonl", "{}\n")
150
+ moved = run_keel(fe, "chat", "role", "--set", "fe", env=as_session("sess-b", other.pid))
151
+ if moved.returncode != 0:
152
+ report(f"{label} keel chat role --set fe exited {moved.returncode}: {moved.stderr!r}")
153
+ return 1
154
+ if "Recorded this session" not in moved.stdout:
155
+ report(f"{label} sess-b's --set fe did not record it as fe's session: {moved.stdout!r}")
156
+ return 1
157
+ context = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
158
+ twins = [w for w in context.get("warnings", []) if "live sessions" in w]
159
+ if twins:
160
+ report(f"{label} sess-b, now fe's, is still reported as a second verify session: {twins!r}")
161
+ return 1
162
+ if other.poll() is not None:
163
+ report(f"{label} sess-b's process ended before the check, so it proves nothing.")
164
+ return 1
165
+ finally:
166
+ if other.poll() is None:
167
+ other.kill()
168
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
169
+ report(f"{label} the scenario registry does not include it.")
170
+ return 1
171
+ report(f"{label.rstrip(':')} scenario passed.")
172
+ return 0
173
+
174
+
115
175
  def validate_patrol_rearm_scenario() -> int:
116
176
  """Issue #260: the patrolling role is reminded to re-arm its schedule.
117
177
 
@@ -3245,6 +3305,8 @@ def running(pid):
3245
3305
  return True
3246
3306
  rows = json.loads(open(agents).read())
3247
3307
  record = {'argv': argv}
3308
+ if argv[:1] == ['rm'] and os.environ.get('FAKE_RM_FAIL'):
3309
+ open(calls, 'a').write(json.dumps(record) + '\\n'); sys.stderr.write(os.environ['FAKE_RM_FAIL'] + '\\n'); sys.exit(1)
3248
3310
  if argv[:1] == ['rm']:
3249
3311
  gone = [row for row in rows if row['id'] == argv[1]]
3250
3312
  record['alive'] = bool(gone) and bool(gone[0].get('_pid')) and running(gone[0]['_pid'])
@@ -3334,6 +3396,98 @@ def validate_shift_cli_removes_after_exit_scenario() -> int:
3334
3396
  return 0
3335
3397
 
3336
3398
 
3399
+ def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None, **fake_env: str):
3400
+ """A delivered hand-over of `5b14fbae` from verify's worktree under the contract fake (#492).
3401
+
3402
+ Returns the `rm` calls the fake logged and `keel shift status` from rtl.
3403
+ The row's `cwd` and the host's recorded `worktreePath` are the inputs.
3404
+ """
3405
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
3406
+ rtl, verify, env, _ = shift_scratch(base)
3407
+ row_cwd = {"rtl": rtl, "verify": verify}[str(row_cwd)]
3408
+ agents, calls, fake, config = base / "agents.json", base / "calls.jsonl", base / "fake-claude", base / "claude"
3409
+ write_text(fake, HANDOVER_CONTRACT_FAKE)
3410
+ fake.chmod(0o755)
3411
+ write_text(config / "projects" / host_project_name(verify) / f"{OLD}.jsonl",
3412
+ json.dumps({"type": "user", "message": {"role": "user", "content": "carry on"}}) + "\n")
3413
+ if worktree_path is not None:
3414
+ write_text(config / "jobs" / OLD[:8] / "state.json", json.dumps({"sessionId": OLD, "cwd": str(row_cwd), "worktreePath": str(verify)}))
3415
+ process = detached_sleeper()
3416
+ try:
3417
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
3418
+ "status": "idle", "state": "done", "pid": process, "cwd": str(row_cwd),
3419
+ "startedAt": 1792500000000}]))
3420
+ calls.write_text("")
3421
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config), "FAKE_AGENTS": str(agents),
3422
+ "FAKE_CALLS": str(calls), "FAKE_STOP_MODE": "late", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
3423
+ "KEEL_SHIFT_EXIT_WAIT_MS": "5000", **fake_env}
3424
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(process)}
3425
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R032", env=cli_env)
3426
+ if readied.returncode != 0:
3427
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
3428
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
3429
+ removals = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
3430
+ return removals, run_keel(rtl, "shift", "status", env=env).stdout, verify
3431
+ finally:
3432
+ with contextlib.suppress(OSError):
3433
+ os.kill(process, signal.SIGKILL)
3434
+
3435
+
3436
+ def validate_shift_cli_keeps_worktree_in_use_scenario() -> int:
3437
+ """Issue #492: a hand-over never `claude rm`s a session whose worktree the new shift uses.
3438
+
3439
+ In ChipSTRIDE the old session had created the worktree with `EnterWorktree`,
3440
+ and the new shift started in it; `claude rm` deletes a session's worktree.
3441
+ Keel skipped the session silently and status called it kept.
3442
+ """
3443
+ label = "shift-cli-keeps-worktree-in-use:"
3444
+ with tempfile.TemporaryDirectory(prefix="keel-shift-492a-") as raw:
3445
+ try:
3446
+ removals, status, verify = handover_old_session(Path(raw), Path("rtl"), Path("verify"))
3447
+ except RuntimeError as error:
3448
+ report(f"{label} {error}")
3449
+ return 1
3450
+ if any(r["argv"][1:2] == ["5b14fbae"] for r in removals):
3451
+ report(f"{label} the session whose worktree the new shift uses was removed with claude rm: {removals!r}")
3452
+ return 1
3453
+ for needle in ("not removed", str(verify), "claude rm would delete it", "claude attach 5b14fbae"):
3454
+ if needle not in status:
3455
+ report(f"{label} shift status does not name {needle!r}: {status!r}")
3456
+ return 1
3457
+ if "old session kept" in status:
3458
+ report(f"{label} shift status calls the session kept though nothing declared keeping it: {status!r}")
3459
+ return 1
3460
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3461
+ report(f"{label} the scenario registry does not include it.")
3462
+ return 1
3463
+ report(f"{label.rstrip(':')} scenario passed.")
3464
+ return 0
3465
+
3466
+
3467
+ def validate_shift_cli_names_failed_removal_scenario() -> int:
3468
+ """Issue #492: a `claude rm` that fails is reported with the host's message, not as kept."""
3469
+ label = "shift-cli-names-failed-removal:"
3470
+ with tempfile.TemporaryDirectory(prefix="keel-shift-492b-") as raw:
3471
+ try:
3472
+ _removals, status, _verify = handover_old_session(Path(raw), Path("verify"), None,
3473
+ FAKE_RM_FAIL="worktree has unpushed commits")
3474
+ except RuntimeError as error:
3475
+ report(f"{label} {error}")
3476
+ return 1
3477
+ for needle in ("not removed", "claude rm exited 1", "worktree has unpushed commits"):
3478
+ if needle not in status:
3479
+ report(f"{label} shift status does not name {needle!r}: {status!r}")
3480
+ return 1
3481
+ if "old session kept" in status:
3482
+ report(f"{label} shift status calls a failed removal kept: {status!r}")
3483
+ return 1
3484
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3485
+ report(f"{label} the scenario registry does not include it.")
3486
+ return 1
3487
+ report(f"{label.rstrip(':')} scenario passed.")
3488
+ return 0
3489
+
3490
+
3337
3491
  def validate_shift_cli_names_host_failure_scenario() -> int:
3338
3492
  """Issue #408: a hand-off the host cannot be asked about says why it waits."""
3339
3493
  label = "shift-cli-names-host-failure:"
@@ -154,9 +154,21 @@ function touchSession(where, role, state) {
154
154
  store.writeJsonAtomic(where, file, sessions);
155
155
  }
156
156
 
157
+ // Whether a listed session is still the role's: one whose own record names
158
+ // another role has bound that one since, and is no twin here (#490 D1). With
159
+ // no record it cannot be told from a twin, so it counts (D2).
160
+ function sessionStillRole(where, role, id) {
161
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(id)) return true;
162
+ const file = path.join(where.root, "sessions", `${id}.json`);
163
+ if (!fs.existsSync(file)) return true;
164
+ const recorded = store.readJsonFile(file).role;
165
+ return !recorded || recorded === role;
166
+ }
167
+
157
168
  // The warning for two or more live sessions on a role (D3), or null.
158
169
  function twinWarning(where, role, now = Date.now()) {
159
- const live = Object.entries(store.readJsonFile(sessionsFile(where, role))).filter(([, entry]) => sessionLive(entry, now));
170
+ const live = Object.entries(store.readJsonFile(sessionsFile(where, role)))
171
+ .filter(([id, entry]) => sessionLive(entry, now) && sessionStillRole(where, role, id));
160
172
  if (live.length < 2) return null;
161
173
  const named = live.map(([id, entry]) => `${id} (pid ${entry.pid || "unknown"}, ${entry.worktree || "unknown worktree"})`).join(", ");
162
174
  return `${live.length} live sessions are bound to role ${role}: ${named}. They post under one name and share one read cursor, `
package/src/core/shift.js CHANGED
@@ -637,33 +637,80 @@ function keptCopyOf(where, role, transcript) {
637
637
  // slot and stays (#401). A session is the role's when it ran in a bound
638
638
  // worktree, or when Keel keeps its transcript under the role: a renamed or
639
639
  // moved worktree leaves a `cwd` no binding names (#462 D2).
640
+ //
641
+ // `claude rm` also deletes the worktree a session created (#492 F4), so a
642
+ // session whose own worktree is in use stays; every session left listed is
643
+ // returned with its reason, which `keel shift status` names (#492 D3, D4).
640
644
  function removeOldSessions(claude, where, entry, keep) {
641
- const bound = new Set(Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
642
- .filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
645
+ const roles = store.readJsonFile(path.join(where.root, "roles.json"));
646
+ const bound = new Set(Object.entries(roles).filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
643
647
  const listed = listAgents(claude);
644
- if (!listed) return [];
648
+ const own = entry.session ? entry.session.slice(0, 8) : null;
649
+ if (!listed) return { removed: [], notRemoved: own ? [{ id: own, reason: "`claude agents` could not be read" }] : [] };
645
650
  const { keptFile } = require("./chat/notice");
646
- const roles = (row) => bound.has(realpath(row.cwd)) || fs.existsSync(keptFile(where, entry.role, `${row.sessionId}.jsonl`));
651
+ const idOf = (row) => row.id || row.sessionId.slice(0, 8);
652
+ // The session the hand-off names is the role's wherever its row says it ran (#492 D1).
653
+ const isRoles = (row) => row.sessionId === entry.session || bound.has(realpath(row.cwd))
654
+ || fs.existsSync(keptFile(where, entry.role, `${row.sessionId}.jsonl`));
647
655
  const old = listed
648
- .filter((row) => row && row.kind === "background" && !row.status && row.cwd && row.sessionId && roles(row)
656
+ .filter((row) => row && row.kind === "background" && !row.status && row.cwd && row.sessionId && isRoles(row)
649
657
  && row.id !== entry.new_session)
650
- .map((row) => ({ row, transcript: hostTranscript(row.cwd, row.sessionId),
651
- kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) }))
658
+ .map((row) => {
659
+ const worktree = hostWorktree(row);
660
+ return { row, worktree, transcript: hostTranscript(row.cwd, row.sessionId) || (worktree && hostTranscript(worktree, row.sessionId)),
661
+ kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) };
662
+ })
652
663
  .filter(({ transcript, kept }) => transcript || fs.existsSync(kept))
653
664
  .sort((a, b) => (Number(b.row.startedAt) || 0) - (Number(a.row.startedAt) || 0));
665
+ // Worktrees in use: the hand-off's, every bound one, and each other listed session's (#492 D2).
666
+ const inUse = (worktree, row) => {
667
+ const real = realpath(worktree);
668
+ if (entry.worktree && realpath(entry.worktree) === real) return "the new shift's worktree";
669
+ const binding = Object.entries(roles).find(([tree]) => realpath(tree) === real);
670
+ if (binding) return `bound to role ${binding[1]}`;
671
+ const other = listed.find((r) => r && r !== row && r.cwd && realpath(r.cwd) === real);
672
+ return other ? `session ${idOf(other)} runs there` : null;
673
+ };
654
674
  const removed = [];
655
- for (const { row, transcript } of old.slice(keep)) {
675
+ const notRemoved = old.slice(0, keep).map(({ row }) => ({ id: idOf(row), reason: "kept by `shift: keep_old_sessions`" }));
676
+ for (const { row, worktree, transcript } of old.slice(keep)) {
656
677
  // Never a session whose process still runs (#408 D1): the one just handed
657
678
  // over gets a bounded wait for the process its note recorded; any other
658
679
  // still running is left for the next hand-over.
659
680
  const handedOver = row.sessionId === entry.session;
660
681
  const pid = Number(handedOver ? entry.pid : row.pid);
661
- if (handedOver ? !waitForExit(pid, envMs("KEEL_SHIFT_EXIT_WAIT_MS", 15 * 1000)) : processRunning(pid)) continue;
662
- if (transcript && !keptCopyOf(where, entry.role, transcript)) continue;
663
- const gone = spawnSync(claude, ["rm", row.id || row.sessionId.slice(0, 8)], { encoding: "utf8", timeout: hostTimeout() });
664
- if (!gone.error && gone.status === 0) removed.push(row.id || row.sessionId.slice(0, 8));
682
+ if (handedOver ? !waitForExit(pid, envMs("KEEL_SHIFT_EXIT_WAIT_MS", 15 * 1000)) : processRunning(pid)) {
683
+ notRemoved.push({ id: idOf(row), reason: "its process was still running" });
684
+ continue;
685
+ }
686
+ if (transcript && !keptCopyOf(where, entry.role, transcript)) {
687
+ notRemoved.push({ id: idOf(row), reason: "Keel could not copy its transcript" });
688
+ continue;
689
+ }
690
+ const using = worktree && fs.existsSync(worktree) ? inUse(worktree, row) : null;
691
+ if (using) {
692
+ notRemoved.push({ id: idOf(row), reason: `its worktree ${worktree} is in use (${using}), and claude rm would delete it` });
693
+ continue;
694
+ }
695
+ const gone = spawnSync(claude, ["rm", idOf(row)], { encoding: "utf8", timeout: hostTimeout() });
696
+ if (!gone.error && gone.status === 0) removed.push(idOf(row));
697
+ else {
698
+ const said = String(gone.stderr || gone.stdout || (gone.error && gone.error.message) || "").trim().split("\n")[0];
699
+ notRemoved.push({ id: idOf(row), reason: `claude rm exited ${gone.error ? "with an error" : gone.status}${said ? `: ${said}` : ""}` });
700
+ }
665
701
  }
666
- return removed;
702
+ return { removed, notRemoved };
703
+ }
704
+
705
+ // The worktree the host records for a session it created one for — with
706
+ // `EnterWorktree` or `claude --bg -w` — which `claude agents` does not show
707
+ // and `claude rm` deletes (#492 F3). Null when the host recorded none.
708
+ function hostWorktree(row) {
709
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
710
+ const id = row.id || (row.sessionId || "").slice(0, 8);
711
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(id)) return null;
712
+ const recorded = store.readJsonFile(path.join(config, "jobs", id, "state.json")).worktreePath;
713
+ return typeof recorded === "string" && recorded ? recorded : null;
667
714
  }
668
715
 
669
716
  // One runner at a time per role (#388 D2): the waiter and the tick both carry
@@ -723,7 +770,9 @@ function deliver(claude, where, entry, id, name, adopted) {
723
770
  Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
724
771
  for (const key of ["error", "failed_at", "runner_pid"]) delete entry[key];
725
772
  if (adopted) entry.adopted = true;
726
- entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
773
+ const swept = removeOldSessions(claude, where, entry, declared.keepOldSessions);
774
+ entry.removed = swept.removed;
775
+ entry.not_removed = swept.notRemoved;
727
776
  if (declared.message) entry.notice = declared.message;
728
777
  store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
729
778
  return entry;
@@ -856,9 +905,14 @@ function describeHandOff(entry) {
856
905
  const removed = (entry.removed || []).length ? `; older sessions removed from \`claude agents\` (transcripts kept by Keel): ${entry.removed.join(", ")}` : "";
857
906
  const notice = entry.notice ? `; ${entry.notice}` : "";
858
907
  const own = entry.session.slice(0, 8);
908
+ const stayed = (entry.not_removed || []).find((item) => item.id === own);
909
+ const revives = `it stays in \`claude agents\`, and opening it (\`claude attach ${own}\`) brings it back beside the new shift`;
910
+ // Kept only when `keep_old_sessions` kept it; otherwise the recorded reason (#492 D4).
859
911
  const reopen = (entry.removed || []).includes(own)
860
912
  ? `old session removed, its conversation kept: \`keel shift history ${entry.role} --show ${own}\``
861
- : `old session kept, reopen it with \`claude attach ${own}\``;
913
+ : stayed && stayed.reason.startsWith("kept by")
914
+ ? `old session kept (\`shift: keep_old_sessions\`), reopen it with \`claude attach ${own}\``
915
+ : `old session not removed: ${stayed ? stayed.reason : "no reason recorded"}; ${revives}`;
862
916
  return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; ${reopen}${removed}${notice}`;
863
917
  }
864
918
 
@@ -1098,7 +1152,7 @@ function removeAtResume(where, role, text) {
1098
1152
  const pid = String(text).match(/^CLI process: (\d+)\.$/m);
1099
1153
  const entry = { role, session: old[1], pid: pid ? Number(pid[1]) : null, new_session: current.slice(0, 8) || null };
1100
1154
  const { readShiftDeclaration } = require("./config");
1101
- return removeOldSessions(process.env.KEEL_CLAUDE || "claude", where, entry, readShiftDeclaration(where.worktree).keepOldSessions);
1155
+ return removeOldSessions(process.env.KEEL_CLAUDE || "claude", where, entry, readShiftDeclaration(where.worktree).keepOldSessions).removed;
1102
1156
  }
1103
1157
 
1104
1158
  function resume(where, named = null) {