@christang/keel 5.213.0 → 5.215.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.213.0",
3
+ "version": "5.215.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.213.0 -->
1
+ <!-- keel:start version=5.215.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.
package/bin/keel.js CHANGED
@@ -26,6 +26,7 @@ const {
26
26
  const {
27
27
  GuardInputError,
28
28
  clearGuard,
29
+ guardHolds,
29
30
  guardStatus,
30
31
  renderGuard,
31
32
  startGuard,
@@ -1489,7 +1490,7 @@ function adoptClaudeSessions(options) {
1489
1490
  left.push(`${named(row)}, ${row.status}`);
1490
1491
  continue;
1491
1492
  }
1492
- if (row.cwd && fs.existsSync(path.join(row.cwd, "keel", "guard.json"))) {
1493
+ if (row.cwd && guardHolds(row.cwd)) {
1493
1494
  left.push(`${named(row)}, under a task's write guard`);
1494
1495
  continue;
1495
1496
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.213.0",
3
+ "version": "5.215.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.213.0",
9
+ "version": "5.215.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.213.0",
5
+ "version": "5.215.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.213.0",
3
+ "version": "5.215.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.213.0",
3
+ "version": "5.215.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.213.0"
38
+ PACKAGE_VERSION = "5.215.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.213.0"
41
+ PROTOCOL_VERSION = "5.215.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -868,6 +868,22 @@ def chat_records_with(repo: Path, group: str, needle: str) -> list[str]:
868
868
  return [p.read_text(encoding="utf-8") for p in sorted(log.glob("*.md")) if needle in p.read_text(encoding="utf-8")]
869
869
 
870
870
 
871
+ def archived_guard(repo: Path, change: str = "demo", task: str = "1.1") -> None:
872
+ """A shape-valid `keel/guard.json` over `change#task`, checked and archived (#496).
873
+
874
+ `keel guard status` reads it as `archived`: the change directory is gone and
875
+ its archived copy shows the task checked, so the manifest enforces nothing.
876
+ """
877
+ tasks = f"openspec/changes/archive/2026-10-28-{change}/tasks.md"
878
+ write_text(repo / tasks, f"# Tasks\n\n- [x] {task} Done\n")
879
+ zero = "0" * 64
880
+ write_text(repo / "keel" / "guard.json", json.dumps({
881
+ "schema": "keel-write-guard/v1", "change": change, "task": task,
882
+ "fingerprint": {"algorithm": "sha256", "value": zero},
883
+ "touch": ["src/a.txt"], "authority": [{"path": tasks, "sha256": zero}],
884
+ }) + "\n")
885
+
886
+
871
887
  def shift_scratch(base: Path) -> tuple[Path, Path, dict, Path]:
872
888
  """`rtl` and `verify` worktrees pushed to a bare remote, for shift scenarios."""
873
889
  rtl, verify, env = chat_scratch_group(base)
@@ -22,6 +22,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
22
22
  from pathlib import Path
23
23
 
24
24
  from validation.common import (
25
+ archived_guard,
25
26
  portable_projection_bytes,
26
27
  HANDOFF_STUB,
27
28
  OPENSPEC_CONFIG_PATH,
@@ -2798,6 +2799,9 @@ def validate_update_adopts_idle_sessions_scenario() -> int:
2798
2799
  npm.chmod(0o755)
2799
2800
  guarded = tmp / "guarded"
2800
2801
  write_text(guarded / "keel" / "guard.json", "{}\n")
2802
+ # Only a checked, archived task's manifest, which enforces nothing (#496).
2803
+ finished = tmp / "finished"
2804
+ archived_guard(finished)
2801
2805
  sleepers: list[int] = []
2802
2806
 
2803
2807
  def row(name: str, sid: str, status: str, started: int, cwd: Path) -> dict:
@@ -2818,6 +2822,7 @@ def validate_update_adopts_idle_sessions_scenario() -> int:
2818
2822
  row("rtl · old guarded", "cccccccc-0000-0000-0000-000000000003", "idle", t0 - 3600000, guarded),
2819
2823
  row("pm · fresh idle", "dddddddd-0000-0000-0000-000000000004", "idle", t0 + 3600000, tmp),
2820
2824
  row("maint · this session", "eeeeeeee-0000-0000-0000-000000000005", "busy", t0 - 3600000, tmp),
2825
+ row("ip · old finished", "ffffffff-0000-0000-0000-000000000006", "idle", t0 - 3600000, finished),
2821
2826
  ]
2822
2827
  (tmp / "state.json").write_text(json.dumps({"version": "5.0.0", "lastUpdated": "2026-10-21T00:00:00.000Z", "rows": rows}))
2823
2828
  env = dict(os.environ)
@@ -2840,11 +2845,15 @@ def validate_update_adopts_idle_sessions_scenario() -> int:
2840
2845
  if adopted.returncode != 0:
2841
2846
  report(f"{label} keel --update --adopt exited {adopted.returncode}: {adopted.stdout!r} {adopted.stderr!r}")
2842
2847
  return 1
2843
- if stops != ["aaaaaaaa"]:
2844
- report(f"{label} --adopt stopped {stops!r}, not only the idle session started before the update.")
2848
+ if "ffffffff" not in stops:
2849
+ report(f"{label} --adopt left alone the session whose worktree holds only an archived manifest: {line!r}")
2845
2850
  return 1
2846
- if len(resumes) != 1 or resumes[0]["args"] != ["--bg", "--resume", "aaaaaaaa-0000-0000-0000-000000000001"]:
2847
- report(f"{label} --adopt did not resume the stopped session with exactly `--bg --resume <id>`: {resumes!r}")
2851
+ if stops != ["aaaaaaaa", "ffffffff"]:
2852
+ report(f"{label} --adopt stopped {stops!r}, not only the idle sessions started before the update.")
2853
+ return 1
2854
+ if [r["args"] for r in resumes] != [["--bg", "--resume", "aaaaaaaa-0000-0000-0000-000000000001"],
2855
+ ["--bg", "--resume", "ffffffff-0000-0000-0000-000000000006"]]:
2856
+ report(f"{label} --adopt did not resume the stopped sessions with exactly `--bg --resume <id>`: {resumes!r}")
2848
2857
  return 1
2849
2858
  if resumes[0]["cwd"] != os.path.realpath(tmp) and resumes[0]["cwd"] != str(tmp):
2850
2859
  report(f"{label} the resume ran in {resumes[0]['cwd']!r}, not the session's worktree {str(tmp)!r}.")
@@ -4346,6 +4355,31 @@ def validate_context_names_the_protocol_refresh_scenario() -> int:
4346
4355
  return 0
4347
4356
 
4348
4357
 
4358
+ def validate_context_archived_guard_does_not_defer_refresh_scenario() -> int:
4359
+ """Issue #496: a manifest over a checked, archived task defers nothing."""
4360
+ label = "context-archived-guard-does-not-defer-refresh:"
4361
+ with tempfile.TemporaryDirectory(prefix="keel-protocol-496-") as raw:
4362
+ repo = _installed_repo(Path(raw), "archived", "claude", "5.0.0")
4363
+ write_text(repo / "keel/config.yaml", "authorize:\n - protocol-refresh\n")
4364
+ archived_guard(repo)
4365
+ status = run_keel(repo, "guard", "status")
4366
+ if "Status: archived" not in status.stdout:
4367
+ report(f"{label} the fixture manifest does not read as archived: {status.stdout.strip()!r}")
4368
+ return 1
4369
+ lines = _protocol_lines(repo)
4370
+ if len(lines) != 1:
4371
+ report(f"{label} context printed {len(lines)} Protocol lines, not one: {lines!r}")
4372
+ return 1
4373
+ if "deferred" in lines[0]:
4374
+ report(f"{label} an archived manifest deferred the refresh: {lines!r}")
4375
+ return 1
4376
+ if "standing-authorized" not in lines[0]:
4377
+ report(f"{label} the refresh is not read as standing-authorized: {lines!r}")
4378
+ return 1
4379
+ report(f"{label.rstrip(':')} scenario passed.")
4380
+ return 0
4381
+
4382
+
4349
4383
  def validate_native_plugin_marketplaces_scenario() -> int:
4350
4384
  codex = shutil.which("codex")
4351
4385
  claude = claude_cli()
@@ -415,6 +415,7 @@ SCENARIOS: tuple = (
415
415
  ("directory-tree-is-the-package-renamed", hosts.validate_directory_tree_is_the_package_renamed_scenario),
416
416
  ("init-declares-plugin-auto-update", hosts.validate_init_declares_plugin_auto_update_scenario),
417
417
  ("context-names-the-protocol-refresh", hosts.validate_context_names_the_protocol_refresh_scenario),
418
+ ("context-archived-guard-does-not-defer-refresh", hosts.validate_context_archived_guard_does_not_defer_refresh_scenario),
418
419
  ("collected-feedback-is-recorded", chat.validate_collected_feedback_is_recorded_scenario),
419
420
  ("shift-change", shift.validate_shift_change_scenario),
420
421
  ("shift-role-elsewhere", shift.validate_shift_role_elsewhere_scenario),
@@ -425,6 +426,8 @@ SCENARIOS: tuple = (
425
426
  ("shift-cli-keeps-old-sessions", shift.validate_shift_cli_keeps_old_sessions_scenario),
426
427
  ("shift-resume-removes-old-sessions", shift.validate_shift_resume_removes_old_sessions_scenario),
427
428
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
429
+ ("shift-cli-keeps-worktree-in-use", shift.validate_shift_cli_keeps_worktree_in_use_scenario),
430
+ ("shift-cli-names-failed-removal", shift.validate_shift_cli_names_failed_removal_scenario),
428
431
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
429
432
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
430
433
  ("shift-cli-handover-claims-once", shift.validate_shift_cli_handover_claims_once_scenario),
@@ -486,6 +489,7 @@ SCENARIOS: tuple = (
486
489
  ("launchd-stable-node", shift.validate_launchd_stable_node_scenario),
487
490
  ("shift-slash-command", shift.validate_shift_slash_command_scenario),
488
491
  ("shift-check-skips-host-keep-awake", shift.validate_shift_check_skips_host_keep_awake_scenario),
492
+ ("shift-check-archived-guard-is-not-in-progress", shift.validate_shift_check_archived_guard_is_not_in_progress_scenario),
489
493
  ("patrol-exit-says-who-acts", shift.validate_patrol_exit_says_who_acts_scenario),
490
494
  ("patrol-nudge", shift.validate_patrol_nudge_scenario),
491
495
  ("patrol-escalate", shift.validate_patrol_escalate_scenario),
@@ -22,6 +22,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
22
22
  from pathlib import Path
23
23
 
24
24
  from validation.common import (
25
+ archived_guard,
25
26
  BOOTSTRAP_BLOCK_BYTE_BUDGET,
26
27
  ROOT,
27
28
  extract_managed_block,
@@ -829,6 +830,59 @@ def validate_shift_check_skips_host_keep_awake_scenario() -> int:
829
830
  return 0
830
831
 
831
832
 
833
+ def validate_shift_check_archived_guard_is_not_in_progress_scenario() -> int:
834
+ """Issue #496: a manifest over a checked, archived task is not a loose end.
835
+
836
+ `keel guard status` reads it as `archived` and the hook enforces nothing
837
+ under it, so the check names it as a note with `keel guard clear`. The same
838
+ manifest over a live change still blocks.
839
+ """
840
+ label = "shift-check-archived-guard-is-not-in-progress:"
841
+ with tempfile.TemporaryDirectory(prefix="keel-shift-496-") as raw:
842
+ base = Path(raw)
843
+ _rtl, verify, env, _ = shift_scratch(base)
844
+ # keel/.gitignore ignores the manifest, as a Keel repository's does.
845
+ write_text(verify / "keel" / ".gitignore", "guard.json\n")
846
+ subprocess.run(["git", "add", "keel/.gitignore"], cwd=verify, check=True, capture_output=True)
847
+ subprocess.run(["git", "commit", "-q", "-m", "ignore guard"], cwd=verify, check=True, capture_output=True)
848
+ subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
849
+ archived_guard(verify)
850
+ subprocess.run(["git", "add", "openspec"], cwd=verify, check=True, capture_output=True)
851
+ subprocess.run(["git", "commit", "-q", "-m", "archive demo"], cwd=verify, check=True, capture_output=True)
852
+ subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
853
+ status = run_keel(verify, "guard", "status", env=env)
854
+ if "Status: archived" not in status.stdout:
855
+ report(f"{label} the fixture manifest does not read as archived: {status.stdout.strip()!r}")
856
+ return 1
857
+ checked = run_keel(verify, "shift", "check", "--json", env=env)
858
+ found = chat_json(checked)
859
+ kinds = [item["kind"] for item in found.get("items", [])]
860
+ if "task-in-progress" in kinds:
861
+ report(f"{label} an archived manifest is reported as task-in-progress: {checked.stdout.strip()[:600]}")
862
+ return 1
863
+ if checked.returncode != 0:
864
+ report(f"{label} with only an archived manifest, keel shift check exited {checked.returncode}: {checked.stdout.strip()[:600]}")
865
+ return 1
866
+ if not any("keel guard clear" in note for note in found.get("notes", [])):
867
+ report(f"{label} no note names `keel guard clear` for the archived manifest: {found.get('notes')!r}")
868
+ return 1
869
+ # The same manifest over a live change of that name still holds.
870
+ live = verify / "openspec" / "changes" / "demo"
871
+ write_text(live / "tasks.md", "# Tasks\n\n- [ ] 1.1 Not yet\n")
872
+ subprocess.run(["git", "add", "openspec"], cwd=verify, check=True, capture_output=True)
873
+ subprocess.run(["git", "commit", "-q", "-m", "live demo"], cwd=verify, check=True, capture_output=True)
874
+ subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
875
+ held = run_keel(verify, "shift", "check", "--json", env=env)
876
+ if "task-in-progress" not in [item["kind"] for item in chat_json(held).get("items", [])]:
877
+ report(f"{label} a manifest over a live change is not reported as task-in-progress: {held.stdout.strip()[:600]}")
878
+ return 1
879
+ if held.returncode != 1:
880
+ report(f"{label} with a manifest over a live change, keel shift check exited {held.returncode}: {held.stdout.strip()[:600]}")
881
+ return 1
882
+ report("shift-check-archived-guard-is-not-in-progress scenario passed.")
883
+ return 0
884
+
885
+
832
886
  def validate_shift_slash_command_scenario() -> int:
833
887
  """Issue #386: a session changes its own shift with one slash command.
834
888
 
@@ -3305,6 +3359,8 @@ def running(pid):
3305
3359
  return True
3306
3360
  rows = json.loads(open(agents).read())
3307
3361
  record = {'argv': argv}
3362
+ if argv[:1] == ['rm'] and os.environ.get('FAKE_RM_FAIL'):
3363
+ open(calls, 'a').write(json.dumps(record) + '\\n'); sys.stderr.write(os.environ['FAKE_RM_FAIL'] + '\\n'); sys.exit(1)
3308
3364
  if argv[:1] == ['rm']:
3309
3365
  gone = [row for row in rows if row['id'] == argv[1]]
3310
3366
  record['alive'] = bool(gone) and bool(gone[0].get('_pid')) and running(gone[0]['_pid'])
@@ -3394,6 +3450,98 @@ def validate_shift_cli_removes_after_exit_scenario() -> int:
3394
3450
  return 0
3395
3451
 
3396
3452
 
3453
+ def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None, **fake_env: str):
3454
+ """A delivered hand-over of `5b14fbae` from verify's worktree under the contract fake (#492).
3455
+
3456
+ Returns the `rm` calls the fake logged and `keel shift status` from rtl.
3457
+ The row's `cwd` and the host's recorded `worktreePath` are the inputs.
3458
+ """
3459
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
3460
+ rtl, verify, env, _ = shift_scratch(base)
3461
+ row_cwd = {"rtl": rtl, "verify": verify}[str(row_cwd)]
3462
+ agents, calls, fake, config = base / "agents.json", base / "calls.jsonl", base / "fake-claude", base / "claude"
3463
+ write_text(fake, HANDOVER_CONTRACT_FAKE)
3464
+ fake.chmod(0o755)
3465
+ write_text(config / "projects" / host_project_name(verify) / f"{OLD}.jsonl",
3466
+ json.dumps({"type": "user", "message": {"role": "user", "content": "carry on"}}) + "\n")
3467
+ if worktree_path is not None:
3468
+ write_text(config / "jobs" / OLD[:8] / "state.json", json.dumps({"sessionId": OLD, "cwd": str(row_cwd), "worktreePath": str(verify)}))
3469
+ process = detached_sleeper()
3470
+ try:
3471
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
3472
+ "status": "idle", "state": "done", "pid": process, "cwd": str(row_cwd),
3473
+ "startedAt": 1792500000000}]))
3474
+ calls.write_text("")
3475
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config), "FAKE_AGENTS": str(agents),
3476
+ "FAKE_CALLS": str(calls), "FAKE_STOP_MODE": "late", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
3477
+ "KEEL_SHIFT_EXIT_WAIT_MS": "5000", **fake_env}
3478
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(process)}
3479
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R032", env=cli_env)
3480
+ if readied.returncode != 0:
3481
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
3482
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
3483
+ removals = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
3484
+ return removals, run_keel(rtl, "shift", "status", env=env).stdout, verify
3485
+ finally:
3486
+ with contextlib.suppress(OSError):
3487
+ os.kill(process, signal.SIGKILL)
3488
+
3489
+
3490
+ def validate_shift_cli_keeps_worktree_in_use_scenario() -> int:
3491
+ """Issue #492: a hand-over never `claude rm`s a session whose worktree the new shift uses.
3492
+
3493
+ In ChipSTRIDE the old session had created the worktree with `EnterWorktree`,
3494
+ and the new shift started in it; `claude rm` deletes a session's worktree.
3495
+ Keel skipped the session silently and status called it kept.
3496
+ """
3497
+ label = "shift-cli-keeps-worktree-in-use:"
3498
+ with tempfile.TemporaryDirectory(prefix="keel-shift-492a-") as raw:
3499
+ try:
3500
+ removals, status, verify = handover_old_session(Path(raw), Path("rtl"), Path("verify"))
3501
+ except RuntimeError as error:
3502
+ report(f"{label} {error}")
3503
+ return 1
3504
+ if any(r["argv"][1:2] == ["5b14fbae"] for r in removals):
3505
+ report(f"{label} the session whose worktree the new shift uses was removed with claude rm: {removals!r}")
3506
+ return 1
3507
+ for needle in ("not removed", str(verify), "claude rm would delete it", "claude attach 5b14fbae"):
3508
+ if needle not in status:
3509
+ report(f"{label} shift status does not name {needle!r}: {status!r}")
3510
+ return 1
3511
+ if "old session kept" in status:
3512
+ report(f"{label} shift status calls the session kept though nothing declared keeping it: {status!r}")
3513
+ return 1
3514
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3515
+ report(f"{label} the scenario registry does not include it.")
3516
+ return 1
3517
+ report(f"{label.rstrip(':')} scenario passed.")
3518
+ return 0
3519
+
3520
+
3521
+ def validate_shift_cli_names_failed_removal_scenario() -> int:
3522
+ """Issue #492: a `claude rm` that fails is reported with the host's message, not as kept."""
3523
+ label = "shift-cli-names-failed-removal:"
3524
+ with tempfile.TemporaryDirectory(prefix="keel-shift-492b-") as raw:
3525
+ try:
3526
+ _removals, status, _verify = handover_old_session(Path(raw), Path("verify"), None,
3527
+ FAKE_RM_FAIL="worktree has unpushed commits")
3528
+ except RuntimeError as error:
3529
+ report(f"{label} {error}")
3530
+ return 1
3531
+ for needle in ("not removed", "claude rm exited 1", "worktree has unpushed commits"):
3532
+ if needle not in status:
3533
+ report(f"{label} shift status does not name {needle!r}: {status!r}")
3534
+ return 1
3535
+ if "old session kept" in status:
3536
+ report(f"{label} shift status calls a failed removal kept: {status!r}")
3537
+ return 1
3538
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3539
+ report(f"{label} the scenario registry does not include it.")
3540
+ return 1
3541
+ report(f"{label.rstrip(':')} scenario passed.")
3542
+ return 0
3543
+
3544
+
3397
3545
  def validate_shift_cli_names_host_failure_scenario() -> int:
3398
3546
  """Issue #408: a hand-off the host cannot be asked about says why it waits."""
3399
3547
  label = "shift-cli-names-host-failure:"
@@ -23,6 +23,7 @@ const {
23
23
  ownerLanguageRule,
24
24
  } = require("./config");
25
25
  const { isKeelSourceRepo } = require("./capabilities");
26
+ const { guardHolds } = require("./guard");
26
27
  const { diagnoseDrift, driftCause } = require("./drift");
27
28
 
28
29
  const NEXT_ACTIONS = new Set([
@@ -1000,7 +1001,7 @@ function protocolRefresh(repo, running, authorization) {
1000
1001
  file: stamped.file,
1001
1002
  command: `keel --install --target ${installedTarget(repo)}`,
1002
1003
  authorized: authorization.scopes.has("protocol-refresh"),
1003
- deferred: fs.existsSync(path.join(repo, "keel", "guard.json")),
1004
+ deferred: guardHolds(repo),
1004
1005
  };
1005
1006
  }
1006
1007
 
package/src/core/guard.js CHANGED
@@ -424,6 +424,15 @@ function guardStatus(repo) {
424
424
  return guardResult("status", "active", { manifest });
425
425
  }
426
426
 
427
+ // Whether a manifest is in force: every state but `absent` and `archived`
428
+ // still has the hook deny writes, so only those two hold nothing (#496 D1).
429
+ // The shift check, the protocol refresh, and `--update --adopt` ask this
430
+ // rather than whether the file exists.
431
+ function guardHolds(repo) {
432
+ const { status } = guardStatus(repo);
433
+ return status !== "absent" && status !== "archived";
434
+ }
435
+
427
436
  function clearGuard(repo) {
428
437
  const file = manifestFile(repo);
429
438
  if (!fs.existsSync(file)) {
@@ -456,6 +465,7 @@ module.exports = {
456
465
  clearGuard,
457
466
  contentSignature,
458
467
  gitPaths,
468
+ guardHolds,
459
469
  guardStatus,
460
470
  readManifest,
461
471
  renderGuard,
package/src/core/shift.js CHANGED
@@ -18,6 +18,7 @@ const path = require("path");
18
18
  const { spawn, spawnSync } = require("child_process");
19
19
  const store = require("./chat/store");
20
20
  const locks = require("./lock");
21
+ const guard = require("./guard");
21
22
 
22
23
  const REF = "keel-shift";
23
24
  const USAGE = [
@@ -197,7 +198,13 @@ function check(where, role) {
197
198
  }
198
199
 
199
200
  if (fs.existsSync(path.join(where.worktree, "keel", "guard.json"))) {
200
- items.push({ kind: "task-in-progress", detail: "keel/guard.json: a task's write guard is still active; complete the task or clear the guard" });
201
+ if (guard.guardHolds(where.worktree)) {
202
+ items.push({ kind: "task-in-progress", detail: "keel/guard.json: a task's write guard is still active; complete the task or clear the guard" });
203
+ } else {
204
+ // Checked and archived: the hook lets every write through (#496 D2).
205
+ const { manifest } = guard.guardStatus(where.worktree);
206
+ notes.push(`keel/guard.json guards ${manifest.change}#${manifest.task}, which is checked and archived, so it enforces nothing; \`keel guard clear\` removes it`);
207
+ }
201
208
  }
202
209
 
203
210
  for (const row of liveProcesses(where.worktree)) {
@@ -637,33 +644,80 @@ function keptCopyOf(where, role, transcript) {
637
644
  // slot and stays (#401). A session is the role's when it ran in a bound
638
645
  // worktree, or when Keel keeps its transcript under the role: a renamed or
639
646
  // moved worktree leaves a `cwd` no binding names (#462 D2).
647
+ //
648
+ // `claude rm` also deletes the worktree a session created (#492 F4), so a
649
+ // session whose own worktree is in use stays; every session left listed is
650
+ // returned with its reason, which `keel shift status` names (#492 D3, D4).
640
651
  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)));
652
+ const roles = store.readJsonFile(path.join(where.root, "roles.json"));
653
+ const bound = new Set(Object.entries(roles).filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
643
654
  const listed = listAgents(claude);
644
- if (!listed) return [];
655
+ const own = entry.session ? entry.session.slice(0, 8) : null;
656
+ if (!listed) return { removed: [], notRemoved: own ? [{ id: own, reason: "`claude agents` could not be read" }] : [] };
645
657
  const { keptFile } = require("./chat/notice");
646
- const roles = (row) => bound.has(realpath(row.cwd)) || fs.existsSync(keptFile(where, entry.role, `${row.sessionId}.jsonl`));
658
+ const idOf = (row) => row.id || row.sessionId.slice(0, 8);
659
+ // The session the hand-off names is the role's wherever its row says it ran (#492 D1).
660
+ const isRoles = (row) => row.sessionId === entry.session || bound.has(realpath(row.cwd))
661
+ || fs.existsSync(keptFile(where, entry.role, `${row.sessionId}.jsonl`));
647
662
  const old = listed
648
- .filter((row) => row && row.kind === "background" && !row.status && row.cwd && row.sessionId && roles(row)
663
+ .filter((row) => row && row.kind === "background" && !row.status && row.cwd && row.sessionId && isRoles(row)
649
664
  && row.id !== entry.new_session)
650
- .map((row) => ({ row, transcript: hostTranscript(row.cwd, row.sessionId),
651
- kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) }))
665
+ .map((row) => {
666
+ const worktree = hostWorktree(row);
667
+ return { row, worktree, transcript: hostTranscript(row.cwd, row.sessionId) || (worktree && hostTranscript(worktree, row.sessionId)),
668
+ kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) };
669
+ })
652
670
  .filter(({ transcript, kept }) => transcript || fs.existsSync(kept))
653
671
  .sort((a, b) => (Number(b.row.startedAt) || 0) - (Number(a.row.startedAt) || 0));
672
+ // Worktrees in use: the hand-off's, every bound one, and each other listed session's (#492 D2).
673
+ const inUse = (worktree, row) => {
674
+ const real = realpath(worktree);
675
+ if (entry.worktree && realpath(entry.worktree) === real) return "the new shift's worktree";
676
+ const binding = Object.entries(roles).find(([tree]) => realpath(tree) === real);
677
+ if (binding) return `bound to role ${binding[1]}`;
678
+ const other = listed.find((r) => r && r !== row && r.cwd && realpath(r.cwd) === real);
679
+ return other ? `session ${idOf(other)} runs there` : null;
680
+ };
654
681
  const removed = [];
655
- for (const { row, transcript } of old.slice(keep)) {
682
+ const notRemoved = old.slice(0, keep).map(({ row }) => ({ id: idOf(row), reason: "kept by `shift: keep_old_sessions`" }));
683
+ for (const { row, worktree, transcript } of old.slice(keep)) {
656
684
  // Never a session whose process still runs (#408 D1): the one just handed
657
685
  // over gets a bounded wait for the process its note recorded; any other
658
686
  // still running is left for the next hand-over.
659
687
  const handedOver = row.sessionId === entry.session;
660
688
  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));
689
+ if (handedOver ? !waitForExit(pid, envMs("KEEL_SHIFT_EXIT_WAIT_MS", 15 * 1000)) : processRunning(pid)) {
690
+ notRemoved.push({ id: idOf(row), reason: "its process was still running" });
691
+ continue;
692
+ }
693
+ if (transcript && !keptCopyOf(where, entry.role, transcript)) {
694
+ notRemoved.push({ id: idOf(row), reason: "Keel could not copy its transcript" });
695
+ continue;
696
+ }
697
+ const using = worktree && fs.existsSync(worktree) ? inUse(worktree, row) : null;
698
+ if (using) {
699
+ notRemoved.push({ id: idOf(row), reason: `its worktree ${worktree} is in use (${using}), and claude rm would delete it` });
700
+ continue;
701
+ }
702
+ const gone = spawnSync(claude, ["rm", idOf(row)], { encoding: "utf8", timeout: hostTimeout() });
703
+ if (!gone.error && gone.status === 0) removed.push(idOf(row));
704
+ else {
705
+ const said = String(gone.stderr || gone.stdout || (gone.error && gone.error.message) || "").trim().split("\n")[0];
706
+ notRemoved.push({ id: idOf(row), reason: `claude rm exited ${gone.error ? "with an error" : gone.status}${said ? `: ${said}` : ""}` });
707
+ }
665
708
  }
666
- return removed;
709
+ return { removed, notRemoved };
710
+ }
711
+
712
+ // The worktree the host records for a session it created one for — with
713
+ // `EnterWorktree` or `claude --bg -w` — which `claude agents` does not show
714
+ // and `claude rm` deletes (#492 F3). Null when the host recorded none.
715
+ function hostWorktree(row) {
716
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
717
+ const id = row.id || (row.sessionId || "").slice(0, 8);
718
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(id)) return null;
719
+ const recorded = store.readJsonFile(path.join(config, "jobs", id, "state.json")).worktreePath;
720
+ return typeof recorded === "string" && recorded ? recorded : null;
667
721
  }
668
722
 
669
723
  // One runner at a time per role (#388 D2): the waiter and the tick both carry
@@ -723,7 +777,9 @@ function deliver(claude, where, entry, id, name, adopted) {
723
777
  Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
724
778
  for (const key of ["error", "failed_at", "runner_pid"]) delete entry[key];
725
779
  if (adopted) entry.adopted = true;
726
- entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
780
+ const swept = removeOldSessions(claude, where, entry, declared.keepOldSessions);
781
+ entry.removed = swept.removed;
782
+ entry.not_removed = swept.notRemoved;
727
783
  if (declared.message) entry.notice = declared.message;
728
784
  store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
729
785
  return entry;
@@ -856,9 +912,14 @@ function describeHandOff(entry) {
856
912
  const removed = (entry.removed || []).length ? `; older sessions removed from \`claude agents\` (transcripts kept by Keel): ${entry.removed.join(", ")}` : "";
857
913
  const notice = entry.notice ? `; ${entry.notice}` : "";
858
914
  const own = entry.session.slice(0, 8);
915
+ const stayed = (entry.not_removed || []).find((item) => item.id === own);
916
+ const revives = `it stays in \`claude agents\`, and opening it (\`claude attach ${own}\`) brings it back beside the new shift`;
917
+ // Kept only when `keep_old_sessions` kept it; otherwise the recorded reason (#492 D4).
859
918
  const reopen = (entry.removed || []).includes(own)
860
919
  ? `old session removed, its conversation kept: \`keel shift history ${entry.role} --show ${own}\``
861
- : `old session kept, reopen it with \`claude attach ${own}\``;
920
+ : stayed && stayed.reason.startsWith("kept by")
921
+ ? `old session kept (\`shift: keep_old_sessions\`), reopen it with \`claude attach ${own}\``
922
+ : `old session not removed: ${stayed ? stayed.reason : "no reason recorded"}; ${revives}`;
862
923
  return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; ${reopen}${removed}${notice}`;
863
924
  }
864
925
 
@@ -1098,7 +1159,7 @@ function removeAtResume(where, role, text) {
1098
1159
  const pid = String(text).match(/^CLI process: (\d+)\.$/m);
1099
1160
  const entry = { role, session: old[1], pid: pid ? Number(pid[1]) : null, new_session: current.slice(0, 8) || null };
1100
1161
  const { readShiftDeclaration } = require("./config");
1101
- return removeOldSessions(process.env.KEEL_CLAUDE || "claude", where, entry, readShiftDeclaration(where.worktree).keepOldSessions);
1162
+ return removeOldSessions(process.env.KEEL_CLAUDE || "claude", where, entry, readShiftDeclaration(where.worktree).keepOldSessions).removed;
1102
1163
  }
1103
1164
 
1104
1165
  function resume(where, named = null) {