@christang/keel 5.215.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.
- package/.claude-plugin/plugin.json +1 -1
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +24 -8
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/scripts/validation/common.py +2 -2
- package/scripts/validation/registry.py +6 -0
- package/scripts/validation/shift.py +424 -0
- package/src/core/config.js +13 -1
- package/src/core/launchd.js +22 -3
- package/src/core/shift.js +38 -5
- package/src/core/tick.js +36 -7
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
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",
|
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
|
-
|
|
2518
|
-
for (const job of
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
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 (!
|
|
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
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
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.
|
|
9
|
+
"version": "5.217.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@fission-ai/openspec": "^1.4.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
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.
|
|
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.
|
|
38
|
+
PACKAGE_VERSION = "5.217.0"
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
PROTOCOL_VERSION = "5.
|
|
41
|
+
PROTOCOL_VERSION = "5.217.0"
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
|
|
@@ -487,9 +487,15 @@ 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),
|
|
496
|
+
("shift-cli-handover-passes-default-model", shift.validate_shift_cli_handover_passes_default_model_scenario),
|
|
497
|
+
("shift-cli-declared-model-wins", shift.validate_shift_cli_declared_model_wins_scenario),
|
|
498
|
+
("shift-cli-handover-names-no-model-when-none", shift.validate_shift_cli_handover_names_no_model_when_none_scenario),
|
|
493
499
|
("patrol-exit-says-who-acts", shift.validate_patrol_exit_says_who_acts_scenario),
|
|
494
500
|
("patrol-nudge", shift.validate_patrol_nudge_scenario),
|
|
495
501
|
("patrol-escalate", shift.validate_patrol_escalate_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
|
|
|
@@ -3754,6 +4030,154 @@ def validate_shift_cli_handover_claims_once_scenario() -> int:
|
|
|
3754
4030
|
return 0
|
|
3755
4031
|
|
|
3756
4032
|
|
|
4033
|
+
def handover_model_case(*, user=None, project=None, local=None, shift_yaml="", anthropic_model=None, raw_user=None) -> dict:
|
|
4034
|
+
"""One CLI hand-over (#500) under the settings given; the call that started the new session, the entry and `shift status`.
|
|
4035
|
+
|
|
4036
|
+
`user`, `project` and `local` are the `model` values of the user's
|
|
4037
|
+
`settings.json` (in `CLAUDE_CONFIG_DIR`), the worktree's `.claude/settings.json`
|
|
4038
|
+
and its `.claude/settings.local.json`; `raw_user` is that user file's text as is.
|
|
4039
|
+
"""
|
|
4040
|
+
OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
|
|
4041
|
+
with tempfile.TemporaryDirectory(prefix="keel-shift-500-") as raw:
|
|
4042
|
+
base = Path(raw)
|
|
4043
|
+
s = handover_retry_scratch(base, OLD)
|
|
4044
|
+
try:
|
|
4045
|
+
config_dir = base / "claude-config"
|
|
4046
|
+
env = {k: v for k, v in s["env"].items() if k != "ANTHROPIC_MODEL"}
|
|
4047
|
+
env["CLAUDE_CONFIG_DIR"] = str(config_dir)
|
|
4048
|
+
if anthropic_model:
|
|
4049
|
+
env["ANTHROPIC_MODEL"] = anthropic_model
|
|
4050
|
+
if raw_user is not None:
|
|
4051
|
+
write_text(config_dir / "settings.json", raw_user)
|
|
4052
|
+
elif user is not None:
|
|
4053
|
+
write_text(config_dir / "settings.json", json.dumps({"model": user, "effortLevel": "xhigh"}))
|
|
4054
|
+
if project is not None:
|
|
4055
|
+
write_text(s["verify"] / ".claude" / "settings.json", json.dumps({"model": project}))
|
|
4056
|
+
if local is not None:
|
|
4057
|
+
write_text(s["verify"] / ".claude" / "settings.local.json", json.dumps({"model": local}))
|
|
4058
|
+
if shift_yaml:
|
|
4059
|
+
write_text(s["verify"] / "keel" / "config.yaml", shift_yaml)
|
|
4060
|
+
run_keel(s["verify"], "tick", "--repo", str(s["rtl"]), env=env)
|
|
4061
|
+
starts = [json.loads(line)["argv"] for line in s["calls"].read_text().splitlines()
|
|
4062
|
+
if json.loads(line)["argv"][:1] == ["--bg"] and "--resume" not in json.loads(line)["argv"]]
|
|
4063
|
+
entry = json.loads(s["queue"].read_text())
|
|
4064
|
+
status = run_keel(s["verify"], "shift", "status", env=env).stdout
|
|
4065
|
+
return {"argv": starts[0] if starts else None, "entry": entry, "status": status, "starts": len(starts)}
|
|
4066
|
+
finally:
|
|
4067
|
+
with contextlib.suppress(OSError):
|
|
4068
|
+
os.kill(s["process"], signal.SIGKILL)
|
|
4069
|
+
|
|
4070
|
+
|
|
4071
|
+
def model_args(argv) -> list:
|
|
4072
|
+
"""The `--model` and `--effort` arguments of a start call, in the order given, before the prompt."""
|
|
4073
|
+
found = []
|
|
4074
|
+
for flag in ("--model", "--effort"):
|
|
4075
|
+
if argv and flag in argv[:-1]:
|
|
4076
|
+
found += [flag, argv[argv.index(flag) + 1]]
|
|
4077
|
+
return found
|
|
4078
|
+
|
|
4079
|
+
|
|
4080
|
+
def validate_shift_cli_handover_passes_default_model_scenario() -> int:
|
|
4081
|
+
"""Issue #500: a hand-over names the model the owner would get, in the host's own order.
|
|
4082
|
+
|
|
4083
|
+
Measured 2026-11-03: the session a hand-over started ran sonnet although the
|
|
4084
|
+
owner's `settings.json` says opus, because the call named no model and the
|
|
4085
|
+
host chose one. The call now carries `--model` after `--permission-mode`.
|
|
4086
|
+
"""
|
|
4087
|
+
label = "shift-cli-handover-passes-default-model:"
|
|
4088
|
+
steps = [
|
|
4089
|
+
({"user": "opus"}, "opus", "user settings"),
|
|
4090
|
+
({"user": "opus", "project": "sonnet"}, "sonnet", "project settings"),
|
|
4091
|
+
({"user": "opus", "project": "sonnet", "local": "haiku"}, "haiku", "project-local settings"),
|
|
4092
|
+
({"user": "opus", "project": "sonnet", "local": "haiku", "anthropic_model": "fable"}, "fable", "ANTHROPIC_MODEL"),
|
|
4093
|
+
]
|
|
4094
|
+
for case, model, source in steps:
|
|
4095
|
+
got = handover_model_case(**case)
|
|
4096
|
+
argv = got["argv"]
|
|
4097
|
+
if got["entry"].get("state") != "delivered":
|
|
4098
|
+
report(f"{label} with {sorted(case)} the hand-off was not delivered: {got['entry']!r}")
|
|
4099
|
+
return 1
|
|
4100
|
+
if not argv:
|
|
4101
|
+
report(f"{label} with {sorted(case)} the hand-off was delivered but no `claude --bg` start call was recorded.")
|
|
4102
|
+
return 1
|
|
4103
|
+
if argv[3:7] != ["--permission-mode", "auto", "--model", model]:
|
|
4104
|
+
report(f"{label} with {sorted(case)} the start call is {argv!r}, not `--permission-mode auto --model {model}` before the prompt.")
|
|
4105
|
+
return 1
|
|
4106
|
+
if "keel shift resume" not in argv[-1]:
|
|
4107
|
+
report(f"{label} with {sorted(case)} the prompt is no longer last in the start call: {argv!r}")
|
|
4108
|
+
return 1
|
|
4109
|
+
if got["entry"].get("model") != model or got["entry"].get("model_source") != source:
|
|
4110
|
+
report(f"{label} with {sorted(case)} the entry records {got['entry'].get('model')!r} from {got['entry'].get('model_source')!r}, not {model!r} from {source!r}.")
|
|
4111
|
+
return 1
|
|
4112
|
+
if model not in got["status"] or source not in got["status"]:
|
|
4113
|
+
report(f"{label} with {sorted(case)} `keel shift status` does not show {model!r} and {source!r}: {got['status']!r}")
|
|
4114
|
+
return 1
|
|
4115
|
+
if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
|
|
4116
|
+
report(f"{label} the scenario registry does not include it.")
|
|
4117
|
+
return 1
|
|
4118
|
+
report(f"{label.rstrip(':')} scenario passed.")
|
|
4119
|
+
return 0
|
|
4120
|
+
|
|
4121
|
+
|
|
4122
|
+
def validate_shift_cli_declared_model_wins_scenario() -> int:
|
|
4123
|
+
"""Issue #500: `shift: model:` and `shift: effort:` start a role's shifts on something else, on purpose."""
|
|
4124
|
+
label = "shift-cli-declared-model-wins:"
|
|
4125
|
+
got = handover_model_case(user="opus", project="haiku", local="haiku", anthropic_model="fable",
|
|
4126
|
+
shift_yaml="shift:\n model: sonnet\n effort: high\n")
|
|
4127
|
+
if model_args(got["argv"]) != ["--model", "sonnet", "--effort", "high"] or got["argv"][3:5] != ["--permission-mode", "auto"]:
|
|
4128
|
+
report(f"{label} the declaration did not win: {got['argv']!r}")
|
|
4129
|
+
return 1
|
|
4130
|
+
if got["entry"].get("model") != "sonnet" or got["entry"].get("model_source") != "declared":
|
|
4131
|
+
report(f"{label} the entry does not record the declared model: {got['entry']!r}")
|
|
4132
|
+
return 1
|
|
4133
|
+
bad = handover_model_case(user="opus", shift_yaml="shift:\n effort: extreme\n")
|
|
4134
|
+
if "--effort" in (bad["argv"] or []):
|
|
4135
|
+
report(f"{label} an effort Keel cannot read was passed: {bad['argv']!r}")
|
|
4136
|
+
return 1
|
|
4137
|
+
if model_args(bad["argv"]) != ["--model", "opus"]:
|
|
4138
|
+
report(f"{label} an effort Keel cannot read took the model with it: {bad['argv']!r}")
|
|
4139
|
+
return 1
|
|
4140
|
+
for needle in ("extreme", "low, medium, high, xhigh, max"):
|
|
4141
|
+
if needle not in bad["status"]:
|
|
4142
|
+
report(f"{label} `keel shift status` does not name {needle!r}: {bad['status']!r}")
|
|
4143
|
+
return 1
|
|
4144
|
+
if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
|
|
4145
|
+
report(f"{label} the scenario registry does not include it.")
|
|
4146
|
+
return 1
|
|
4147
|
+
report(f"{label.rstrip(':')} scenario passed.")
|
|
4148
|
+
return 0
|
|
4149
|
+
|
|
4150
|
+
|
|
4151
|
+
def validate_shift_cli_handover_names_no_model_when_none_scenario() -> int:
|
|
4152
|
+
"""Issue #500: when nothing names a model the call names none, and the hand-over still happens."""
|
|
4153
|
+
label = "shift-cli-handover-names-no-model-when-none:"
|
|
4154
|
+
cases = {
|
|
4155
|
+
"no source": {},
|
|
4156
|
+
"invalid JSON": {"raw_user": "{not json"},
|
|
4157
|
+
"model not a string": {"raw_user": json.dumps({"model": {"name": "opus"}})},
|
|
4158
|
+
"empty model": {"raw_user": json.dumps({"model": ""})},
|
|
4159
|
+
}
|
|
4160
|
+
for name, case in cases.items():
|
|
4161
|
+
got = handover_model_case(**case)
|
|
4162
|
+
if got["entry"].get("state") != "delivered":
|
|
4163
|
+
report(f"{label} with {name} the hand-off was not delivered: {got['entry']!r}")
|
|
4164
|
+
return 1
|
|
4165
|
+
if not got["argv"]:
|
|
4166
|
+
report(f"{label} with {name} the hand-off was delivered but no `claude --bg` start call was recorded.")
|
|
4167
|
+
return 1
|
|
4168
|
+
if model_args(got["argv"]):
|
|
4169
|
+
report(f"{label} with {name} the call names a model: {got['argv']!r}")
|
|
4170
|
+
return 1
|
|
4171
|
+
if "model" in got["entry"] or "model_source" in got["entry"]:
|
|
4172
|
+
report(f"{label} with {name} the entry records a model: {got['entry']!r}")
|
|
4173
|
+
return 1
|
|
4174
|
+
if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
|
|
4175
|
+
report(f"{label} the scenario registry does not include it.")
|
|
4176
|
+
return 1
|
|
4177
|
+
report(f"{label.rstrip(':')} scenario passed.")
|
|
4178
|
+
return 0
|
|
4179
|
+
|
|
4180
|
+
|
|
3757
4181
|
def validate_shift_cli_retries_failed_handover_scenario() -> int:
|
|
3758
4182
|
"""Issue #408, second loop: a failed hand-off is retried within a bound (D4, D5).
|
|
3759
4183
|
|
package/src/core/config.js
CHANGED
|
@@ -1087,6 +1087,9 @@ function readPatrolDeclaration(repo, options = {}) {
|
|
|
1087
1087
|
|
|
1088
1088
|
// `shift: permission_mode:` for the session a CLI hand-off starts (#357 D5).
|
|
1089
1089
|
const PERMISSION_MODES = ["default", "acceptEdits", "auto", "plan", "bypassPermissions"];
|
|
1090
|
+
// `shift: model:` is a name or alias the host takes after `--model`; `shift: effort:` one of its `--effort` levels (#500).
|
|
1091
|
+
const SHIFT_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:\[\]-]*$/;
|
|
1092
|
+
const SHIFT_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
1090
1093
|
// `shift: keep_old_sessions:`, how many stopped old shift sessions a hand-over
|
|
1091
1094
|
// leaves listed per role (#397 D2): a whole number, 0 when absent or unreadable,
|
|
1092
1095
|
// so the old shift leaves the session list where the owner could mistake it for
|
|
@@ -1102,7 +1105,16 @@ function readShiftDeclaration(repo) {
|
|
|
1102
1105
|
let keepOldSessions = 0;
|
|
1103
1106
|
if (keep !== undefined && /^\d+$/.test(String(keep).trim())) keepOldSessions = Number(String(keep).trim());
|
|
1104
1107
|
else if (keep !== undefined) messages.push(`keel/config.yaml shift: keep_old_sessions \`${keep}\` is not a whole number, so 0 applies.`);
|
|
1105
|
-
|
|
1108
|
+
// `model:` and `effort:` start a role's shifts on something else on purpose (#500).
|
|
1109
|
+
let model = null;
|
|
1110
|
+
const declaredModel = block.model === undefined ? undefined : String(block.model).trim();
|
|
1111
|
+
if (declaredModel !== undefined && SHIFT_MODEL.test(declaredModel)) model = declaredModel;
|
|
1112
|
+
else if (declaredModel !== undefined) messages.push(`keel/config.yaml shift: model \`${declaredModel}\` is not a model name or alias, so it is ignored.`);
|
|
1113
|
+
let effort = null;
|
|
1114
|
+
const declaredEffort = block.effort === undefined ? undefined : String(block.effort).trim();
|
|
1115
|
+
if (SHIFT_EFFORTS.includes(declaredEffort)) effort = declaredEffort;
|
|
1116
|
+
else if (declaredEffort !== undefined) messages.push(`keel/config.yaml shift: effort \`${declaredEffort}\` is not one of ${SHIFT_EFFORTS.join(", ")}, so it is ignored.`);
|
|
1117
|
+
return { permissionMode, keepOldSessions, model, effort, message: messages.length ? messages.join(" ") : null };
|
|
1106
1118
|
}
|
|
1107
1119
|
|
|
1108
1120
|
// `branches:` (#469 D1, D7): `trunk:` names the branches beyond the remote
|
package/src/core/launchd.js
CHANGED
|
@@ -51,7 +51,26 @@ const RECREATE = [
|
|
|
51
51
|
[/^dev\.keel\.chat-bridge/, "keel chat bridge install"],
|
|
52
52
|
];
|
|
53
53
|
|
|
54
|
-
//
|
|
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(/</g, "<").replace(/>/g, ">").replace(/&/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]
|
|
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
|
@@ -822,6 +822,36 @@ function claim(where, queued, sessions) {
|
|
|
822
822
|
});
|
|
823
823
|
}
|
|
824
824
|
|
|
825
|
+
// The model a hand-over starts the new session on (#500). The host chose one
|
|
826
|
+
// itself when the call named none, and on 2026-11-01 it chose sonnet over the
|
|
827
|
+
// owner's `model: opus`, so the call names the owner's default: the declared
|
|
828
|
+
// `shift: model:`, else the first of the host's own sources that names one, in
|
|
829
|
+
// its order. A missing file, invalid JSON, or a value that is not a plain
|
|
830
|
+
// string names nothing and the next source is tried; managed policy settings
|
|
831
|
+
// are not read. Null when no source names a model: the call then names none.
|
|
832
|
+
function resolveShiftModel(worktree, declared) {
|
|
833
|
+
if (declared && declared.model) return { model: declared.model, source: "declared" };
|
|
834
|
+
const named = (value) => (typeof value === "string" && value.trim() && !value.trim().startsWith("-") ? value.trim() : null);
|
|
835
|
+
const fromEnv = named(process.env.ANTHROPIC_MODEL);
|
|
836
|
+
if (fromEnv) return { model: fromEnv, source: "ANTHROPIC_MODEL" };
|
|
837
|
+
const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
|
|
838
|
+
const files = [
|
|
839
|
+
[path.join(worktree, ".claude", "settings.local.json"), "project-local settings"],
|
|
840
|
+
[path.join(worktree, ".claude", "settings.json"), "project settings"],
|
|
841
|
+
[path.join(config, "settings.json"), "user settings"],
|
|
842
|
+
];
|
|
843
|
+
for (const [file, source] of files) {
|
|
844
|
+
let model = null;
|
|
845
|
+
try {
|
|
846
|
+
model = named(JSON.parse(fs.readFileSync(file, "utf8")).model);
|
|
847
|
+
} catch {
|
|
848
|
+
model = null;
|
|
849
|
+
}
|
|
850
|
+
if (model) return { model, source };
|
|
851
|
+
}
|
|
852
|
+
return null;
|
|
853
|
+
}
|
|
854
|
+
|
|
825
855
|
// One step of the waker (#357 D2): a busy or unfinished old session waits; a
|
|
826
856
|
// finished or gone one is retired (stopped) and a new session starts. A claim
|
|
827
857
|
// left by a runner that died is settled, and a failed start is tried again
|
|
@@ -856,14 +886,17 @@ function handOver(where, only = null) {
|
|
|
856
886
|
// `stop`, `attach` and `logs` take the 8-character job id, not the full
|
|
857
887
|
// session id (`No job matching`, measured 2026-10-19).
|
|
858
888
|
if (row) retire(claude, entry, row);
|
|
859
|
-
const
|
|
889
|
+
const declaration = readShiftDeclaration(entry.worktree);
|
|
860
890
|
const name = sessionName(entry.role);
|
|
861
|
-
const
|
|
862
|
-
|
|
863
|
-
|
|
891
|
+
const chosen = resolveShiftModel(entry.worktree, declaration);
|
|
892
|
+
const startArgs = ["--bg", "-n", name, "--permission-mode", declaration.permissionMode,
|
|
893
|
+
...(chosen ? ["--model", chosen.model] : []), ...(declaration.effort ? ["--effort", declaration.effort] : []),
|
|
894
|
+
SHIFT_START_TEXT(entry.role)];
|
|
895
|
+
const started = spawnSync(claude, startArgs, { cwd: entry.worktree, encoding: "utf8", timeout: hostTimeout() });
|
|
864
896
|
const output = `${started.stdout || ""}`;
|
|
865
897
|
if (!started.error && started.status === 0) {
|
|
866
898
|
const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
|
|
899
|
+
if (chosen) Object.assign(entry, { model: chosen.model, model_source: chosen.source });
|
|
867
900
|
done.push(deliver(claude, where, entry, id, name, false));
|
|
868
901
|
} else {
|
|
869
902
|
const reason = started.error ? hostTrouble(started, "claude --bg") : String(started.stderr || output).trim().split(/\r?\n/).pop();
|
|
@@ -903,7 +936,7 @@ function waitForHandOver(where, role) {
|
|
|
903
936
|
|
|
904
937
|
function describeHandOff(entry) {
|
|
905
938
|
const tail = entry.state === "delivered"
|
|
906
|
-
? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}`
|
|
939
|
+
? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}${entry.model ? ` on model ${entry.model} (${entry.model_source})` : ""}`
|
|
907
940
|
: entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}; ${retryNote(entry)}`
|
|
908
941
|
: entry.state === "starting" ? `starting since ${entry.starting_at} (attempt ${entry.attempts} of ${HANDOVER_ATTEMPTS})`
|
|
909
942
|
: entry.waiting_on ? `pending: cannot ask the host — ${entry.waiting_on}` : "pending: waits for the session to go idle";
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
|
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
|
"",
|