@christang/keel 5.216.0 → 5.218.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.216.0",
3
+ "version": "5.218.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.216.0 -->
1
+ <!-- keel:start version=5.218.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
@@ -2514,15 +2514,31 @@ function runDoctor(options) {
2514
2514
  function printLaunchdJobs() {
2515
2515
  const jobs = require("../src/core/launchd").inspectJobs();
2516
2516
  if (!jobs.length) return;
2517
- const gone = jobs.filter((job) => !job.exists);
2518
- for (const job of gone) {
2519
- printDoctorLine(
2520
- "launchd",
2521
- "problem",
2522
- `${job.name} runs ${job.program || "no program"}, which does not exist; re-create it with \`${job.recreate}\``
2523
- );
2517
+ let problems = 0;
2518
+ for (const job of jobs) {
2519
+ if (!job.exists) {
2520
+ problems += 1;
2521
+ printDoctorLine(
2522
+ "launchd",
2523
+ "problem",
2524
+ `${job.name} runs ${job.program || "no program"}, which does not exist; re-create it with \`${job.recreate}\``
2525
+ );
2526
+ }
2527
+ // The directory it runs in (#503): gone, or a worktree Keel creates and
2528
+ // prunes, so the job stops the day the worktree moves.
2529
+ for (const directory of job.directories || []) {
2530
+ if (directory.exists && !directory.regenerated) continue;
2531
+ problems += 1;
2532
+ printDoctorLine(
2533
+ "launchd",
2534
+ "problem",
2535
+ directory.exists
2536
+ ? `${job.name} runs in ${directory.path}, a worktree Keel creates and prunes, so it stops when that moves; re-create it with \`${job.recreate}\``
2537
+ : `${job.name} runs in ${directory.path}, which does not exist; re-create it with \`${job.recreate}\``
2538
+ );
2539
+ }
2524
2540
  }
2525
- if (!gone.length) printDoctorLine("launchd", "ok", `${jobs.length} dev.keel job${jobs.length === 1 ? "" : "s"}, each naming a node that exists`);
2541
+ if (!problems) printDoctorLine("launchd", "ok", `${jobs.length} dev.keel job${jobs.length === 1 ? "" : "s"}, each naming a node that exists and no directory that is gone or regenerated`);
2526
2542
  }
2527
2543
 
2528
2544
  // Each role's merged, unused task branches (#469 D5): a count pointing at
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.216.0",
3
+ "version": "5.218.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.216.0",
9
+ "version": "5.218.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.216.0",
5
+ "version": "5.218.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.216.0",
3
+ "version": "5.218.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.216.0",
3
+ "version": "5.218.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.216.0"
38
+ PACKAGE_VERSION = "5.218.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.216.0"
41
+ PROTOCOL_VERSION = "5.218.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -428,6 +428,9 @@ SCENARIOS: tuple = (
428
428
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
429
429
  ("shift-cli-keeps-worktree-in-use", shift.validate_shift_cli_keeps_worktree_in_use_scenario),
430
430
  ("shift-cli-names-failed-removal", shift.validate_shift_cli_names_failed_removal_scenario),
431
+ ("shift-ready-says-session-stays", shift.validate_shift_ready_says_session_stays_scenario),
432
+ ("shift-ready-promises-removal-when-removable", shift.validate_shift_ready_promises_removal_when_removable_scenario),
433
+ ("shift-ready-kept-session-names-shared-worktree", shift.validate_shift_ready_kept_session_names_shared_worktree_scenario),
431
434
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
432
435
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
433
436
  ("shift-cli-handover-claims-once", shift.validate_shift_cli_handover_claims_once_scenario),
@@ -487,6 +490,9 @@ SCENARIOS: tuple = (
487
490
  ("tick-checks-issues", shift.validate_tick_checks_issues_scenario),
488
491
  ("tick-reports-issue-checks", shift.validate_tick_reports_issue_checks_scenario),
489
492
  ("launchd-stable-node", shift.validate_launchd_stable_node_scenario),
493
+ ("tick-task-names-main-checkout", shift.validate_tick_task_names_main_checkout_scenario),
494
+ ("tick-skips-missing-bound-worktree", shift.validate_tick_skips_missing_bound_worktree_scenario),
495
+ ("launchd-doctor-names-job-directories", shift.validate_launchd_doctor_names_job_directories_scenario),
490
496
  ("shift-slash-command", shift.validate_shift_slash_command_scenario),
491
497
  ("shift-check-skips-host-keep-awake", shift.validate_shift_check_skips_host_keep_awake_scenario),
492
498
  ("shift-check-archived-guard-is-not-in-progress", shift.validate_shift_check_archived_guard_is_not_in_progress_scenario),
@@ -771,6 +771,282 @@ def validate_launchd_stable_node_scenario() -> int:
771
771
  return 0
772
772
 
773
773
 
774
+ def validate_tick_task_names_main_checkout_scenario() -> int:
775
+ """Issue #503: the launchd job names a path that outlives a worktree.
776
+
777
+ `keel tick task` wrote the worktree the patrol role was bound to when it
778
+ ran, a checkout Keel creates and prunes, so the installed job named a path
779
+ that moved. It now names the repository's main checkout, from which
780
+ `keel tick` finds the bound worktree on every run, and falls back to the
781
+ bound worktree, saying so, only when the main checkout declares no patrol.
782
+ """
783
+ label = "tick-task-names-main-checkout:"
784
+ with tempfile.TemporaryDirectory(prefix="keel-tick-503-") as raw:
785
+ base = Path(raw)
786
+ rtl, verify, env, _ = shift_scratch(base)
787
+ write_text(rtl / "openspec/specs/.keep", "")
788
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n runner: tick\n")
789
+ for args in (["add", "-A"], ["commit", "-q", "-m", "patrol"]):
790
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
791
+ main = os.path.realpath(rtl)
792
+
793
+ def named(text: str, pattern: str) -> str:
794
+ return (re.search(pattern, text, re.S) or [None, ""])[1]
795
+
796
+ def repo_of(text: str) -> str:
797
+ return named(text, r"<string>--repo</string>\s*<string>(.*?)</string>")
798
+
799
+ def directory_of(text: str) -> str:
800
+ return named(text, r"<key>WorkingDirectory</key>\s*<string>(.*?)</string>")
801
+
802
+ # The role leaves the main checkout for linked worktrees under .claude/worktrees/.
803
+ run_keel(rtl, "chat", "role", "--set", "main", env=env)
804
+ wa = chat_worktree(rtl, rtl / ".claude" / "worktrees" / "wa")
805
+ wb = chat_worktree(rtl, rtl / ".claude" / "worktrees" / "wb")
806
+ bound = run_keel(wa, "chat", "role", "--set", "rtl", env=env)
807
+ if bound.returncode != 0:
808
+ report(f"{label} could not bind the role to a worktree: {bound.stdout!r} {bound.stderr!r}")
809
+ return 1
810
+
811
+ from_a = run_keel(wa, "tick", "task", env=env)
812
+ if from_a.returncode != 0:
813
+ report(f"{label} keel tick task failed in a worktree: {from_a.stderr!r}")
814
+ return 1
815
+ if repo_of(from_a.stdout) != main or directory_of(from_a.stdout) != main:
816
+ report(f"{label} the job printed from a worktree does not name the main checkout {main!r}: "
817
+ f"--repo {repo_of(from_a.stdout)!r}, WorkingDirectory {directory_of(from_a.stdout)!r}")
818
+ return 1
819
+ for tree in (wa, wb):
820
+ if os.path.realpath(tree) in from_a.stdout:
821
+ report(f"{label} the job printed from a worktree still names {os.path.realpath(tree)!r}: {from_a.stdout!r}")
822
+ return 1
823
+ from_main = run_keel(rtl, "tick", "task", env=env)
824
+ if from_main.returncode != 0:
825
+ report(f"{label} keel tick task failed in the main checkout: {from_main.stderr!r}")
826
+ return 1
827
+ if repo_of(from_main.stdout) != main or directory_of(from_main.stdout) != main:
828
+ report(f"{label} the job printed from the main checkout does not name it: {from_main.stdout!r}")
829
+ return 1
830
+ for needle in ("<integer>300</integer>", "<string>tick</string>", "launchctl bootstrap", "Keel creates nothing"):
831
+ if needle not in from_main.stdout:
832
+ report(f"{label} the job printed from the main checkout does not carry {needle!r}: {from_main.stdout!r}")
833
+ return 1
834
+
835
+ # Binding the role elsewhere needs no new job.
836
+ run_keel(wa, "chat", "role", "--unset", "--leave-branches", env=env)
837
+ rebound = run_keel(wb, "chat", "role", "--set", "rtl", env=env)
838
+ if rebound.returncode != 0:
839
+ report(f"{label} could not rebind the role to another worktree: {rebound.stdout!r} {rebound.stderr!r}")
840
+ return 1
841
+ from_b = run_keel(wb, "tick", "task", env=env)
842
+ if from_b.stdout != from_a.stdout:
843
+ report(f"{label} the job printed after rebinding the role differs from the one printed before: "
844
+ f"{from_a.stdout!r} then {from_b.stdout!r}")
845
+ return 1
846
+ ticked = run_keel(verify, "tick", "--repo", main, "--json", env=env)
847
+ try:
848
+ patrol = json.loads(ticked.stdout)["patrols"][0]
849
+ except (ValueError, KeyError, IndexError):
850
+ report(f"{label} keel tick --repo {main} printed no patrol result: {ticked.stdout!r} {ticked.stderr!r}")
851
+ return 1
852
+ if not patrol.get("ran"):
853
+ report(f"{label} after rebinding, the tick did not run the patrol: {patrol!r}")
854
+ return 1
855
+ if patrol.get("worktree") != os.path.realpath(wb):
856
+ report(f"{label} after rebinding, the tick ran the patrol in {patrol.get('worktree')!r}, not {os.path.realpath(wb)!r}")
857
+ return 1
858
+
859
+ # A main checkout that declares no patrol cannot stand in: the worktree is named, and why.
860
+ solo = mailbox_repository(base / "solo")
861
+ wc = chat_worktree(solo, solo / ".claude" / "worktrees" / "wc")
862
+ write_authorize_config(wc, "patrol:\n role: sr\n every: 60m\n runner: tick\n")
863
+ subprocess.run(["git", "add", "-A"], cwd=wc, check=True, capture_output=True)
864
+ subprocess.run(["git", "commit", "-q", "-m", "patrol"], cwd=wc, check=True, capture_output=True)
865
+ run_keel(wc, "chat", "role", "--set", "sr", env=env)
866
+ fallback = run_keel(wc, "tick", "task", env=env)
867
+ if fallback.returncode != 0:
868
+ report(f"{label} keel tick task failed where the main checkout declares no patrol: {fallback.stderr!r}")
869
+ return 1
870
+ if repo_of(fallback.stdout) != os.path.realpath(wc):
871
+ report(f"{label} with no patrol in the main checkout the job does not name the bound worktree: {fallback.stdout!r}")
872
+ return 1
873
+ if "declares no `patrol:`" not in fallback.stdout:
874
+ report(f"{label} the fallback job does not say the main checkout declares no patrol: {fallback.stdout!r}")
875
+ return 1
876
+ if "tick-task-names-main-checkout" not in {name for name, _ in registry.SCENARIOS}:
877
+ report(f"{label} scenario is not registered.")
878
+ return 1
879
+ report("tick-task-names-main-checkout scenario passed.")
880
+ return 0
881
+
882
+
883
+ def validate_tick_skips_missing_bound_worktree_scenario() -> int:
884
+ """Issue #503: a bound worktree that was removed does not stop the patrol.
885
+
886
+ `roles.json` keeps a role's binding after `git worktree remove`. The tick
887
+ took the first bound worktree and started the patrol in a directory that
888
+ was gone; it now uses the first bound worktree that exists, and says so
889
+ when none does.
890
+ """
891
+ label = "tick-skips-missing-bound-worktree:"
892
+ with tempfile.TemporaryDirectory(prefix="keel-tick-503-gone-") as raw:
893
+ base = Path(raw)
894
+ rtl, _verify, env, _ = shift_scratch(base)
895
+ write_text(rtl / "openspec/specs/.keep", "")
896
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n runner: tick\n")
897
+ for args in (["add", "-A"], ["commit", "-q", "-m", "patrol"]):
898
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
899
+ # `a-gone` sorts before `rtl`, so the removed worktree is the one a plain "first bound" picks.
900
+ gone = chat_worktree(rtl, base / "a-gone")
901
+ bound = run_keel(gone, "chat", "role", "--set", "rtl", env=env)
902
+ if bound.returncode != 0:
903
+ report(f"{label} could not bind the role to the worktree to remove: {bound.stdout!r} {bound.stderr!r}")
904
+ return 1
905
+ removed = subprocess.run(["git", "worktree", "remove", "--force", str(gone)], cwd=rtl,
906
+ text=True, capture_output=True, check=False)
907
+ if removed.returncode != 0 or gone.exists():
908
+ report(f"{label} could not remove the worktree: {removed.stderr!r}")
909
+ return 1
910
+ bindings = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
911
+ if not any(p.endswith("/a-gone") for p in bindings):
912
+ report(f"{label} the removed worktree is no longer bound, so the case is not reproduced: {bindings!r}")
913
+ return 1
914
+
915
+ def tick() -> subprocess.CompletedProcess[str]:
916
+ return run_keel(rtl, "tick", "--repo", str(rtl), "--json", env=env)
917
+
918
+ first = tick()
919
+ try:
920
+ patrol = json.loads(first.stdout)["patrols"][0]
921
+ except (ValueError, KeyError, IndexError):
922
+ report(f"{label} the tick printed no patrol result: {first.stdout!r} {first.stderr!r}")
923
+ return 1
924
+ if first.returncode != 0:
925
+ report(f"{label} the tick exited {first.returncode} with one bound worktree gone and one present: {first.stderr!r}")
926
+ return 1
927
+ if not patrol.get("ran"):
928
+ report(f"{label} with one bound worktree gone and one present, the tick ran no patrol: {patrol!r}")
929
+ return 1
930
+ if patrol.get("worktree") != os.path.realpath(rtl):
931
+ report(f"{label} with one bound worktree gone and one present, the patrol ran in {patrol.get('worktree')!r}, not {os.path.realpath(rtl)!r}")
932
+ return 1
933
+
934
+ # Only the removed worktree stays bound.
935
+ run_keel(rtl, "chat", "role", "--set", "main", env=env)
936
+ second = tick()
937
+ try:
938
+ patrol = json.loads(second.stdout)["patrols"][0]
939
+ except (ValueError, KeyError, IndexError):
940
+ report(f"{label} the second tick printed no patrol result: {second.stdout!r} {second.stderr!r}")
941
+ return 1
942
+ if second.returncode != 0:
943
+ report(f"{label} the tick exited {second.returncode} with only a removed worktree bound: {second.stderr!r}")
944
+ return 1
945
+ if patrol.get("ran"):
946
+ report(f"{label} the tick ran a patrol with only a removed worktree bound: {patrol!r}")
947
+ return 1
948
+ for needle in ("no longer exist", "keel chat role --prune"):
949
+ if needle not in str(patrol.get("why")):
950
+ report(f"{label} the tick does not say {needle!r} for a role bound only to a removed worktree: {patrol!r}")
951
+ return 1
952
+ if "tick-skips-missing-bound-worktree" not in {name for name, _ in registry.SCENARIOS}:
953
+ report(f"{label} scenario is not registered.")
954
+ return 1
955
+ report("tick-skips-missing-bound-worktree scenario passed.")
956
+ return 0
957
+
958
+
959
+ def validate_launchd_doctor_names_job_directories_scenario() -> int:
960
+ """Issue #503: `keel --doctor` checks where a job runs, not only its node.
961
+
962
+ A tick job names `--repo` and `WorkingDirectory`; when that directory is
963
+ gone, or is a worktree Keel creates and prunes, launchd keeps firing and the
964
+ job fails with no trace but `tick.err`, while doctor said `launchd: ok`
965
+ because it read only the first program argument.
966
+ """
967
+ label = "launchd-doctor-names-job-directories:"
968
+ with tempfile.TemporaryDirectory(prefix="keel-launchd-503-") as raw:
969
+ base = Path(raw)
970
+ rtl, cx, env, _ = chat_wake_scratch(base)
971
+ write_text(rtl / "openspec/specs/.keep", "")
972
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n runner: tick\n")
973
+ for args in (["add", "-A"], ["commit", "-q", "-m", "patrol"]):
974
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
975
+ main = os.path.realpath(rtl)
976
+ worktree = chat_worktree(rtl, rtl / ".claude" / "worktrees" / "wa")
977
+ printed = run_keel(rtl, "tick", "task", env=env)
978
+ if printed.returncode != 0:
979
+ report(f"{label} keel tick task failed: {printed.stderr!r}")
980
+ return 1
981
+ if "<?xml" not in printed.stdout:
982
+ report(f"{label} keel tick task printed no plist: {printed.stdout!r}")
983
+ return 1
984
+ plist = printed.stdout[printed.stdout.index("<?xml"):printed.stdout.index("</plist>") + 8]
985
+ agents = base / "agents"
986
+ agents.mkdir(exist_ok=True)
987
+ job = agents / "dev.keel.tick.x.plist"
988
+
989
+ def runs_in(directory: str) -> str:
990
+ text = re.sub(r"(<string>--repo</string>\s*<string>).*?(</string>)", lambda m: m.group(1) + directory + m.group(2), plist, flags=re.S)
991
+ return re.sub(r"(<key>WorkingDirectory</key>\s*<string>).*?(</string>)", lambda m: m.group(1) + directory + m.group(2), text, flags=re.S)
992
+
993
+ def doctor() -> tuple[int, str]:
994
+ ran = run_keel(rtl, "--doctor", env=env)
995
+ return ran.returncode, next((line for line in ran.stdout.splitlines() if line.startswith("launchd:")), "")
996
+
997
+ job.write_text(runs_in(main), encoding="utf-8")
998
+ baseline_status, baseline = doctor()
999
+ if not baseline.startswith("launchd: ok"):
1000
+ report(f"{label} a job naming the main checkout is not reported ok: {baseline!r}")
1001
+ return 1
1002
+
1003
+ gone = base / "gone-checkout"
1004
+ job.write_text(runs_in(str(gone)), encoding="utf-8")
1005
+ status, line = doctor()
1006
+ if not line.startswith("launchd: problem"):
1007
+ report(f"{label} a job running in a removed directory is not reported as a problem: {line!r}")
1008
+ return 1
1009
+ for needle in ("dev.keel.tick.x.plist", str(gone), "keel tick task"):
1010
+ if needle not in line:
1011
+ report(f"{label} the problem line for a removed directory does not name {needle!r}: {line!r}")
1012
+ return 1
1013
+ if status != baseline_status:
1014
+ report(f"{label} a removed directory changed doctor's exit status from {baseline_status} to {status}.")
1015
+ return 1
1016
+
1017
+ job.write_text(runs_in(os.path.realpath(worktree)), encoding="utf-8")
1018
+ status, line = doctor()
1019
+ if not line.startswith("launchd: problem"):
1020
+ report(f"{label} a job running in a worktree under .claude/worktrees is not reported as a problem: {line!r}")
1021
+ return 1
1022
+ for needle in ("dev.keel.tick.x.plist", os.path.realpath(worktree), "keel tick task"):
1023
+ if needle not in line:
1024
+ report(f"{label} the problem line for a regenerated worktree does not name {needle!r}: {line!r}")
1025
+ return 1
1026
+ if status != baseline_status:
1027
+ report(f"{label} a regenerated worktree changed doctor's exit status from {baseline_status} to {status}.")
1028
+ return 1
1029
+
1030
+ # A job with neither key is judged by its node alone.
1031
+ job.unlink()
1032
+ added = run_keel(cx, "chat", "wake", "add", env=env)
1033
+ if added.returncode != 0:
1034
+ report(f"{label} keel chat wake add failed: {(added.stdout + added.stderr).strip()!r}")
1035
+ return 1
1036
+ if not list(agents.glob("dev.keel.chat-wake.*.plist")):
1037
+ report(f"{label} keel chat wake add wrote no LaunchAgent: {added.stdout.strip()!r}")
1038
+ return 1
1039
+ _, line = doctor()
1040
+ if not line.startswith("launchd: ok"):
1041
+ report(f"{label} a chat waker with no directory is not reported ok: {line!r}")
1042
+ return 1
1043
+ if "launchd-doctor-names-job-directories" not in {name for name, _ in registry.SCENARIOS}:
1044
+ report(f"{label} scenario is not registered.")
1045
+ return 1
1046
+ report("launchd-doctor-names-job-directories scenario passed.")
1047
+ return 0
1048
+
1049
+
774
1050
  def validate_shift_check_skips_host_keep_awake_scenario() -> int:
775
1051
  """Issue #447: the host's own keep-awake is not a loose end of the shift.
776
1052
 
@@ -3450,14 +3726,20 @@ def validate_shift_cli_removes_after_exit_scenario() -> int:
3450
3726
  return 0
3451
3727
 
3452
3728
 
3453
- def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None, **fake_env: str):
3729
+ def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None, ready_out: list | None = None,
3730
+ config_text: str | None = None, **fake_env: str):
3454
3731
  """A delivered hand-over of `5b14fbae` from verify's worktree under the contract fake (#492).
3455
3732
 
3456
3733
  Returns the `rm` calls the fake logged and `keel shift status` from rtl.
3457
3734
  The row's `cwd` and the host's recorded `worktreePath` are the inputs.
3735
+ `ready_out`, when given, receives what `shift ready --wake` printed as text and then as `--json` (#506).
3458
3736
  """
3459
3737
  OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
3460
3738
  rtl, verify, env, _ = shift_scratch(base)
3739
+ if config_text is not None:
3740
+ write_text(verify / "keel" / "config.yaml", config_text)
3741
+ for git in (["add", "keel/config.yaml"], ["commit", "-q", "-m", "declare shift"], ["push", "-q", "origin", "HEAD"]):
3742
+ subprocess.run(["git", *git], cwd=verify, check=True, capture_output=True)
3461
3743
  row_cwd = {"rtl": rtl, "verify": verify}[str(row_cwd)]
3462
3744
  agents, calls, fake, config = base / "agents.json", base / "calls.jsonl", base / "fake-claude", base / "claude"
3463
3745
  write_text(fake, HANDOVER_CONTRACT_FAKE)
@@ -3479,6 +3761,9 @@ def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None,
3479
3761
  readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R032", env=cli_env)
3480
3762
  if readied.returncode != 0:
3481
3763
  raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
3764
+ if ready_out is not None:
3765
+ as_json = run_keel(verify, "shift", "ready", "--wake", "--json", "next: rerun R032", env=cli_env)
3766
+ ready_out.extend([readied.stdout, as_json.stdout])
3482
3767
  run_keel(verify, "tick", "--repo", str(rtl), env=env)
3483
3768
  removals = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
3484
3769
  return removals, run_keel(rtl, "shift", "status", env=env).stdout, verify
@@ -3542,6 +3827,101 @@ def validate_shift_cli_names_failed_removal_scenario() -> int:
3542
3827
  return 0
3543
3828
 
3544
3829
 
3830
+ def validate_shift_ready_says_session_stays_scenario() -> int:
3831
+ """Issue #506: `shift ready` does not promise a removal the hand-over will not carry out.
3832
+
3833
+ The session had made its worktree with `EnterWorktree` and the new shift
3834
+ starts in it, so `claude rm` would delete the worktree and the hand-over
3835
+ leaves the session listed (#492). `ready` printed that it is removed.
3836
+ """
3837
+ label = "shift-ready-says-session-stays:"
3838
+ with tempfile.TemporaryDirectory(prefix="keel-shift-506a-") as raw:
3839
+ shown: list[str] = []
3840
+ try:
3841
+ removals, _status, verify = handover_old_session(Path(raw), Path("rtl"), Path("verify"), ready_out=shown)
3842
+ except RuntimeError as error:
3843
+ report(f"{label} {error}")
3844
+ return 1
3845
+ if len(shown) != 2:
3846
+ report(f"{label} the fixture did not return what ready printed: {shown!r}")
3847
+ return 1
3848
+ try:
3849
+ clear = json.loads(shown[1])["clear"]
3850
+ except (ValueError, KeyError) as error:
3851
+ report(f"{label} ready --json has no readable `clear` field ({error!r}): {shown[1]!r}")
3852
+ return 1
3853
+ for name, text in (("text", shown[0]), ("clear", clear)):
3854
+ if "removes it from the session list" in text:
3855
+ report(f"{label} the {name} hint promises a removal the hand-over does not carry out: {text!r}")
3856
+ return 1
3857
+ for needle in ("stays in `claude agents`", str(verify), "claude rm", "claude attach 5b14fbae"):
3858
+ if needle not in text:
3859
+ report(f"{label} the {name} hint does not say {needle!r}: {text!r}")
3860
+ return 1
3861
+ if any(r["argv"][1:2] == ["5b14fbae"] for r in removals):
3862
+ report(f"{label} the hand-over removed the session the hint said stays: {removals!r}")
3863
+ return 1
3864
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3865
+ report(f"{label} the scenario registry does not include it.")
3866
+ return 1
3867
+ report(f"{label.rstrip(':')} scenario passed.")
3868
+ return 0
3869
+
3870
+
3871
+ def validate_shift_ready_promises_removal_when_removable_scenario() -> int:
3872
+ """Issue #506: a session nothing keeps is still told it is removed, and is."""
3873
+ label = "shift-ready-promises-removal-when-removable:"
3874
+ with tempfile.TemporaryDirectory(prefix="keel-shift-506b-") as raw:
3875
+ shown: list[str] = []
3876
+ try:
3877
+ removals, _status, _verify = handover_old_session(Path(raw), Path("verify"), None, ready_out=shown)
3878
+ except RuntimeError as error:
3879
+ report(f"{label} {error}")
3880
+ return 1
3881
+ if len(shown) != 2:
3882
+ report(f"{label} the fixture did not return what ready printed: {shown!r}")
3883
+ return 1
3884
+ if "removes it from the session list" not in shown[0]:
3885
+ report(f"{label} the hint no longer promises the removal that follows: {shown[0]!r}")
3886
+ return 1
3887
+ if "stays in `claude agents`" in shown[0]:
3888
+ report(f"{label} the hint says a removable session stays: {shown[0]!r}")
3889
+ return 1
3890
+ if not any(r["argv"][1:2] == ["5b14fbae"] for r in removals):
3891
+ report(f"{label} the hand-over did not call claude rm for the session the hint said is removed: {removals!r}")
3892
+ return 1
3893
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3894
+ report(f"{label} the scenario registry does not include it.")
3895
+ return 1
3896
+ report(f"{label.rstrip(':')} scenario passed.")
3897
+ return 0
3898
+
3899
+
3900
+ def validate_shift_ready_kept_session_names_shared_worktree_scenario() -> int:
3901
+ """Issue #506: a kept session whose worktree is the new shift's says so."""
3902
+ label = "shift-ready-kept-session-names-shared-worktree:"
3903
+ with tempfile.TemporaryDirectory(prefix="keel-shift-506c-") as raw:
3904
+ shown: list[str] = []
3905
+ try:
3906
+ _removals, _status, verify = handover_old_session(Path(raw), Path("rtl"), Path("verify"), ready_out=shown,
3907
+ config_text="shift:\n keep_old_sessions: 1\n")
3908
+ except RuntimeError as error:
3909
+ report(f"{label} {error}")
3910
+ return 1
3911
+ if len(shown) != 2:
3912
+ report(f"{label} the fixture did not return what ready printed: {shown!r}")
3913
+ return 1
3914
+ for needle in ("its conversation is kept", "claude attach 5b14fbae", str(verify), "the new shift's"):
3915
+ if needle not in shown[0]:
3916
+ report(f"{label} the hint does not say {needle!r}: {shown[0]!r}")
3917
+ return 1
3918
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
3919
+ report(f"{label} the scenario registry does not include it.")
3920
+ return 1
3921
+ report(f"{label.rstrip(':')} scenario passed.")
3922
+ return 0
3923
+
3924
+
3545
3925
  def validate_shift_cli_names_host_failure_scenario() -> int:
3546
3926
  """Issue #408: a hand-off the host cannot be asked about says why it waits."""
3547
3927
  label = "shift-cli-names-host-failure:"
@@ -51,7 +51,26 @@ const RECREATE = [
51
51
  [/^dev\.keel\.chat-bridge/, "keel chat bridge install"],
52
52
  ];
53
53
 
54
- // Each `dev.keel.*` LaunchAgent with the program it runs and whether that exists.
54
+ // A worktree under `.claude/worktrees/` is a checkout Keel creates and prunes (#503).
55
+ const REGENERATED = /[\\/]\.claude[\\/]worktrees[\\/]/;
56
+
57
+ function unescapeXml(value) {
58
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
59
+ }
60
+
61
+ // The directories a job runs in: its `WorkingDirectory` and the argument after
62
+ // `--repo`, each once, with whether it exists and whether Keel regenerates it.
63
+ function jobDirectories(text) {
64
+ const found = [
65
+ text.match(/<key>WorkingDirectory<\/key>\s*<string>([^<]*)<\/string>/),
66
+ text.match(/<string>--repo<\/string>\s*<string>([^<]*)<\/string>/),
67
+ ];
68
+ const paths = [...new Set(found.filter(Boolean).map((match) => unescapeXml(match[1])))];
69
+ return paths.map((dir) => ({ path: dir, exists: fs.existsSync(dir), regenerated: REGENERATED.test(`${dir}${path.sep}`) }));
70
+ }
71
+
72
+ // Each `dev.keel.*` LaunchAgent with the program it runs and whether that
73
+ // exists, and the directories it runs in (#503).
55
74
  function inspectJobs() {
56
75
  let names = [];
57
76
  try {
@@ -67,9 +86,9 @@ function inspectJobs() {
67
86
  // unreadable: reported as no program below
68
87
  }
69
88
  const match = text.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/);
70
- const program = match ? match[1].replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&") : null;
89
+ const program = match ? unescapeXml(match[1]) : null;
71
90
  const recreate = (RECREATE.find(([pattern]) => pattern.test(name)) || [null, "the command that wrote it"])[1];
72
- return { name, program, exists: Boolean(program) && fs.existsSync(program), recreate };
91
+ return { name, program, exists: Boolean(program) && fs.existsSync(program), recreate, directories: jobDirectories(text) };
73
92
  });
74
93
  }
75
94
 
package/src/core/shift.js CHANGED
@@ -636,6 +636,20 @@ function keptCopyOf(where, role, transcript) {
636
636
  }
637
637
  }
638
638
 
639
+ // Worktrees in use: the hand-off's, every bound one, and each other listed
640
+ // session's (#492 D2). `claude rm` deletes the worktree a session created, so a
641
+ // session whose worktree is in use stays listed. `ready` asks the same question
642
+ // to say so up front (#506 D1), without a listing, so the last reason is
643
+ // evaluated only when `listed` is given.
644
+ function worktreeInUse(roles, handOffWorktree, worktree, row, listed) {
645
+ const real = realpath(worktree);
646
+ if (handOffWorktree && realpath(handOffWorktree) === real) return "the new shift's worktree";
647
+ const binding = Object.entries(roles).find(([tree]) => realpath(tree) === real);
648
+ if (binding) return `bound to role ${binding[1]}`;
649
+ const other = (listed || []).find((r) => r && r !== row && r.cwd && realpath(r.cwd) === real);
650
+ return other ? `session ${other.id || other.sessionId.slice(0, 8)} runs there` : null;
651
+ }
652
+
639
653
  // After a delivered hand-over or a resume, the newest `keep` stopped background
640
654
  // sessions of the role stay listed; each older one is removed with `claude rm`
641
655
  // once Keel's store holds its transcript (#397 D2). `claude rm` leaves the
@@ -669,15 +683,7 @@ function removeOldSessions(claude, where, entry, keep) {
669
683
  })
670
684
  .filter(({ transcript, kept }) => transcript || fs.existsSync(kept))
671
685
  .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
- };
686
+ const inUse = (worktree, row) => worktreeInUse(roles, entry.worktree, worktree, row, listed);
681
687
  const removed = [];
682
688
  const notRemoved = old.slice(0, keep).map(({ row }) => ({ id: idOf(row), reason: "kept by `shift: keep_old_sessions`" }));
683
689
  for (const { row, worktree, transcript } of old.slice(keep)) {
@@ -1518,13 +1524,19 @@ const CLEAR_HINT = [
1518
1524
 
1519
1525
  // Who starts the new session (#293 D3): the coordinator that asked, nobody,
1520
1526
  // or — without a chat role — the person who opens it.
1521
- function clearHint(result) {
1527
+ function clearHint(result, where) {
1522
1528
  if (result.queued) {
1523
1529
  const own = result.cli.session.slice(0, 8);
1530
+ // The hand-over leaves this session listed when its worktree is in use (#492), and says so here (#506 D2).
1531
+ const host = hostWorktree({ id: own, sessionId: result.cli.session });
1532
+ const using = host && fs.existsSync(host)
1533
+ ? worktreeInUse(store.readJsonFile(path.join(where.root, "roles.json")), result.worktree, host, null, null) : null;
1524
1534
  // Nothing kept by default (#418): the old shift is removed once Keel holds its transcript.
1525
1535
  const kept = require("./config").readShiftDeclaration(result.worktree).keepOldSessions > 0
1526
- ? `its conversation is kept, \`claude attach ${own}\` reopens it`
1527
- : `then removes it from the session list once Keel's store holds its transcript, which \`keel shift history ${result.role} --show ${own}\` prints`;
1536
+ ? `its conversation is kept, \`claude attach ${own}\` reopens it${using ? `, beside the new shift, because its worktree ${host} is in use (${using})` : ""}`
1537
+ : using
1538
+ ? `it stays in \`claude agents\`, because its worktree ${host} is in use (${using}) and \`claude rm\` would delete it, and \`claude attach ${own}\` brings it back beside the new shift`
1539
+ : `then removes it from the session list once Keel's store holds its transcript, which \`keel shift history ${result.role} --show ${own}\` prints`;
1528
1540
  return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session has finished, "
1529
1541
  + `a waiter stops it — ${kept} — and starts a new session `
1530
1542
  + `named for its start, \`${result.role} · <MM-DD HH:MM>\`, in ${result.worktree} that runs \`keel shift resume\`; \`keel tick\` does the same if the waiter is gone. \`keel shift status\` shows the hand-off.`;
@@ -1620,7 +1632,7 @@ function runShift(argv) {
1620
1632
  case "ready": {
1621
1633
  const result = ready(where, { ...options, text: rest.join(" ") });
1622
1634
  const whose = result.role || "this worktree (no chat role, so no request to close)";
1623
- const hint = clearHint(result);
1635
+ const hint = clearHint(result, where);
1624
1636
  out({ ...result, clear: hint }, `Stored the shift note for ${whose} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${hint}`);
1625
1637
  return 0;
1626
1638
  }
package/src/core/tick.js CHANGED
@@ -41,10 +41,29 @@ function patrolWorktrees(where) {
41
41
  if (!bound.length) {
42
42
  return { declaration, worktree: null, why: `No worktree is bound to role ${declaration.role}; bind one with \`keel chat role --set ${declaration.role}\` there first.` };
43
43
  }
44
- return { declaration, worktree: bound[0], why: null };
44
+ // A removed worktree stays bound until `keel chat role --prune` (#503 D3):
45
+ // the first one that still exists is used, and when none does the patrol
46
+ // does not start in a directory that is gone.
47
+ const present = bound.filter((worktree) => fs.existsSync(worktree));
48
+ if (!present.length) {
49
+ return { declaration, worktree: null, why: `Role ${declaration.role} is bound to ${bound.join(", ")}, which no longer ${bound.length === 1 ? "exists" : "exist"}; \`keel chat role --prune\` drops the binding, and \`keel chat role --set ${declaration.role}\` in a worktree that exists binds the role again.` };
50
+ }
51
+ return { declaration, worktree: present[0], why: null };
45
52
  });
46
53
  }
47
54
 
55
+ // The directory a launchd job names so that it outlives the role's worktree
56
+ // (#503 D1): the repository's main checkout, from which every run finds the
57
+ // bound worktree again. It stands in only when it exists and its
58
+ // keel/config.yaml declares a `patrol:`, since that is the file `keel tick
59
+ // --repo` reads; otherwise `dir` is null and `why` says which.
60
+ function stableRepo(where) {
61
+ if (path.basename(where.common) !== ".git") return { dir: null, why: "the repository has no main checkout" };
62
+ const dir = path.dirname(where.common);
63
+ if (!require("./config").readPatrolDeclarations(dir).declarations.length) return { dir: null, why: `the main checkout ${dir} declares no \`patrol:\`` };
64
+ return { dir, why: null };
65
+ }
66
+
48
67
  // Free space on a worktree's filesystem in GiB, as `df -g` reports it (#456 D1).
49
68
  function freeDiskGb(dir) {
50
69
  try {
@@ -200,7 +219,7 @@ function tick(where, now = new Date()) {
200
219
  const own = listed ? ((state.patrols || {})[role] || (role === all[0].declaration.role ? state.patrol : null)) : state.patrol;
201
220
  const due = own && own.next_at ? Date.parse(own.next_at) : NaN;
202
221
  if (!Number.isNaN(due) && due > now.getTime()) {
203
- return { role, ran: false, why: `${listed ? `${role}'s ` : ""}patrol not due until ${own.next_at}`, next_at: own.next_at };
222
+ return { role, ran: false, why: `${listed ? `${role}'s ` : ""}patrol not due until ${own.next_at}`, next_at: own.next_at, worktree: found.worktree };
204
223
  }
205
224
  // The host task this replaces fetched first (F1); a failed fetch is reported
206
225
  // and the patrol still runs on the refs it has.
@@ -226,7 +245,7 @@ function tick(where, now = new Date()) {
226
245
  else state.patrol = record;
227
246
  store.writeJsonAtomic(where, stateFile(where), state);
228
247
  return {
229
- role, listed, ran: true, exit: ran.status, next_at: next, rule: payload.next_rule || null,
248
+ role, listed, ran: true, worktree: found.worktree, exit: ran.status, next_at: next, rule: payload.next_rule || null,
230
249
  fetchError, diskError: disk.error, error: ran.status === 1 ? String(ran.stderr || "").trim() : null,
231
250
  };
232
251
  });
@@ -267,7 +286,11 @@ function task(where) {
267
286
  if (!found.worktree) throw new TickError(found.why);
268
287
  const label = `dev.keel.tick.${where.project.replace(/[^A-Za-z0-9.-]/g, "-")}`;
269
288
  const logs = path.join(where.root, "tick");
270
- const args = [stableNode(), KEEL, "tick", "--repo", found.worktree];
289
+ // The job names the main checkout when it can stand in (#503 D1), so that
290
+ // binding the role elsewhere or pruning a worktree changes nothing it names.
291
+ const stable = stableRepo(where);
292
+ const repo = stable.dir || found.worktree;
293
+ const args = [stableNode(), KEEL, "tick", "--repo", repo];
271
294
  const plist = [
272
295
  '<?xml version="1.0" encoding="UTF-8"?>',
273
296
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -275,7 +298,7 @@ function task(where) {
275
298
  "<dict>",
276
299
  " <key>Label</key>", ` <string>${xml(label)}</string>`,
277
300
  " <key>ProgramArguments</key>", " <array>", ...args.map((arg) => ` <string>${xml(arg)}</string>`), " </array>",
278
- " <key>WorkingDirectory</key>", ` <string>${xml(found.worktree)}</string>`,
301
+ " <key>WorkingDirectory</key>", ` <string>${xml(repo)}</string>`,
279
302
  " <key>EnvironmentVariables</key>", " <dict>", " <key>PATH</key>", ` <string>${xml(launchdPath(process.env.PATH))}</string>`, " </dict>",
280
303
  " <key>StartInterval</key>", ` <integer>${INTERVAL_SECONDS}</integer>`,
281
304
  " <key>StandardOutPath</key>", ` <string>${xml(path.join(logs, "tick.log"))}</string>`,
@@ -284,13 +307,19 @@ function task(where) {
284
307
  "</plist>",
285
308
  ].join("\n");
286
309
  const target = path.join(os.homedir(), "Library", "LaunchAgents", `${label}.plist`);
287
- return { label, interval: INTERVAL_SECONDS, worktree: found.worktree, plist, target,
310
+ return { label, interval: INTERVAL_SECONDS, repo, stable: Boolean(stable.dir), why: stable.why, worktree: found.worktree, plist, target,
288
311
  install: [`mkdir -p ${path.dirname(target)} && cat > ${target} <<'PLIST'\n${plist}\nPLIST`, `launchctl bootstrap gui/${process.getuid ? process.getuid() : "<uid>"} ${target}`] };
289
312
  }
290
313
 
291
314
  function renderTask(job) {
315
+ // The main checkout is named when it can stand in, and the tick finds each
316
+ // role's bound worktree on every run; otherwise the worktree is named, and
317
+ // the job stops working if that worktree moves (#503).
318
+ const where = job.stable
319
+ ? `in the main checkout ${job.repo}, and the tick runs each declared patrol in the worktree its role is bound to when due, so binding a role elsewhere needs no new job`
320
+ : `in the worktree ${job.repo}, because ${job.why}; the job stops working if that worktree is moved or pruned, so declare the \`patrol:\` in the main checkout and print it again`;
292
321
  return [
293
- `launchd job for \`keel tick\` (label ${job.label}): it calls \`keel tick\` every ${job.interval} s, and the tick runs the patrol of the worktree ${job.worktree} when due. Keel creates nothing: install it with the two commands below.`,
322
+ `launchd job for \`keel tick\` (label ${job.label}): it calls \`keel tick\` every ${job.interval} s ${where}. Keel creates nothing: install it with the two commands below.`,
294
323
  "",
295
324
  job.plist,
296
325
  "",