@christang/keel 5.85.0 → 5.87.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.
@@ -41,8 +41,8 @@ REQUIRED_SCRIPTS = [
41
41
  "scripts/validate_plugin.py",
42
42
  ]
43
43
 
44
- PACKAGE_VERSION = "5.85.0"
45
- PROTOCOL_VERSION = "5.85.0"
44
+ PACKAGE_VERSION = "5.87.0"
45
+ PROTOCOL_VERSION = "5.87.0"
46
46
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
47
47
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
48
48
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -761,7 +761,7 @@ def validate_openspec_schema(errors: list[str]) -> None:
761
761
  "Execution recommendation",
762
762
  "Autonomy boundary",
763
763
  "current Keel agent remains task owner and executor",
764
- "Do not hand Keel-managed execution to another agent",
764
+ "Keep task decisions in the current agent",
765
765
  "Modify only files listed under Touch",
766
766
  "repository-wide read authority is read-only",
767
767
  "Out-of-scope Need",
@@ -2899,6 +2899,11 @@ def validate_chat_human_view_scenario() -> int:
2899
2899
  report(f"{label} the presence line gives no state for {role}: {presence.group(1)}")
2900
2900
  return 1
2901
2901
 
2902
+ chat(rtl, "post", "soc", "@all standup in five")
2903
+ everyone = chat(rtl, "soc", "--peek").stdout
2904
+ if "@all @all" in everyone:
2905
+ report(f"{label} the view repeats a mention its text already shows: {everyone}")
2906
+ return 1
2902
2907
  recent = chat(rtl, "soc", "--peek", "--since", "1m")
2903
2908
  if "back-dated note" in recent.stdout:
2904
2909
  report(f"{label} --since 1m still shows a record from two hours ago.")
@@ -2922,6 +2927,17 @@ def validate_chat_human_view_scenario() -> int:
2922
2927
  deadline = time.time() + 5
2923
2928
  while time.time() < deadline and not any("followed message" in line for line in lines_seen):
2924
2929
  time.sleep(0.2)
2930
+ # A record whose id sorts before ones already shown — written by a
2931
+ # machine whose clock runs behind — must still be printed (#196).
2932
+ late_id = "20200101T000001000Z-verify-1a7e1a"
2933
+ write_text(
2934
+ chat_log(rtl, "soc") / f"{late_id}.md",
2935
+ f"---\nid: {late_id}\ngroup: soc\nkind: message\nfrom: verify\n"
2936
+ "created: 2020-01-01T00:00:01+00:00\n---\n\nlate arrival\n",
2937
+ )
2938
+ deadline = time.time() + 5
2939
+ while time.time() < deadline and not any("late arrival" in line for line in lines_seen):
2940
+ time.sleep(0.2)
2925
2941
  finally:
2926
2942
  follower.terminate()
2927
2943
  follower.wait(timeout=5)
@@ -2929,6 +2945,9 @@ def validate_chat_human_view_scenario() -> int:
2929
2945
  if "followed message" not in seen:
2930
2946
  report(f"{label} --follow did not print a message posted from another worktree within five seconds: {seen!r}")
2931
2947
  return 1
2948
+ if "late arrival" not in seen:
2949
+ report(f"{label} --follow did not print a record whose id sorts before the ones already shown: {seen!r}")
2950
+ return 1
2932
2951
 
2933
2952
  transcript = mailbox_common_dir(rtl) / "keel-chat" / "transcripts" / "soc.md"
2934
2953
  if not transcript.is_file():
@@ -3140,9 +3159,13 @@ def validate_chat_bridge_outbound_scenario() -> int:
3140
3159
  return 1
3141
3160
 
3142
3161
  before = len(slack.calls_to("chat.postMessage"))
3143
- again = chat(rtl, "bridge", "run", "--once")
3162
+ # launchd starts the bridge in `/`, outside every repository, so the
3163
+ # second run starts outside one too.
3164
+ elsewhere = base / "elsewhere"
3165
+ elsewhere.mkdir()
3166
+ again = chat(elsewhere, "bridge", "run", "--once")
3144
3167
  if again.returncode != 0:
3145
- report(f"{label} a second bridge run failed: {again.stderr.strip()}")
3168
+ report(f"{label} a bridge run started outside any repository failed: {again.stderr.strip()}")
3146
3169
  return 1
3147
3170
  if len(slack.calls_to("chat.postMessage")) != before:
3148
3171
  report(f"{label} a second run posted records again.")
@@ -3704,6 +3727,501 @@ def validate_chat_archive_scenario() -> int:
3704
3727
  return 0
3705
3728
 
3706
3729
 
3730
+ def validate_chat_reply_marks_read_scenario() -> int:
3731
+ """Issue #201: answering a record marks it read for the one who answered.
3732
+
3733
+ A reply moves the poster's cursor to the replied-to record and `done`
3734
+ moves the closer's cursor to the todo, never backwards, so records after
3735
+ the answered one stay unread.
3736
+ """
3737
+ label = "chat-reply-marks-read:"
3738
+ with tempfile.TemporaryDirectory(prefix="keel-chat-reply-read-") as raw:
3739
+ base = Path(raw)
3740
+ rtl, verify, env = chat_scratch_group(base)
3741
+
3742
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3743
+ return run_keel(cwd, "chat", *args, env=env)
3744
+
3745
+ def unread_ids() -> list[str]:
3746
+ return [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
3747
+
3748
+ first = chat_json(chat(rtl, "post", "soc", "@verify first", "--json")).get("id", "")
3749
+ second = chat_json(chat(rtl, "post", "soc", "@verify second", "--json")).get("id", "")
3750
+ if not first or not second:
3751
+ report(f"{label} the two posts did not report ids.")
3752
+ return 1
3753
+ replied = chat(verify, "post", "soc", "on it", "--reply-to", first)
3754
+ if replied.returncode != 0:
3755
+ report(f"{label} the reply failed: {replied.stderr.strip()}")
3756
+ return 1
3757
+ after_reply = unread_ids()
3758
+ if first in after_reply:
3759
+ report(f"{label} the replied-to record is still unread for verify: {after_reply!r}")
3760
+ return 1
3761
+ if second not in after_reply:
3762
+ report(f"{label} the record after the replied-to one is no longer unread: {after_reply!r}")
3763
+ return 1
3764
+ readers = chat_json(chat(rtl, "show", first, "--json")).get("readers", [])
3765
+ if "verify" not in readers:
3766
+ report(f"{label} show does not list verify as a reader after its reply: {readers!r}")
3767
+ return 1
3768
+
3769
+ task = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun", "--json")).get("id", "")
3770
+ closed = chat(verify, "done", task)
3771
+ if closed.returncode != 0:
3772
+ report(f"{label} done failed: {closed.stderr.strip()}")
3773
+ return 1
3774
+ after_done = unread_ids()
3775
+ if task in after_done:
3776
+ report(f"{label} the closed todo is still unread for verify: {after_done!r}")
3777
+ return 1
3778
+
3779
+ third = chat_json(chat(rtl, "post", "soc", "@verify third", "--json")).get("id", "")
3780
+ chat(verify, "post", "soc", "late answer", "--reply-to", first)
3781
+ if third not in unread_ids():
3782
+ report(f"{label} a reply to a record behind the cursor moved it past a later unread record.")
3783
+ return 1
3784
+
3785
+ if "chat-reply-marks-read" not in {name for name, _ in SCENARIOS}:
3786
+ report(f"{label} scenario is not registered.")
3787
+ return 1
3788
+ report("chat-reply-marks-read scenario passed.")
3789
+ return 0
3790
+
3791
+
3792
+ FAKE_CODEX = r"""#!/usr/bin/env node
3793
+ const fs = require("fs");
3794
+ let input = "";
3795
+ try { input = fs.readFileSync(0, "utf8"); } catch {}
3796
+ fs.appendFileSync(process.env.FAKE_CODEX_LOG, JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), stdin: input }) + "\n");
3797
+ console.log(JSON.stringify({ type: "thread.started", thread_id: "thread-fake-1" }));
3798
+ console.log(JSON.stringify({ type: "turn.completed" }));
3799
+ """
3800
+
3801
+
3802
+ def chat_wake_scratch(base: Path) -> tuple[Path, Path, dict[str, str], Path]:
3803
+ """`rtl` and a `cx` worktree sharing `lab` and `other`; `cx` declares chat-reply:lab.
3804
+
3805
+ Returns the two worktrees, an environment whose KEEL_HOME, launchctl,
3806
+ LaunchAgents directory, and Codex executable are scratch doubles, and the
3807
+ file the fake Codex appends one JSON line per turn to.
3808
+ """
3809
+ rtl = mailbox_repository(base / "rtl")
3810
+ cx = chat_worktree(rtl, base / "cx")
3811
+ write_text(cx / "keel" / "config.yaml", "authorize:\n - chat-reply:lab\n")
3812
+ subprocess.run(["git", "add", "keel/config.yaml"], cwd=cx, check=True, capture_output=True)
3813
+ subprocess.run(["git", "commit", "-q", "-m", "chat-reply"], cwd=cx, check=True, capture_output=True)
3814
+ calls = base / "codex-calls.jsonl"
3815
+ codex = base / "fake-codex"
3816
+ write_text(codex, FAKE_CODEX)
3817
+ codex.chmod(0o755)
3818
+ launchctl = base / "launchctl"
3819
+ write_text(launchctl, f'#!/bin/sh\necho "$@" >> "{base / "launchctl-calls"}"\nexit 0\n')
3820
+ launchctl.chmod(0o755)
3821
+ env = chat_environment(
3822
+ KEEL_HOME=str(base / "home"),
3823
+ KEEL_CHAT_CODEX=str(codex),
3824
+ FAKE_CODEX_LOG=str(calls),
3825
+ KEEL_CHAT_LAUNCHCTL=str(launchctl),
3826
+ KEEL_CHAT_LAUNCH_AGENTS_DIR=str(base / "agents"),
3827
+ )
3828
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
3829
+ run_keel(cx, "chat", "role", "--set", "cx", env=env)
3830
+ run_keel(rtl, "chat", "group", "create", "lab", "--member", "cx", env=env)
3831
+ run_keel(rtl, "chat", "group", "create", "other", "--member", "cx", env=env)
3832
+ return rtl, cx, env, calls
3833
+
3834
+
3835
+ def codex_calls(calls: Path) -> list[dict]:
3836
+ if not calls.exists():
3837
+ return []
3838
+ return [json.loads(line) for line in calls.read_text().splitlines() if line.strip()]
3839
+
3840
+
3841
+ def validate_chat_wake_run_scenario() -> int:
3842
+ """Issue #203: an addressed record starts one Codex turn, and nothing else does.
3843
+
3844
+ A registered waker starts a turn only for unread records that wake the
3845
+ role, in a group declaring chat-reply, newer than what an earlier turn
3846
+ was given; the first turn creates the thread and later ones resume it,
3847
+ with compaction and the git common directory as a writable root, under a
3848
+ per-hour limit and a per-role lock, and nothing lands in the worktree.
3849
+ """
3850
+ label = "chat-wake-run:"
3851
+ with tempfile.TemporaryDirectory(prefix="keel-chat-wake-run-") as raw:
3852
+ base = Path(raw)
3853
+ rtl, cx, env, calls = chat_wake_scratch(base)
3854
+
3855
+ def keel(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3856
+ return run_keel(cwd, "chat", *args, env=env)
3857
+
3858
+ def run_once() -> subprocess.CompletedProcess[str]:
3859
+ return keel(base, "wake", "run", "--once", "--worktree", str(cx))
3860
+
3861
+ added = keel(cx, "wake", "add")
3862
+ if added.returncode != 0:
3863
+ report(f"{label} keel chat wake add failed: {(added.stdout + added.stderr).strip()}")
3864
+ return 1
3865
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=cx, capture_output=True, text=True).stdout
3866
+
3867
+ def expect_turns(count: int, why: str) -> bool:
3868
+ result = run_once()
3869
+ if result.returncode != 0:
3870
+ report(f"{label} wake run --once failed {why}: {(result.stdout + result.stderr).strip()}")
3871
+ return False
3872
+ turns = codex_calls(calls)
3873
+ if len(turns) != count:
3874
+ report(f"{label} {len(turns)} Codex turns {why}, not {count}.")
3875
+ return False
3876
+ return True
3877
+
3878
+ if not expect_turns(0, "with nothing unread"):
3879
+ return 1
3880
+ keel(rtl, "post", "lab", "@all standup")
3881
+ if not expect_turns(0, "when the only unread record is @all"):
3882
+ return 1
3883
+ keel(rtl, "post", "other", "@cx ping-in-other")
3884
+ if not expect_turns(0, "for a mention in a group without chat-reply"):
3885
+ return 1
3886
+ keel(rtl, "post", "lab", "@cx ping-secret-123")
3887
+ if not expect_turns(1, "for one @cx record in lab"):
3888
+ return 1
3889
+ first = codex_calls(calls)[0]
3890
+ argv = first["argv"]
3891
+ common = str(mailbox_common_dir(rtl))
3892
+ if argv[:2] != ["exec", "--json"]:
3893
+ report(f"{label} the first turn is not a new `exec --json` turn: {argv!r}")
3894
+ return 1
3895
+ if "resume" in argv:
3896
+ report(f"{label} the first turn resumes a thread although none exists: {argv!r}")
3897
+ return 1
3898
+ joined = " ".join(argv)
3899
+ for needle in ("model_auto_compact_token_limit=100000", 'sandbox_mode="workspace-write"', "sandbox_workspace_write.writable_roots=", common):
3900
+ if needle not in joined:
3901
+ report(f"{label} the turn's arguments lack {needle!r}: {argv!r}")
3902
+ return 1
3903
+ if Path(first["cwd"]).resolve() != cx.resolve():
3904
+ report(f"{label} the turn ran in {first['cwd']}, not the worktree.")
3905
+ return 1
3906
+ if "ping-secret-123" in joined:
3907
+ report(f"{label} the record text reached the turn's arguments.")
3908
+ return 1
3909
+ if "ping-secret-123" in first["stdin"]:
3910
+ report(f"{label} the record text reached the turn's standard input.")
3911
+ return 1
3912
+ registrations = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [])
3913
+ if len(registrations) != 1:
3914
+ report(f"{label} status lists {len(registrations)} registrations, not one: {registrations!r}")
3915
+ return 1
3916
+ if registrations[0].get("thread") != "thread-fake-1":
3917
+ report(f"{label} status does not report the turn's thread: {registrations!r}")
3918
+ return 1
3919
+ if not expect_turns(1, "on a second run with no new record"):
3920
+ return 1
3921
+ keel(rtl, "post", "lab", "@cx second")
3922
+ if not expect_turns(2, "for a second @cx record"):
3923
+ return 1
3924
+ second = codex_calls(calls)[1]["argv"]
3925
+ if second[:3] != ["exec", "resume", "thread-fake-1"]:
3926
+ report(f"{label} the second turn does not resume the thread: {second!r}")
3927
+ return 1
3928
+
3929
+ limited = keel(cx, "wake", "add", "--max-per-hour", "2")
3930
+ if limited.returncode != 0:
3931
+ report(f"{label} wake add --max-per-hour failed: {(limited.stdout + limited.stderr).strip()}")
3932
+ return 1
3933
+ keel(rtl, "post", "lab", "@cx third")
3934
+ if not expect_turns(2, "past the hourly limit of 2"):
3935
+ return 1
3936
+ held = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [{}])[0]
3937
+ if held.get("held") is not True:
3938
+ report(f"{label} status does not report the registration held: {held!r}")
3939
+ return 1
3940
+
3941
+ keel(cx, "wake", "add", "--max-per-hour", "10")
3942
+ lock = base / "home" / "chat" / "wake" / f"{held.get('label')}.lock"
3943
+ write_text(lock, f"{os.getpid()}\n")
3944
+ if not expect_turns(2, "while another run holds the role's lock"):
3945
+ return 1
3946
+ lock.unlink()
3947
+ if not expect_turns(3, "after the lock is released"):
3948
+ return 1
3949
+
3950
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=cx, capture_output=True, text=True).stdout
3951
+ if after.strip():
3952
+ report(f"{label} the waker left files in the worktree: {after!r} (before: {before!r})")
3953
+ return 1
3954
+ if not (base / "home" / "chat" / "wake.json").exists():
3955
+ report(f"{label} the registration is not under KEEL_HOME.")
3956
+ return 1
3957
+
3958
+ if "chat-wake-run" not in {name for name, _ in SCENARIOS}:
3959
+ report(f"{label} scenario is not registered.")
3960
+ return 1
3961
+ report("chat-wake-run scenario passed.")
3962
+ return 0
3963
+
3964
+
3965
+ def validate_chat_wake_lifecycle_scenario() -> int:
3966
+ """Issue #203: the owner installs and removes a waker, and it watches the signal file.
3967
+
3968
+ `wake add` writes a LaunchAgent that watches the role's signal file and
3969
+ runs `wake run --once --worktree <path>` at load and on each change; it is
3970
+ refused without a role or for a host other than Codex, and warns when no
3971
+ chat-reply is declared; `wake remove` unloads and deletes it and keeps
3972
+ the log.
3973
+ """
3974
+ import plistlib # noqa: PLC0415 - only the lifecycle scenarios read a plist
3975
+
3976
+ label = "chat-wake-lifecycle:"
3977
+ with tempfile.TemporaryDirectory(prefix="keel-chat-wake-life-") as raw:
3978
+ base = Path(raw)
3979
+ rtl, cx, env, calls = chat_wake_scratch(base)
3980
+ norole = chat_worktree(rtl, base / "norole")
3981
+ agents = base / "agents"
3982
+ launchctl_calls = base / "launchctl-calls"
3983
+
3984
+ def keel(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3985
+ return run_keel(cwd, "chat", *args, env=env)
3986
+
3987
+ added = keel(cx, "wake", "add")
3988
+ if added.returncode != 0:
3989
+ report(f"{label} wake add failed: {(added.stdout + added.stderr).strip()}")
3990
+ return 1
3991
+ plists = list(agents.glob("*.plist"))
3992
+ if len(plists) != 1:
3993
+ report(f"{label} wake add wrote {len(plists)} plists, not one.")
3994
+ return 1
3995
+ plist = plistlib.loads(plists[0].read_bytes())
3996
+ if not str(plist.get("Label", "")).startswith("dev.keel.chat-wake.cx-"):
3997
+ report(f"{label} the LaunchAgent label does not name the role: {plist.get('Label')!r}")
3998
+ return 1
3999
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "cx"
4000
+ if [Path(p).resolve() for p in plist.get("WatchPaths", [])] != [signal.resolve()]:
4001
+ report(f"{label} the LaunchAgent does not watch the role's signal file: {plist.get('WatchPaths')!r}")
4002
+ return 1
4003
+ if not signal.exists():
4004
+ report(f"{label} wake add did not create the signal file it watches.")
4005
+ return 1
4006
+ program = plist.get("ProgramArguments", [])
4007
+ if program[-6:-1] != ["chat", "wake", "run", "--once", "--worktree"]:
4008
+ report(f"{label} the LaunchAgent does not run `chat wake run --once --worktree`: {program!r}")
4009
+ return 1
4010
+ if Path(program[-1]).resolve() != cx.resolve():
4011
+ report(f"{label} the LaunchAgent names {program[-1]}, not the worktree.")
4012
+ return 1
4013
+ if plist.get("RunAtLoad") is not True:
4014
+ report(f"{label} the LaunchAgent does not run at load: {plist!r}")
4015
+ return 1
4016
+ if "bootstrap" not in launchctl_calls.read_text():
4017
+ report(f"{label} wake add did not load the LaunchAgent.")
4018
+ return 1
4019
+
4020
+ unbound = keel(norole, "wake", "add")
4021
+ if unbound.returncode == 0:
4022
+ report(f"{label} wake add succeeded in a worktree with no role.")
4023
+ return 1
4024
+ if "role" not in unbound.stderr:
4025
+ report(f"{label} the no-role refusal does not say a role is needed: {unbound.stderr.strip()}")
4026
+ return 1
4027
+ other_host = keel(cx, "wake", "add", "--host", "claude")
4028
+ if other_host.returncode == 0:
4029
+ report(f"{label} wake add accepted --host claude.")
4030
+ return 1
4031
+ if "--host" not in other_host.stderr:
4032
+ report(f"{label} the host refusal does not name --host: {other_host.stderr.strip()}")
4033
+ return 1
4034
+
4035
+ listed = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [])
4036
+ mine = [entry for entry in listed if entry.get("role") == "cx"]
4037
+ if len(mine) != 1:
4038
+ report(f"{label} status does not list the cx registration once: {listed!r}")
4039
+ return 1
4040
+ if mine[0].get("installed") is not True:
4041
+ report(f"{label} status does not report the waker installed: {mine[0]!r}")
4042
+ return 1
4043
+
4044
+ undeclared = keel(rtl, "wake", "add")
4045
+ if undeclared.returncode != 0:
4046
+ report(f"{label} wake add without chat-reply failed: {(undeclared.stdout + undeclared.stderr).strip()}")
4047
+ return 1
4048
+ if "declares no chat-reply" not in undeclared.stdout:
4049
+ report(f"{label} wake add without chat-reply does not say nothing will wake: {undeclared.stdout.strip()}")
4050
+ return 1
4051
+
4052
+ keel(rtl, "post", "lab", "@cx ping")
4053
+ keel(base, "wake", "run", "--once", "--worktree", str(cx))
4054
+ log = Path(mine[0].get("log", ""))
4055
+ if not log.exists():
4056
+ report(f"{label} a turn wrote no wake log at {log}.")
4057
+ return 1
4058
+ removed = keel(cx, "wake", "remove")
4059
+ if removed.returncode != 0:
4060
+ report(f"{label} wake remove failed: {(removed.stdout + removed.stderr).strip()}")
4061
+ return 1
4062
+ if "bootout" not in launchctl_calls.read_text():
4063
+ report(f"{label} wake remove did not unload the LaunchAgent.")
4064
+ return 1
4065
+ if plists[0].exists():
4066
+ report(f"{label} wake remove left the plist.")
4067
+ return 1
4068
+ remaining = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [])
4069
+ if any(entry.get("role") == "cx" for entry in remaining):
4070
+ report(f"{label} wake remove left the registration: {remaining!r}")
4071
+ return 1
4072
+ if not log.exists():
4073
+ report(f"{label} wake remove deleted the log.")
4074
+ return 1
4075
+
4076
+ if "chat-wake-lifecycle" not in {name for name, _ in SCENARIOS}:
4077
+ report(f"{label} scenario is not registered.")
4078
+ return 1
4079
+ report("chat-wake-lifecycle scenario passed.")
4080
+ return 0
4081
+
4082
+
4083
+ def validate_chat_notice_check_scenario() -> int:
4084
+ """Issue #194: a scheduler asks, without a model turn, whether to start one.
4085
+
4086
+ `keel chat notice --check` prints nothing and moves no cursor. It exits
4087
+ 0 exactly when something that would wake the role is unread — a mention,
4088
+ an assigned todo, a direct message — and 1 otherwise, including for a
4089
+ broadcast alone, outside a repository, and with no role bound.
4090
+ """
4091
+ label = "chat-notice-check:"
4092
+ with tempfile.TemporaryDirectory(prefix="keel-chat-check-") as raw:
4093
+ base = Path(raw)
4094
+ rtl, verify, env = chat_scratch_group(base)
4095
+ unbound = mailbox_repository(base / "unbound")
4096
+ plain = base / "plain"
4097
+ plain.mkdir()
4098
+
4099
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4100
+ return run_keel(cwd, "chat", *args, env=env)
4101
+
4102
+ def check(cwd: Path, expected: int, why: str) -> bool:
4103
+ result = chat(cwd, "notice", "--check")
4104
+ if result.stdout or result.stderr:
4105
+ report(f"{label} --check wrote output {why}: {(result.stdout + result.stderr).strip()!r}")
4106
+ return False
4107
+ if result.returncode != expected:
4108
+ report(f"{label} --check exited {result.returncode} {why}, not {expected}.")
4109
+ return False
4110
+ return True
4111
+
4112
+ if not check(verify, 1, "with nothing unread"):
4113
+ return 1
4114
+ chat(rtl, "post", "soc", "@all standup in five")
4115
+ if not check(verify, 1, "when the only unread record is @all"):
4116
+ return 1
4117
+ chat(rtl, "post", "soc", "@verify please rerun")
4118
+ if not check(verify, 0, "with an unread @verify"):
4119
+ return 1
4120
+ before = chat_json(chat(verify, "unread", "--json")).get("unread", [])
4121
+ store = mailbox_common_dir(rtl) / "keel-chat"
4122
+
4123
+ def snapshot() -> dict[str, bytes]:
4124
+ return {str(p.relative_to(store)): p.read_bytes() for p in store.rglob("*") if p.is_file()}
4125
+
4126
+ files_before = snapshot()
4127
+ if not check(verify, 0, "a second time"):
4128
+ return 1
4129
+ if snapshot() != files_before:
4130
+ report(f"{label} --check wrote to the chat store.")
4131
+ return 1
4132
+ after = chat_json(chat(verify, "unread", "--json")).get("unread", [])
4133
+ if [r.get("id") for r in after] != [r.get("id") for r in before]:
4134
+ report(f"{label} --check changed what verify has unread.")
4135
+ return 1
4136
+ chat(verify, "read")
4137
+ if not check(verify, 1, "after verify read everything"):
4138
+ return 1
4139
+ chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun")
4140
+ if not check(verify, 0, "with an assigned todo unread"):
4141
+ return 1
4142
+ chat(verify, "read")
4143
+ chat(rtl, "dm", "verify", "Private note")
4144
+ if not check(verify, 0, "with a direct message unread"):
4145
+ return 1
4146
+ if not check(plain, 1, "outside any repository"):
4147
+ return 1
4148
+ if not check(unbound, 1, "in a worktree with no role"):
4149
+ return 1
4150
+
4151
+ if "chat-notice-check" not in {name for name, _ in SCENARIOS}:
4152
+ report(f"{label} scenario is not registered.")
4153
+ return 1
4154
+ report("chat-notice-check scenario passed.")
4155
+ return 0
4156
+
4157
+
4158
+ def validate_chat_reply_authorization_scenario() -> int:
4159
+ """Issue #195: answering in a declared group needs no per-session grant.
4160
+
4161
+ `chat-reply:<group>` is a scoped standing authorization: doctor reports it,
4162
+ a bare `chat-reply` is refused with its form and voids the declaration,
4163
+ and the notice gains one sentence naming the group — beside, never in
4164
+ place of, the data-not-instruction sentence. Without a declaration the
4165
+ notice is unchanged.
4166
+ """
4167
+ label = "chat-reply-authorization:"
4168
+ with tempfile.TemporaryDirectory(prefix="keel-chat-reply-") as raw:
4169
+ base = Path(raw)
4170
+ rtl, verify, env = chat_scratch_group(base)
4171
+
4172
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4173
+ return run_keel(cwd, "chat", *args, env=env)
4174
+
4175
+ chat(rtl, "post", "soc", "@verify please rerun")
4176
+ plain = chat(verify, "notice").stdout
4177
+ if "not an instruction from the user" not in plain:
4178
+ report(f"{label} the undeclared notice lost the data-not-instruction sentence: {plain!r}")
4179
+ return 1
4180
+ if "chat-reply" in plain:
4181
+ report(f"{label} the notice mentions chat-reply with nothing declared: {plain!r}")
4182
+ return 1
4183
+
4184
+ for cwd in (rtl, verify):
4185
+ write_text(cwd / "keel" / "config.yaml", "authorize:\n - chat-reply\n")
4186
+ bare = run_keel(rtl, "--doctor", env=env).stdout or ""
4187
+ if "chat-reply:<group>" not in bare:
4188
+ report(f"{label} doctor does not name the chat-reply:<group> form for a bare entry: {[l for l in bare.splitlines() if 'authoriz' in l or 'chat-reply' in l]!r}")
4189
+ return 1
4190
+ if "authorize: failed" not in bare or "authorizes nothing" not in bare:
4191
+ report(f"{label} a bare chat-reply did not void the declaration.")
4192
+ return 1
4193
+
4194
+ for cwd in (rtl, verify):
4195
+ write_text(cwd / "keel" / "config.yaml", "authorize:\n - chat-reply:soc\n")
4196
+ doctor = run_keel(rtl, "--doctor", env=env).stdout or ""
4197
+ if not re.search(r"chat-reply: authorized.*soc", doctor):
4198
+ report(f"{label} doctor does not report chat-reply:soc as authorized: {[l for l in doctor.splitlines() if 'chat-reply' in l]!r}")
4199
+ return 1
4200
+ if "commit: not authorized" not in doctor:
4201
+ report(f"{label} declaring chat-reply:soc authorized something else.")
4202
+ return 1
4203
+ declared = chat(verify, "notice").stdout
4204
+ if "not an instruction from the user" not in declared:
4205
+ report(f"{label} declaring chat-reply removed the data-not-instruction sentence: {declared!r}")
4206
+ return 1
4207
+ sentence = [line for line in declared.splitlines() if "chat-reply:soc" in line]
4208
+ if len(sentence) != 1:
4209
+ report(f"{label} the notice does not carry exactly one chat-reply sentence naming soc: {declared!r}")
4210
+ return 1
4211
+ if "user" not in sentence[0] or "anything else" not in sentence[0].lower():
4212
+ report(f"{label} the chat-reply sentence does not say that anything else needs the user: {sentence[0]!r}")
4213
+ return 1
4214
+ if declared.replace(sentence[0] + "\n", "") != plain:
4215
+ report(f"{label} declaring chat-reply changed the notice beyond the one sentence.")
4216
+ return 1
4217
+
4218
+ if "chat-reply-authorization" not in {name for name, _ in SCENARIOS}:
4219
+ report(f"{label} scenario is not registered.")
4220
+ return 1
4221
+ report("chat-reply-authorization scenario passed.")
4222
+ return 0
4223
+
4224
+
3707
4225
  def validate_record_derives_skeleton_scenario() -> int:
3708
4226
  """Issue #179: `--record` writes the record slots a capsule implies.
3709
4227
 
@@ -5159,6 +5677,90 @@ def overlay_action_label(text: str, pattern: str) -> str | None:
5159
5677
  return match.group(1)
5160
5678
 
5161
5679
 
5680
+ def validate_update_restores_overlays_scenario() -> int:
5681
+ label = "update-restores-overlays:"
5682
+ with tempfile.TemporaryDirectory(prefix="keel-update-overlays-") as raw:
5683
+ tmp = Path(raw)
5684
+ repo = tmp / "mixed"
5685
+ repo.mkdir()
5686
+ env = os.environ.copy()
5687
+ env["CODEX_HOME"] = str(tmp / "codex-home")
5688
+ for target in ("claude", "codex"):
5689
+ result = run_keel(repo, "--init", "--target", target, env=env)
5690
+ if result.returncode:
5691
+ report(f"{label} init {target} failed: {result.stderr or result.stdout}")
5692
+ return 1
5693
+ # Diagnose a missing foreign target before the upstream rewrite.
5694
+ codex_paths = [p for paths in openspec_overlay_files(
5695
+ repo, "codex", tmp / "codex-home").values() for p in paths]
5696
+ for p in codex_paths:
5697
+ if p.exists():
5698
+ p.write_text(strip_openspec_surface_overlay(p.read_text()), encoding="utf-8")
5699
+ doctor = run_keel(repo, "--doctor", "--target", "claude", env=env)
5700
+ if not re.search(r"Codex.*overlay: (missing|partial)", doctor.stdout):
5701
+ report(f"{label} doctor hid missing Codex overlays while selecting Claude")
5702
+ return 1
5703
+ for iteration in range(2):
5704
+ result = run_keel(repo, "openspec", "update", env=env)
5705
+ if result.returncode:
5706
+ report(f"{label} update failed: {result.stderr or result.stdout}")
5707
+ return 1
5708
+ for target in ("claude", "codex"):
5709
+ error = assert_target_overlays(repo, target, tmp / "codex-home")
5710
+ if error:
5711
+ report(f"{label} update {iteration}: {error}")
5712
+ return 1
5713
+ for action, skill in OVERLAY_ACTION_SKILLS.items():
5714
+ surface = repo / (".claude/skills" if target == "claude" else ".agents/skills") / skill / "SKILL.md"
5715
+ content = surface.read_text()
5716
+ if content.count(OPENSPEC_SURFACE_OVERLAY_START) != 1 or content.count(OPENSPEC_SURFACE_OVERLAY_END) != 1:
5717
+ report(f"{label} managed action has missing or duplicate overlays: {surface}")
5718
+ return 1
5719
+ if not strip_openspec_surface_overlay(content).strip():
5720
+ report(f"{label} upstream body removed: {surface}")
5721
+ return 1
5722
+ legacy = tmp / "legacy"
5723
+ legacy.mkdir()
5724
+ result = run_keel(legacy, "--init", "--target", "claude", env=env)
5725
+ if result.returncode:
5726
+ report(f"{label} legacy fixture init failed")
5727
+ return 1
5728
+ for skill in OVERLAY_ACTION_SKILLS.values():
5729
+ write_text(legacy / ".codex/skills" / skill / "SKILL.md", "# Legacy OpenSpec workflow\n")
5730
+ doctor = run_keel(legacy, "--doctor", "--target", "claude", env=env)
5731
+ if not re.search(r"Codex.*overlay: (missing|partial)", doctor.stdout):
5732
+ report(f"{label} legacy Codex coverage was hidden")
5733
+ return 1
5734
+ # A single-target repository must stay isolated, even with global prompts.
5735
+ single = tmp / "single"
5736
+ single.mkdir()
5737
+ result = run_keel(single, "--init", "--target", "claude", env=env)
5738
+ if result.returncode:
5739
+ report(f"{label} single init failed")
5740
+ return 1
5741
+ result = run_keel(single, "openspec", "update", env=env)
5742
+ if result.returncode or (single / ".agents/skills").exists() or (single / ".codex/skills").exists():
5743
+ report(f"{label} single-target update failed or created Codex surfaces")
5744
+ return 1
5745
+ doctor = run_keel(single, "--doctor", "--target", "claude", env=env)
5746
+ if re.search(r"Codex.*overlay:", doctor.stdout):
5747
+ report(f"{label} global prompts enrolled an unrelated repository")
5748
+ return 1
5749
+ # Invalid options fail in real upstream OpenSpec; no recovery may write.
5750
+ surface = repo / ".agents/skills/openspec-apply-change/SKILL.md"
5751
+ surface.write_text(strip_openspec_surface_overlay(surface.read_text()), encoding="utf-8")
5752
+ files = {p: p.read_bytes() for p in repo.rglob("*.md")}
5753
+ upstream = subprocess.run(
5754
+ ["node", str(ROOT / "node_modules/.bin/openspec"), "update", "--keel-invalid-option"],
5755
+ cwd=repo, env=env, capture_output=True, text=True, check=False)
5756
+ failed = run_keel(repo, "openspec", "update", "--keel-invalid-option", env=env)
5757
+ if not failed.returncode or failed.returncode != upstream.returncode or any(p.read_bytes() != b for p, b in files.items()):
5758
+ report(f"{label} failed update was masked or changed surfaces")
5759
+ return 1
5760
+ report("update-restores-overlays scenario passed.")
5761
+ return 0
5762
+
5763
+
5162
5764
  def validate_openspec_surface_overlay_scenario() -> int:
5163
5765
  with tempfile.TemporaryDirectory(prefix="keel-overlay-") as raw_tmp:
5164
5766
  tmp = Path(raw_tmp)
@@ -19821,9 +20423,9 @@ def validate_native_runtime_projection_scenario() -> int:
19821
20423
  "--json",
19822
20424
  env=env,
19823
20425
  )
19824
- if json.loads(unauthorized_subagent.stdout).get("status") != "blocked":
20426
+ if json.loads(unauthorized_subagent.stdout).get("status") != "ready":
19825
20427
  report(
19826
- f"native-runtime-projection {target} activated subagent implicitly."
20428
+ f"native-runtime-projection {target} requires extra helper activation."
19827
20429
  )
19828
20430
  return 1
19829
20431
 
@@ -20585,6 +21187,7 @@ STANDING_AUTHORIZATION_ACTIONS = (
20585
21187
  "archive",
20586
21188
  "continuation",
20587
21189
  "protocol-refresh",
21190
+ "chat-reply",
20588
21191
  )
20589
21192
 
20590
21193
 
@@ -21708,7 +22311,7 @@ def validate_delegation_resident_text_scenario() -> int:
21708
22311
  agents = ROOT / "AGENTS.md"
21709
22312
  text = flat(agents)
21710
22313
  for needle in (
21711
- "as delegates implementing the selected task inside",
22314
+ "implementation delegates use the selected task write authority inside",
21712
22315
  "a guard manifest is active",
21713
22316
  "re-runs each",
21714
22317
  "check itself before recording Evidence",
@@ -21729,7 +22332,7 @@ def validate_delegation_resident_text_scenario() -> int:
21729
22332
  # constant; a raise with no reason beside it is the drift this guards.
21730
22333
  bootstrap = ROOT / "assets/bootstrap/AGENTS.md"
21731
22334
  boot = flat(bootstrap)
21732
- if re.sub(r"\s+", " ", "One current agent owns writes") not in boot:
22335
+ if re.sub(r"\s+", " ", "One agent owns decisions") not in boot:
21733
22336
  report("delegation-resident-text: the bootstrap lost its single-writer default.")
21734
22337
  return 1
21735
22338
  block = bootstrap.read_text(encoding="utf-8")
@@ -21783,8 +22386,8 @@ def validate_delegation_resident_text_scenario() -> int:
21783
22386
  if re.sub(r"\s+", " ", "helpers stay read-only/evidence-only") not in body:
21784
22387
  report(f"delegation-resident-text: {path.relative_to(ROOT)} dropped the helper default.")
21785
22388
  return 1
21786
- if re.sub(r"\s+", " ", "delegation defaults to none") not in body:
21787
- report(f"delegation-resident-text: {path.relative_to(ROOT)} does not state the delegation default.")
22389
+ if re.sub(r"\s+", " ", "matching active guard") not in body:
22390
+ report(f"delegation-resident-text: {path.relative_to(ROOT)} does not state the implementation guard boundary.")
21788
22391
  return 1
21789
22392
  if source.read_bytes() != installed.read_bytes():
21790
22393
  report("delegation-resident-text: the template source and its installed copy diverged.")
@@ -21818,7 +22421,7 @@ def validate_delegation_overlay_scenario() -> int:
21818
22421
  # its results are worth. Asserted on every generated copy, because the
21819
22422
  # overlay is what a subagent on that surface actually reads.
21820
22423
  needles = (
21821
- "where `delegation:` is declared",
22424
+ "using existing task write authority",
21822
22425
  "a guard manifest is active",
21823
22426
  "only inside `Touch`",
21824
22427
  "re-runs each `M<n>` check itself before recording Evidence",
@@ -22264,8 +22867,8 @@ def validate_delegation_sole_authority_scenario() -> int:
22264
22867
  # M1 — the stop list refuses an undeclared delegation and no longer
22265
22868
  # refuses a declared one outright.
22266
22869
  skill_text = flat(canonical)
22267
- if re.sub(r"\s+", " ", "undeclared delegation") not in skill_text:
22268
- report("delegation-sole-authority: the stop list does not refuse an undeclared delegation.")
22870
+ if re.sub(r"\s+", " ", "matching active guard") not in skill_text:
22871
+ report("delegation-sole-authority: the stop list omits guarded task authority.")
22269
22872
  return 1
22270
22873
  if re.sub(r"\s+", " ", "any request to delegate implementation to another agent") in skill_text:
22271
22874
  report("delegation-sole-authority: the stop list still refuses every delegation outright.")
@@ -22281,6 +22884,9 @@ def validate_delegation_sole_authority_scenario() -> int:
22281
22884
  if re.sub(r"\s+", " ", "read-only subagent helpers only") in text:
22282
22885
  report(f"delegation-sole-authority: {path.name} still says read-only helpers only.")
22283
22886
  return 1
22887
+ if "matching active guard" not in text or "host policy" not in text.lower():
22888
+ report(f"delegation-sole-authority: {path.name} omits guard or host boundary.")
22889
+ return 1
22284
22890
 
22285
22891
  # M2 — the canonical source and its distribution copy stay byte-identical.
22286
22892
  if canonical.read_bytes() != packaged.read_bytes():
@@ -22298,6 +22904,144 @@ def validate_delegation_sole_authority_scenario() -> int:
22298
22904
  return 0
22299
22905
 
22300
22906
 
22907
+ def validate_model_chosen_subagents_scenario() -> int:
22908
+ label = "model-chosen-subagents:"
22909
+ with tempfile.TemporaryDirectory(prefix="keel-model-subagents-") as raw:
22910
+ repo = Path(raw)
22911
+ write_gate_fixture(repo, standing_authorization_task())
22912
+ def project(*extra: str) -> dict:
22913
+ result = run_keel(repo, "project", "--target", "codex",
22914
+ "--event", "subagent-start", "--change", "demo", "--task", "1.1", "--json", *extra)
22915
+ return json.loads(result.stdout)
22916
+ helper = project()
22917
+ if helper.get("status") != "ready":
22918
+ report(f"{label} ordinary helper still requires activation: {helper.get('reasons')}")
22919
+ return 1
22920
+ if helper["projection"].get("subagentMode") != "helper" or helper["projection"].get("delegation"):
22921
+ report(f"{label} helper posture grants delegation")
22922
+ return 1
22923
+ write_authorize_config(repo, "delegation:\n tier: turbo\n")
22924
+ if project().get("status") != "ready":
22925
+ report(f"{label} helper depends on implementation tier metadata")
22926
+ return 1
22927
+ write_authorize_config(repo, "fast_check: echo ok\n")
22928
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22929
+ report(f"{label} unguarded implementation allowed")
22930
+ return 1
22931
+ started = run_keel(repo, "gate", "task-start", "--change", "demo", "--task", "1.1", "--record", "--json")
22932
+ if json.loads(started.stdout).get("status") != "pass":
22933
+ report(f"{label} valid task did not start: {started.stdout}")
22934
+ return 1
22935
+ delegate = project("--subagent-mode", "implementation")
22936
+ if delegate.get("status") != "ready":
22937
+ report(f"{label} guarded implementation requires tier: {delegate.get('reasons')}")
22938
+ return 1
22939
+ brief = delegate["projection"]
22940
+ if brief.get("delegation", {}).get("writeBoundary") != ["src/feature.js"] or brief["delegation"].get("tier") is not None:
22941
+ report(f"{label} delegate boundary or absent tier incorrect")
22942
+ return 1
22943
+ if not all(any(term in p for p in brief["prohibitions"]) for term in ["Acceptance", "commit", "mark tasks complete", "task execution records", "Evidence", "Review"]):
22944
+ report(f"{label} ownership prohibitions lost")
22945
+ return 1
22946
+ manifest_path = repo / "keel/guard.json"
22947
+ saved = manifest_path.read_bytes()
22948
+ manifest_path.write_text("{}")
22949
+ if project().get("status") != "ready":
22950
+ report(f"{label} malformed implementation guard blocked read-only help")
22951
+ return 1
22952
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22953
+ report(f"{label} malformed guard allowed implementation")
22954
+ return 1
22955
+ manifest_path.write_bytes(saved)
22956
+ manifest = json.loads(saved)
22957
+ manifest["fingerprint"]["value"] = "0" * 64
22958
+ manifest_path.write_text(json.dumps(manifest))
22959
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22960
+ report(f"{label} drifted guard allowed implementation")
22961
+ return 1
22962
+ manifest_path.write_bytes(saved)
22963
+ manifest = json.loads(saved)
22964
+ manifest["touch"].append("src/outside.js")
22965
+ manifest_path.write_text(json.dumps(manifest))
22966
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22967
+ report(f"{label} widened manifest Touch allowed implementation")
22968
+ return 1
22969
+ manifest = json.loads(saved)
22970
+ manifest["task"] = "9.9"
22971
+ manifest_path.write_text(json.dumps(manifest))
22972
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22973
+ report(f"{label} different task guard allowed implementation")
22974
+ return 1
22975
+ manifest_path.write_bytes(saved)
22976
+ shutil.copytree(repo / "openspec/changes/demo", repo / "openspec/changes/other")
22977
+ other_start = run_keel(repo, "gate", "task-start", "--change", "other", "--task", "1.1", "--record", "--json")
22978
+ if json.loads(other_start.stdout).get("status") != "pass":
22979
+ report(f"{label} other task guard fixture did not start")
22980
+ return 1
22981
+ mismatch = project("--subagent-mode", "implementation")
22982
+ if mismatch.get("status") == "ready":
22983
+ report(f"{label} active guard for another owner allowed implementation")
22984
+ return 1
22985
+ if "matching" not in " ".join(mismatch.get("reasons", [])):
22986
+ report(f"{label} other-owner refusal did not name guard mismatch")
22987
+ return 1
22988
+ manifest_path.write_bytes(saved)
22989
+ task_path = repo / "openspec/changes/demo/tasks.md"
22990
+ task_before = task_path.read_text()
22991
+ task_path.write_text(task_before.replace("src/feature.js", "src/other.js"))
22992
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22993
+ report(f"{label} authority drift allowed implementation")
22994
+ return 1
22995
+ task_path.write_text(task_before)
22996
+ returned = run_keel(repo, "project", "--event", "subagent-stop", "--subagent-mode", "implementation", "--native-complete", "--change", "demo", "--task", "1.1", "--json")
22997
+ returned_payload = json.loads(returned.stdout)
22998
+ if task_path.read_text() != task_before:
22999
+ report(f"{label} delegate completion modified task authority or records")
23000
+ return 1
23001
+ if returned_payload.get("projection", {}).get("returnAuthority") != "report-and-evidence-only":
23002
+ report(f"{label} delegate return did not remain evidence-only")
23003
+ return 1
23004
+ goal = run_keel(repo, "project", "--event", "goal", "--change", "demo", "--task", "1.1", "--json")
23005
+ if json.loads(goal.stdout).get("status") != "blocked":
23006
+ report(f"{label} goal activation became implicit")
23007
+ return 1
23008
+ configured = repo / "configured"
23009
+ configured.mkdir()
23010
+ write_gate_fixture(configured, standing_authorization_task())
23011
+ write_authorize_config(configured, "delegation:\n tier: deep\n")
23012
+ explicit = run_keel(configured, "project", "--event", "subagent-start", "--authorize", "subagent", "--subagent-mode", "helper", "--change", "demo", "--task", "1.1", "--json")
23013
+ payload = json.loads(explicit.stdout)
23014
+ if payload.get("status") != "ready" or payload["projection"].get("delegation"):
23015
+ report(f"{label} explicit helper became writer due to tier metadata")
23016
+ return 1
23017
+ for name,task,config in [
23018
+ ("bad-task-tier", standing_authorization_task().replace(" - Covers:", " - Delegation: turbo\n - Covers:"), ""),
23019
+ ("bad-config-tier", standing_authorization_task(), "delegation:\n tier: turbo\n"),
23020
+ ("plan-first", standing_authorization_task().replace(" - Covers:", " - Mode: plan-first\n - Covers:"), ""),
23021
+ ("diagnose-only", standing_authorization_task().replace(" - Covers:", " - Mode: diagnose-only\n - Covers:").replace(" - src/feature.js", " - none"), ""),
23022
+ ("repo-action", standing_authorization_task().replace(" - Covers:", " - Mode: repo-action\n - Covers:").replace(" - src/feature.js", " - none"), ""),
23023
+ ]:
23024
+ other = repo / name
23025
+ other.mkdir()
23026
+ write_gate_fixture(other, task)
23027
+ write_authorize_config(other, config)
23028
+ result = run_keel(other, "project", "--event", "subagent-start", "--change", "demo", "--task", "1.1", "--json")
23029
+ if json.loads(result.stdout).get("status") != "ready":
23030
+ report(f"{label} read-only helper refused for {name}: {result.stdout}")
23031
+ return 1
23032
+ result = run_keel(other, "project", "--event", "subagent-start", "--subagent-mode", "implementation", "--change", "demo", "--task", "1.1", "--json")
23033
+ rejected = json.loads(result.stdout)
23034
+ if rejected.get("status") == "ready":
23035
+ report(f"{label} implementation allowed for {name}")
23036
+ return 1
23037
+ expected = "turbo" if "tier" in name else "implementation task"
23038
+ if expected not in " ".join(rejected.get("reasons", [])):
23039
+ report(f"{label} {name} refusal named wrong cause: {rejected.get('reasons')}")
23040
+ return 1
23041
+ report("model-chosen-subagents scenario passed.")
23042
+ return 0
23043
+
23044
+
22301
23045
  def validate_delegation_projection_scenario() -> int:
22302
23046
  """The projection Keel already publishes carries the delegation, and
22303
23047
  refuses where the preconditions for one do not hold.
@@ -22450,8 +23194,8 @@ def validate_delegation_projection_scenario() -> int:
22450
23194
  except json.JSONDecodeError:
22451
23195
  report(f"delegation-projection: unauthorized start returned no JSON: {unauthorized.stdout!r}")
22452
23196
  return 1
22453
- if refused.get("status") == "ready":
22454
- report("delegation-projection: subagent-start projected without authorization.")
23197
+ if refused.get("status") != "ready":
23198
+ report("delegation-projection: ordinary helper required extra authorization.")
22455
23199
  return 1
22456
23200
 
22457
23201
  report("delegation-projection scenario passed.")
@@ -23494,8 +24238,8 @@ def validate_continuation_docs_scenario() -> int:
23494
24238
  # to spell all of it: a reader copies from the list they are shown.
23495
24239
  for needle in (
23496
24240
  "accepted names: commit, push, release, archive, continuation, "
23497
- "issue:<owner>/<repo>, protocol-refresh",
23498
- "The seven names above are the whole vocabulary.",
24241
+ "issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>",
24242
+ "The eight names above are the whole vocabulary.",
23499
24243
  "`protocol-refresh`, the seventh name",
23500
24244
  ):
23501
24245
  if needle not in readme:
@@ -23503,7 +24247,7 @@ def validate_continuation_docs_scenario() -> int:
23503
24247
  return 1
23504
24248
 
23505
24249
  config_text = (ROOT / "keel/config.yaml").read_text(encoding="utf-8")
23506
- if "commit, push, release, archive,\n# continuation, issue:<owner>/<repo>, protocol-refresh" not in config_text:
24250
+ if "commit, push, release, archive,\n# continuation, issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>" not in config_text:
23507
24251
  report(
23508
24252
  f"{label}: keel/config.yaml's comment lacks: protocol-refresh in the "
23509
24253
  "seven-name vocabulary."
@@ -33717,6 +34461,26 @@ SCENARIOS: tuple = (
33717
34461
  "chat-archive",
33718
34462
  validate_chat_archive_scenario,
33719
34463
  ),
34464
+ (
34465
+ "chat-reply-authorization",
34466
+ validate_chat_reply_authorization_scenario,
34467
+ ),
34468
+ (
34469
+ "chat-notice-check",
34470
+ validate_chat_notice_check_scenario,
34471
+ ),
34472
+ (
34473
+ "chat-reply-marks-read",
34474
+ validate_chat_reply_marks_read_scenario,
34475
+ ),
34476
+ (
34477
+ "chat-wake-run",
34478
+ validate_chat_wake_run_scenario,
34479
+ ),
34480
+ (
34481
+ "chat-wake-lifecycle",
34482
+ validate_chat_wake_lifecycle_scenario,
34483
+ ),
33720
34484
  (
33721
34485
  "record-derives-skeleton",
33722
34486
  validate_record_derives_skeleton_scenario,
@@ -33736,6 +34500,8 @@ SCENARIOS: tuple = (
33736
34500
  ("version-alignment", validate_version_alignment_scenario),
33737
34501
  ("sync-surface-overlay", validate_sync_surface_overlay_scenario),
33738
34502
  ("openspec-surface-overlay", validate_openspec_surface_overlay_scenario),
34503
+ ("update-restores-overlays", validate_update_restores_overlays_scenario),
34504
+ ("model-chosen-subagents", validate_model_chosen_subagents_scenario),
33739
34505
  ("uninstall", validate_uninstall_scenario),
33740
34506
  (
33741
34507
  "uninstall-removes-the-overlay",