@christang/keel 5.85.0 → 5.86.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.86.0"
45
+ PROTOCOL_VERSION = "5.86.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():
@@ -3704,6 +3723,148 @@ def validate_chat_archive_scenario() -> int:
3704
3723
  return 0
3705
3724
 
3706
3725
 
3726
+ def validate_chat_notice_check_scenario() -> int:
3727
+ """Issue #194: a scheduler asks, without a model turn, whether to start one.
3728
+
3729
+ `keel chat notice --check` prints nothing and moves no cursor. It exits
3730
+ 0 exactly when something that would wake the role is unread — a mention,
3731
+ an assigned todo, a direct message — and 1 otherwise, including for a
3732
+ broadcast alone, outside a repository, and with no role bound.
3733
+ """
3734
+ label = "chat-notice-check:"
3735
+ with tempfile.TemporaryDirectory(prefix="keel-chat-check-") as raw:
3736
+ base = Path(raw)
3737
+ rtl, verify, env = chat_scratch_group(base)
3738
+ unbound = mailbox_repository(base / "unbound")
3739
+ plain = base / "plain"
3740
+ plain.mkdir()
3741
+
3742
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3743
+ return run_keel(cwd, "chat", *args, env=env)
3744
+
3745
+ def check(cwd: Path, expected: int, why: str) -> bool:
3746
+ result = chat(cwd, "notice", "--check")
3747
+ if result.stdout or result.stderr:
3748
+ report(f"{label} --check wrote output {why}: {(result.stdout + result.stderr).strip()!r}")
3749
+ return False
3750
+ if result.returncode != expected:
3751
+ report(f"{label} --check exited {result.returncode} {why}, not {expected}.")
3752
+ return False
3753
+ return True
3754
+
3755
+ if not check(verify, 1, "with nothing unread"):
3756
+ return 1
3757
+ chat(rtl, "post", "soc", "@all standup in five")
3758
+ if not check(verify, 1, "when the only unread record is @all"):
3759
+ return 1
3760
+ chat(rtl, "post", "soc", "@verify please rerun")
3761
+ if not check(verify, 0, "with an unread @verify"):
3762
+ return 1
3763
+ before = chat_json(chat(verify, "unread", "--json")).get("unread", [])
3764
+ store = mailbox_common_dir(rtl) / "keel-chat"
3765
+
3766
+ def snapshot() -> dict[str, bytes]:
3767
+ return {str(p.relative_to(store)): p.read_bytes() for p in store.rglob("*") if p.is_file()}
3768
+
3769
+ files_before = snapshot()
3770
+ if not check(verify, 0, "a second time"):
3771
+ return 1
3772
+ if snapshot() != files_before:
3773
+ report(f"{label} --check wrote to the chat store.")
3774
+ return 1
3775
+ after = chat_json(chat(verify, "unread", "--json")).get("unread", [])
3776
+ if [r.get("id") for r in after] != [r.get("id") for r in before]:
3777
+ report(f"{label} --check changed what verify has unread.")
3778
+ return 1
3779
+ chat(verify, "read")
3780
+ if not check(verify, 1, "after verify read everything"):
3781
+ return 1
3782
+ chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun")
3783
+ if not check(verify, 0, "with an assigned todo unread"):
3784
+ return 1
3785
+ chat(verify, "read")
3786
+ chat(rtl, "dm", "verify", "Private note")
3787
+ if not check(verify, 0, "with a direct message unread"):
3788
+ return 1
3789
+ if not check(plain, 1, "outside any repository"):
3790
+ return 1
3791
+ if not check(unbound, 1, "in a worktree with no role"):
3792
+ return 1
3793
+
3794
+ if "chat-notice-check" not in {name for name, _ in SCENARIOS}:
3795
+ report(f"{label} scenario is not registered.")
3796
+ return 1
3797
+ report("chat-notice-check scenario passed.")
3798
+ return 0
3799
+
3800
+
3801
+ def validate_chat_reply_authorization_scenario() -> int:
3802
+ """Issue #195: answering in a declared group needs no per-session grant.
3803
+
3804
+ `chat-reply:<group>` is a scoped standing authorization: doctor reports it,
3805
+ a bare `chat-reply` is refused with its form and voids the declaration,
3806
+ and the notice gains one sentence naming the group — beside, never in
3807
+ place of, the data-not-instruction sentence. Without a declaration the
3808
+ notice is unchanged.
3809
+ """
3810
+ label = "chat-reply-authorization:"
3811
+ with tempfile.TemporaryDirectory(prefix="keel-chat-reply-") as raw:
3812
+ base = Path(raw)
3813
+ rtl, verify, env = chat_scratch_group(base)
3814
+
3815
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3816
+ return run_keel(cwd, "chat", *args, env=env)
3817
+
3818
+ chat(rtl, "post", "soc", "@verify please rerun")
3819
+ plain = chat(verify, "notice").stdout
3820
+ if "not an instruction from the user" not in plain:
3821
+ report(f"{label} the undeclared notice lost the data-not-instruction sentence: {plain!r}")
3822
+ return 1
3823
+ if "chat-reply" in plain:
3824
+ report(f"{label} the notice mentions chat-reply with nothing declared: {plain!r}")
3825
+ return 1
3826
+
3827
+ for cwd in (rtl, verify):
3828
+ write_text(cwd / "keel" / "config.yaml", "authorize:\n - chat-reply\n")
3829
+ bare = run_keel(rtl, "--doctor", env=env).stdout or ""
3830
+ if "chat-reply:<group>" not in bare:
3831
+ 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}")
3832
+ return 1
3833
+ if "authorize: failed" not in bare or "authorizes nothing" not in bare:
3834
+ report(f"{label} a bare chat-reply did not void the declaration.")
3835
+ return 1
3836
+
3837
+ for cwd in (rtl, verify):
3838
+ write_text(cwd / "keel" / "config.yaml", "authorize:\n - chat-reply:soc\n")
3839
+ doctor = run_keel(rtl, "--doctor", env=env).stdout or ""
3840
+ if not re.search(r"chat-reply: authorized.*soc", doctor):
3841
+ report(f"{label} doctor does not report chat-reply:soc as authorized: {[l for l in doctor.splitlines() if 'chat-reply' in l]!r}")
3842
+ return 1
3843
+ if "commit: not authorized" not in doctor:
3844
+ report(f"{label} declaring chat-reply:soc authorized something else.")
3845
+ return 1
3846
+ declared = chat(verify, "notice").stdout
3847
+ if "not an instruction from the user" not in declared:
3848
+ report(f"{label} declaring chat-reply removed the data-not-instruction sentence: {declared!r}")
3849
+ return 1
3850
+ sentence = [line for line in declared.splitlines() if "chat-reply:soc" in line]
3851
+ if len(sentence) != 1:
3852
+ report(f"{label} the notice does not carry exactly one chat-reply sentence naming soc: {declared!r}")
3853
+ return 1
3854
+ if "user" not in sentence[0] or "anything else" not in sentence[0].lower():
3855
+ report(f"{label} the chat-reply sentence does not say that anything else needs the user: {sentence[0]!r}")
3856
+ return 1
3857
+ if declared.replace(sentence[0] + "\n", "") != plain:
3858
+ report(f"{label} declaring chat-reply changed the notice beyond the one sentence.")
3859
+ return 1
3860
+
3861
+ if "chat-reply-authorization" not in {name for name, _ in SCENARIOS}:
3862
+ report(f"{label} scenario is not registered.")
3863
+ return 1
3864
+ report("chat-reply-authorization scenario passed.")
3865
+ return 0
3866
+
3867
+
3707
3868
  def validate_record_derives_skeleton_scenario() -> int:
3708
3869
  """Issue #179: `--record` writes the record slots a capsule implies.
3709
3870
 
@@ -5159,6 +5320,90 @@ def overlay_action_label(text: str, pattern: str) -> str | None:
5159
5320
  return match.group(1)
5160
5321
 
5161
5322
 
5323
+ def validate_update_restores_overlays_scenario() -> int:
5324
+ label = "update-restores-overlays:"
5325
+ with tempfile.TemporaryDirectory(prefix="keel-update-overlays-") as raw:
5326
+ tmp = Path(raw)
5327
+ repo = tmp / "mixed"
5328
+ repo.mkdir()
5329
+ env = os.environ.copy()
5330
+ env["CODEX_HOME"] = str(tmp / "codex-home")
5331
+ for target in ("claude", "codex"):
5332
+ result = run_keel(repo, "--init", "--target", target, env=env)
5333
+ if result.returncode:
5334
+ report(f"{label} init {target} failed: {result.stderr or result.stdout}")
5335
+ return 1
5336
+ # Diagnose a missing foreign target before the upstream rewrite.
5337
+ codex_paths = [p for paths in openspec_overlay_files(
5338
+ repo, "codex", tmp / "codex-home").values() for p in paths]
5339
+ for p in codex_paths:
5340
+ if p.exists():
5341
+ p.write_text(strip_openspec_surface_overlay(p.read_text()), encoding="utf-8")
5342
+ doctor = run_keel(repo, "--doctor", "--target", "claude", env=env)
5343
+ if not re.search(r"Codex.*overlay: (missing|partial)", doctor.stdout):
5344
+ report(f"{label} doctor hid missing Codex overlays while selecting Claude")
5345
+ return 1
5346
+ for iteration in range(2):
5347
+ result = run_keel(repo, "openspec", "update", env=env)
5348
+ if result.returncode:
5349
+ report(f"{label} update failed: {result.stderr or result.stdout}")
5350
+ return 1
5351
+ for target in ("claude", "codex"):
5352
+ error = assert_target_overlays(repo, target, tmp / "codex-home")
5353
+ if error:
5354
+ report(f"{label} update {iteration}: {error}")
5355
+ return 1
5356
+ for action, skill in OVERLAY_ACTION_SKILLS.items():
5357
+ surface = repo / (".claude/skills" if target == "claude" else ".agents/skills") / skill / "SKILL.md"
5358
+ content = surface.read_text()
5359
+ if content.count(OPENSPEC_SURFACE_OVERLAY_START) != 1 or content.count(OPENSPEC_SURFACE_OVERLAY_END) != 1:
5360
+ report(f"{label} managed action has missing or duplicate overlays: {surface}")
5361
+ return 1
5362
+ if not strip_openspec_surface_overlay(content).strip():
5363
+ report(f"{label} upstream body removed: {surface}")
5364
+ return 1
5365
+ legacy = tmp / "legacy"
5366
+ legacy.mkdir()
5367
+ result = run_keel(legacy, "--init", "--target", "claude", env=env)
5368
+ if result.returncode:
5369
+ report(f"{label} legacy fixture init failed")
5370
+ return 1
5371
+ for skill in OVERLAY_ACTION_SKILLS.values():
5372
+ write_text(legacy / ".codex/skills" / skill / "SKILL.md", "# Legacy OpenSpec workflow\n")
5373
+ doctor = run_keel(legacy, "--doctor", "--target", "claude", env=env)
5374
+ if not re.search(r"Codex.*overlay: (missing|partial)", doctor.stdout):
5375
+ report(f"{label} legacy Codex coverage was hidden")
5376
+ return 1
5377
+ # A single-target repository must stay isolated, even with global prompts.
5378
+ single = tmp / "single"
5379
+ single.mkdir()
5380
+ result = run_keel(single, "--init", "--target", "claude", env=env)
5381
+ if result.returncode:
5382
+ report(f"{label} single init failed")
5383
+ return 1
5384
+ result = run_keel(single, "openspec", "update", env=env)
5385
+ if result.returncode or (single / ".agents/skills").exists() or (single / ".codex/skills").exists():
5386
+ report(f"{label} single-target update failed or created Codex surfaces")
5387
+ return 1
5388
+ doctor = run_keel(single, "--doctor", "--target", "claude", env=env)
5389
+ if re.search(r"Codex.*overlay:", doctor.stdout):
5390
+ report(f"{label} global prompts enrolled an unrelated repository")
5391
+ return 1
5392
+ # Invalid options fail in real upstream OpenSpec; no recovery may write.
5393
+ surface = repo / ".agents/skills/openspec-apply-change/SKILL.md"
5394
+ surface.write_text(strip_openspec_surface_overlay(surface.read_text()), encoding="utf-8")
5395
+ files = {p: p.read_bytes() for p in repo.rglob("*.md")}
5396
+ upstream = subprocess.run(
5397
+ ["node", str(ROOT / "node_modules/.bin/openspec"), "update", "--keel-invalid-option"],
5398
+ cwd=repo, env=env, capture_output=True, text=True, check=False)
5399
+ failed = run_keel(repo, "openspec", "update", "--keel-invalid-option", env=env)
5400
+ if not failed.returncode or failed.returncode != upstream.returncode or any(p.read_bytes() != b for p, b in files.items()):
5401
+ report(f"{label} failed update was masked or changed surfaces")
5402
+ return 1
5403
+ report("update-restores-overlays scenario passed.")
5404
+ return 0
5405
+
5406
+
5162
5407
  def validate_openspec_surface_overlay_scenario() -> int:
5163
5408
  with tempfile.TemporaryDirectory(prefix="keel-overlay-") as raw_tmp:
5164
5409
  tmp = Path(raw_tmp)
@@ -19821,9 +20066,9 @@ def validate_native_runtime_projection_scenario() -> int:
19821
20066
  "--json",
19822
20067
  env=env,
19823
20068
  )
19824
- if json.loads(unauthorized_subagent.stdout).get("status") != "blocked":
20069
+ if json.loads(unauthorized_subagent.stdout).get("status") != "ready":
19825
20070
  report(
19826
- f"native-runtime-projection {target} activated subagent implicitly."
20071
+ f"native-runtime-projection {target} requires extra helper activation."
19827
20072
  )
19828
20073
  return 1
19829
20074
 
@@ -20585,6 +20830,7 @@ STANDING_AUTHORIZATION_ACTIONS = (
20585
20830
  "archive",
20586
20831
  "continuation",
20587
20832
  "protocol-refresh",
20833
+ "chat-reply",
20588
20834
  )
20589
20835
 
20590
20836
 
@@ -21708,7 +21954,7 @@ def validate_delegation_resident_text_scenario() -> int:
21708
21954
  agents = ROOT / "AGENTS.md"
21709
21955
  text = flat(agents)
21710
21956
  for needle in (
21711
- "as delegates implementing the selected task inside",
21957
+ "implementation delegates use the selected task write authority inside",
21712
21958
  "a guard manifest is active",
21713
21959
  "re-runs each",
21714
21960
  "check itself before recording Evidence",
@@ -21729,7 +21975,7 @@ def validate_delegation_resident_text_scenario() -> int:
21729
21975
  # constant; a raise with no reason beside it is the drift this guards.
21730
21976
  bootstrap = ROOT / "assets/bootstrap/AGENTS.md"
21731
21977
  boot = flat(bootstrap)
21732
- if re.sub(r"\s+", " ", "One current agent owns writes") not in boot:
21978
+ if re.sub(r"\s+", " ", "One agent owns decisions") not in boot:
21733
21979
  report("delegation-resident-text: the bootstrap lost its single-writer default.")
21734
21980
  return 1
21735
21981
  block = bootstrap.read_text(encoding="utf-8")
@@ -21783,8 +22029,8 @@ def validate_delegation_resident_text_scenario() -> int:
21783
22029
  if re.sub(r"\s+", " ", "helpers stay read-only/evidence-only") not in body:
21784
22030
  report(f"delegation-resident-text: {path.relative_to(ROOT)} dropped the helper default.")
21785
22031
  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.")
22032
+ if re.sub(r"\s+", " ", "matching active guard") not in body:
22033
+ report(f"delegation-resident-text: {path.relative_to(ROOT)} does not state the implementation guard boundary.")
21788
22034
  return 1
21789
22035
  if source.read_bytes() != installed.read_bytes():
21790
22036
  report("delegation-resident-text: the template source and its installed copy diverged.")
@@ -21818,7 +22064,7 @@ def validate_delegation_overlay_scenario() -> int:
21818
22064
  # its results are worth. Asserted on every generated copy, because the
21819
22065
  # overlay is what a subagent on that surface actually reads.
21820
22066
  needles = (
21821
- "where `delegation:` is declared",
22067
+ "using existing task write authority",
21822
22068
  "a guard manifest is active",
21823
22069
  "only inside `Touch`",
21824
22070
  "re-runs each `M<n>` check itself before recording Evidence",
@@ -22264,8 +22510,8 @@ def validate_delegation_sole_authority_scenario() -> int:
22264
22510
  # M1 — the stop list refuses an undeclared delegation and no longer
22265
22511
  # refuses a declared one outright.
22266
22512
  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.")
22513
+ if re.sub(r"\s+", " ", "matching active guard") not in skill_text:
22514
+ report("delegation-sole-authority: the stop list omits guarded task authority.")
22269
22515
  return 1
22270
22516
  if re.sub(r"\s+", " ", "any request to delegate implementation to another agent") in skill_text:
22271
22517
  report("delegation-sole-authority: the stop list still refuses every delegation outright.")
@@ -22281,6 +22527,9 @@ def validate_delegation_sole_authority_scenario() -> int:
22281
22527
  if re.sub(r"\s+", " ", "read-only subagent helpers only") in text:
22282
22528
  report(f"delegation-sole-authority: {path.name} still says read-only helpers only.")
22283
22529
  return 1
22530
+ if "matching active guard" not in text or "host policy" not in text.lower():
22531
+ report(f"delegation-sole-authority: {path.name} omits guard or host boundary.")
22532
+ return 1
22284
22533
 
22285
22534
  # M2 — the canonical source and its distribution copy stay byte-identical.
22286
22535
  if canonical.read_bytes() != packaged.read_bytes():
@@ -22298,6 +22547,144 @@ def validate_delegation_sole_authority_scenario() -> int:
22298
22547
  return 0
22299
22548
 
22300
22549
 
22550
+ def validate_model_chosen_subagents_scenario() -> int:
22551
+ label = "model-chosen-subagents:"
22552
+ with tempfile.TemporaryDirectory(prefix="keel-model-subagents-") as raw:
22553
+ repo = Path(raw)
22554
+ write_gate_fixture(repo, standing_authorization_task())
22555
+ def project(*extra: str) -> dict:
22556
+ result = run_keel(repo, "project", "--target", "codex",
22557
+ "--event", "subagent-start", "--change", "demo", "--task", "1.1", "--json", *extra)
22558
+ return json.loads(result.stdout)
22559
+ helper = project()
22560
+ if helper.get("status") != "ready":
22561
+ report(f"{label} ordinary helper still requires activation: {helper.get('reasons')}")
22562
+ return 1
22563
+ if helper["projection"].get("subagentMode") != "helper" or helper["projection"].get("delegation"):
22564
+ report(f"{label} helper posture grants delegation")
22565
+ return 1
22566
+ write_authorize_config(repo, "delegation:\n tier: turbo\n")
22567
+ if project().get("status") != "ready":
22568
+ report(f"{label} helper depends on implementation tier metadata")
22569
+ return 1
22570
+ write_authorize_config(repo, "fast_check: echo ok\n")
22571
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22572
+ report(f"{label} unguarded implementation allowed")
22573
+ return 1
22574
+ started = run_keel(repo, "gate", "task-start", "--change", "demo", "--task", "1.1", "--record", "--json")
22575
+ if json.loads(started.stdout).get("status") != "pass":
22576
+ report(f"{label} valid task did not start: {started.stdout}")
22577
+ return 1
22578
+ delegate = project("--subagent-mode", "implementation")
22579
+ if delegate.get("status") != "ready":
22580
+ report(f"{label} guarded implementation requires tier: {delegate.get('reasons')}")
22581
+ return 1
22582
+ brief = delegate["projection"]
22583
+ if brief.get("delegation", {}).get("writeBoundary") != ["src/feature.js"] or brief["delegation"].get("tier") is not None:
22584
+ report(f"{label} delegate boundary or absent tier incorrect")
22585
+ return 1
22586
+ 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"]):
22587
+ report(f"{label} ownership prohibitions lost")
22588
+ return 1
22589
+ manifest_path = repo / "keel/guard.json"
22590
+ saved = manifest_path.read_bytes()
22591
+ manifest_path.write_text("{}")
22592
+ if project().get("status") != "ready":
22593
+ report(f"{label} malformed implementation guard blocked read-only help")
22594
+ return 1
22595
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22596
+ report(f"{label} malformed guard allowed implementation")
22597
+ return 1
22598
+ manifest_path.write_bytes(saved)
22599
+ manifest = json.loads(saved)
22600
+ manifest["fingerprint"]["value"] = "0" * 64
22601
+ manifest_path.write_text(json.dumps(manifest))
22602
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22603
+ report(f"{label} drifted guard allowed implementation")
22604
+ return 1
22605
+ manifest_path.write_bytes(saved)
22606
+ manifest = json.loads(saved)
22607
+ manifest["touch"].append("src/outside.js")
22608
+ manifest_path.write_text(json.dumps(manifest))
22609
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22610
+ report(f"{label} widened manifest Touch allowed implementation")
22611
+ return 1
22612
+ manifest = json.loads(saved)
22613
+ manifest["task"] = "9.9"
22614
+ manifest_path.write_text(json.dumps(manifest))
22615
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22616
+ report(f"{label} different task guard allowed implementation")
22617
+ return 1
22618
+ manifest_path.write_bytes(saved)
22619
+ shutil.copytree(repo / "openspec/changes/demo", repo / "openspec/changes/other")
22620
+ other_start = run_keel(repo, "gate", "task-start", "--change", "other", "--task", "1.1", "--record", "--json")
22621
+ if json.loads(other_start.stdout).get("status") != "pass":
22622
+ report(f"{label} other task guard fixture did not start")
22623
+ return 1
22624
+ mismatch = project("--subagent-mode", "implementation")
22625
+ if mismatch.get("status") == "ready":
22626
+ report(f"{label} active guard for another owner allowed implementation")
22627
+ return 1
22628
+ if "matching" not in " ".join(mismatch.get("reasons", [])):
22629
+ report(f"{label} other-owner refusal did not name guard mismatch")
22630
+ return 1
22631
+ manifest_path.write_bytes(saved)
22632
+ task_path = repo / "openspec/changes/demo/tasks.md"
22633
+ task_before = task_path.read_text()
22634
+ task_path.write_text(task_before.replace("src/feature.js", "src/other.js"))
22635
+ if project("--subagent-mode", "implementation").get("status") == "ready":
22636
+ report(f"{label} authority drift allowed implementation")
22637
+ return 1
22638
+ task_path.write_text(task_before)
22639
+ returned = run_keel(repo, "project", "--event", "subagent-stop", "--subagent-mode", "implementation", "--native-complete", "--change", "demo", "--task", "1.1", "--json")
22640
+ returned_payload = json.loads(returned.stdout)
22641
+ if task_path.read_text() != task_before:
22642
+ report(f"{label} delegate completion modified task authority or records")
22643
+ return 1
22644
+ if returned_payload.get("projection", {}).get("returnAuthority") != "report-and-evidence-only":
22645
+ report(f"{label} delegate return did not remain evidence-only")
22646
+ return 1
22647
+ goal = run_keel(repo, "project", "--event", "goal", "--change", "demo", "--task", "1.1", "--json")
22648
+ if json.loads(goal.stdout).get("status") != "blocked":
22649
+ report(f"{label} goal activation became implicit")
22650
+ return 1
22651
+ configured = repo / "configured"
22652
+ configured.mkdir()
22653
+ write_gate_fixture(configured, standing_authorization_task())
22654
+ write_authorize_config(configured, "delegation:\n tier: deep\n")
22655
+ explicit = run_keel(configured, "project", "--event", "subagent-start", "--authorize", "subagent", "--subagent-mode", "helper", "--change", "demo", "--task", "1.1", "--json")
22656
+ payload = json.loads(explicit.stdout)
22657
+ if payload.get("status") != "ready" or payload["projection"].get("delegation"):
22658
+ report(f"{label} explicit helper became writer due to tier metadata")
22659
+ return 1
22660
+ for name,task,config in [
22661
+ ("bad-task-tier", standing_authorization_task().replace(" - Covers:", " - Delegation: turbo\n - Covers:"), ""),
22662
+ ("bad-config-tier", standing_authorization_task(), "delegation:\n tier: turbo\n"),
22663
+ ("plan-first", standing_authorization_task().replace(" - Covers:", " - Mode: plan-first\n - Covers:"), ""),
22664
+ ("diagnose-only", standing_authorization_task().replace(" - Covers:", " - Mode: diagnose-only\n - Covers:").replace(" - src/feature.js", " - none"), ""),
22665
+ ("repo-action", standing_authorization_task().replace(" - Covers:", " - Mode: repo-action\n - Covers:").replace(" - src/feature.js", " - none"), ""),
22666
+ ]:
22667
+ other = repo / name
22668
+ other.mkdir()
22669
+ write_gate_fixture(other, task)
22670
+ write_authorize_config(other, config)
22671
+ result = run_keel(other, "project", "--event", "subagent-start", "--change", "demo", "--task", "1.1", "--json")
22672
+ if json.loads(result.stdout).get("status") != "ready":
22673
+ report(f"{label} read-only helper refused for {name}: {result.stdout}")
22674
+ return 1
22675
+ result = run_keel(other, "project", "--event", "subagent-start", "--subagent-mode", "implementation", "--change", "demo", "--task", "1.1", "--json")
22676
+ rejected = json.loads(result.stdout)
22677
+ if rejected.get("status") == "ready":
22678
+ report(f"{label} implementation allowed for {name}")
22679
+ return 1
22680
+ expected = "turbo" if "tier" in name else "implementation task"
22681
+ if expected not in " ".join(rejected.get("reasons", [])):
22682
+ report(f"{label} {name} refusal named wrong cause: {rejected.get('reasons')}")
22683
+ return 1
22684
+ report("model-chosen-subagents scenario passed.")
22685
+ return 0
22686
+
22687
+
22301
22688
  def validate_delegation_projection_scenario() -> int:
22302
22689
  """The projection Keel already publishes carries the delegation, and
22303
22690
  refuses where the preconditions for one do not hold.
@@ -22450,8 +22837,8 @@ def validate_delegation_projection_scenario() -> int:
22450
22837
  except json.JSONDecodeError:
22451
22838
  report(f"delegation-projection: unauthorized start returned no JSON: {unauthorized.stdout!r}")
22452
22839
  return 1
22453
- if refused.get("status") == "ready":
22454
- report("delegation-projection: subagent-start projected without authorization.")
22840
+ if refused.get("status") != "ready":
22841
+ report("delegation-projection: ordinary helper required extra authorization.")
22455
22842
  return 1
22456
22843
 
22457
22844
  report("delegation-projection scenario passed.")
@@ -23494,8 +23881,8 @@ def validate_continuation_docs_scenario() -> int:
23494
23881
  # to spell all of it: a reader copies from the list they are shown.
23495
23882
  for needle in (
23496
23883
  "accepted names: commit, push, release, archive, continuation, "
23497
- "issue:<owner>/<repo>, protocol-refresh",
23498
- "The seven names above are the whole vocabulary.",
23884
+ "issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>",
23885
+ "The eight names above are the whole vocabulary.",
23499
23886
  "`protocol-refresh`, the seventh name",
23500
23887
  ):
23501
23888
  if needle not in readme:
@@ -23503,7 +23890,7 @@ def validate_continuation_docs_scenario() -> int:
23503
23890
  return 1
23504
23891
 
23505
23892
  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:
23893
+ if "commit, push, release, archive,\n# continuation, issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>" not in config_text:
23507
23894
  report(
23508
23895
  f"{label}: keel/config.yaml's comment lacks: protocol-refresh in the "
23509
23896
  "seven-name vocabulary."
@@ -33717,6 +34104,14 @@ SCENARIOS: tuple = (
33717
34104
  "chat-archive",
33718
34105
  validate_chat_archive_scenario,
33719
34106
  ),
34107
+ (
34108
+ "chat-reply-authorization",
34109
+ validate_chat_reply_authorization_scenario,
34110
+ ),
34111
+ (
34112
+ "chat-notice-check",
34113
+ validate_chat_notice_check_scenario,
34114
+ ),
33720
34115
  (
33721
34116
  "record-derives-skeleton",
33722
34117
  validate_record_derives_skeleton_scenario,
@@ -33736,6 +34131,8 @@ SCENARIOS: tuple = (
33736
34131
  ("version-alignment", validate_version_alignment_scenario),
33737
34132
  ("sync-surface-overlay", validate_sync_surface_overlay_scenario),
33738
34133
  ("openspec-surface-overlay", validate_openspec_surface_overlay_scenario),
34134
+ ("update-restores-overlays", validate_update_restores_overlays_scenario),
34135
+ ("model-chosen-subagents", validate_model_chosen_subagents_scenario),
33739
34136
  ("uninstall", validate_uninstall_scenario),
33740
34137
  (
33741
34138
  "uninstall-removes-the-overlay",
@@ -23,9 +23,9 @@ const CAPABILITY_COMMANDS = {
23
23
  "execution.worktree":
24
24
  "keel project --target <target> --event worktree --expected-owner <owner> --json",
25
25
  "delegation.context":
26
- "keel project --target <target> --event subagent-start --authorize subagent --json",
26
+ "keel project --target <target> --event subagent-start --json",
27
27
  "delegation.return":
28
- "keel project --target <target> --event subagent-stop --authorize subagent --json",
28
+ "keel project --target <target> --event subagent-stop --json",
29
29
  };
30
30
 
31
31
  const SUPPORTED_TARGETS = new Set(["claude", "codex", "opencode"]);
@@ -39,6 +39,7 @@ const USAGE = [
39
39
  "keel chat bridge pause <30m|2h|1d> | resume",
40
40
  "keel chat bridge status [--json]",
41
41
  "keel chat notice (what is unread and addressed to you, for any host; always exits 0)",
42
+ "keel chat notice --check (for schedulers: no output; exit 0 only when something addressed to you is unread, else 1)",
42
43
  "keel chat hook session-start|user-prompt-submit|file-changed|session-end (Claude Code hook; JSON on stdin)",
43
44
  "Every command takes --repo <path> to act on another repository.",
44
45
  ];
@@ -54,10 +55,10 @@ const VALUED = {
54
55
  "--since": "since",
55
56
  };
56
57
  const REPEATED = { "--member": "members" };
57
- const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail" };
58
+ const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check" };
58
59
 
59
60
  function parseChatArgs(argv) {
60
- const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false };
61
+ const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false };
61
62
  for (const key of Object.values(VALUED)) options[key] = null;
62
63
  for (let index = 0; index < argv.length; index += 1) {
63
64
  const arg = argv[index];
@@ -201,15 +202,22 @@ function runView(where, group, options) {
201
202
  // Keeps printing records as they arrive until interrupted. Polling the log
202
203
  // directory, rather than a file watcher, behaves the same on every platform
203
204
  // and over a synced folder.
205
+ // Remembers every id already accounted for rather than the last one: a
206
+ // record can arrive with an id that sorts earlier — written by a machine
207
+ // whose clock runs behind, or landing between the first read and the first
208
+ // poll — and comparing against the newest id would skip it for good (#196).
204
209
  function follow(where, role, group, initial, options) {
205
- let last = initial.length ? initial[initial.length - 1].id : "";
210
+ const known = new Set(initial.map((record) => record.id));
206
211
  const timer = setInterval(() => {
207
212
  const records = store.readLog(where, group);
208
- const fresh = displayRecords(records).filter((record) => record.id > last);
213
+ const fresh = records.filter((record) => !known.has(record.id));
209
214
  if (!fresh.length) return;
210
- for (const record of fresh) out(options.json ? JSON.stringify(publicRecord(record)) : formatLine(record));
211
- last = records[records.length - 1].id;
212
- if (!options.peek && role) store.advanceCursor(where, role, group, last);
215
+ for (const record of fresh) known.add(record.id);
216
+ const freshIds = new Set(fresh.map((record) => record.id));
217
+ for (const record of displayRecords(records).filter((shown) => freshIds.has(shown.id))) {
218
+ out(options.json ? JSON.stringify(publicRecord(record)) : formatLine(record));
219
+ }
220
+ if (!options.peek && role) store.advanceCursor(where, role, group, records[records.length - 1].id);
213
221
  }, 500);
214
222
  const stop = () => {
215
223
  clearInterval(timer);
@@ -432,6 +440,10 @@ function runChat(argv) {
432
440
  if (result.stderr) process.stderr.write(result.stderr);
433
441
  return result.code;
434
442
  }
443
+ // `notice --check` is what a scheduler runs before deciding to start a
444
+ // model turn (#194): no output, no file written — not even presence or
445
+ // the 5.83 migration — and 0 only when something would wake the role.
446
+ if (options.positionals[0] === "notice" && options.check) return notice.check(cwd);
435
447
  // A notice is read by hosts on every prompt: outside a repository it says
436
448
  // nothing and still exits 0.
437
449
  if (options.positionals[0] === "notice" && !store.locate(cwd)) return 0;