@christang/keel 5.216.0 → 5.217.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.217.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.217.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.217.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.217.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.217.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.217.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.217.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.217.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.216.0"
41
+ PROTOCOL_VERSION = "5.217.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -487,6 +487,9 @@ SCENARIOS: tuple = (
487
487
  ("tick-checks-issues", shift.validate_tick_checks_issues_scenario),
488
488
  ("tick-reports-issue-checks", shift.validate_tick_reports_issue_checks_scenario),
489
489
  ("launchd-stable-node", shift.validate_launchd_stable_node_scenario),
490
+ ("tick-task-names-main-checkout", shift.validate_tick_task_names_main_checkout_scenario),
491
+ ("tick-skips-missing-bound-worktree", shift.validate_tick_skips_missing_bound_worktree_scenario),
492
+ ("launchd-doctor-names-job-directories", shift.validate_launchd_doctor_names_job_directories_scenario),
490
493
  ("shift-slash-command", shift.validate_shift_slash_command_scenario),
491
494
  ("shift-check-skips-host-keep-awake", shift.validate_shift_check_skips_host_keep_awake_scenario),
492
495
  ("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
 
@@ -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/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
  "",