@christang/keel 5.171.0 → 5.173.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.
@@ -51,8 +51,8 @@ REQUIRED_SCRIPTS = [
51
51
  "scripts/validate_plugin.py",
52
52
  ]
53
53
 
54
- PACKAGE_VERSION = "5.171.0"
55
- PROTOCOL_VERSION = "5.171.0"
54
+ PACKAGE_VERSION = "5.173.0"
55
+ PROTOCOL_VERSION = "5.173.0"
56
56
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
57
57
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
58
58
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -80,7 +80,6 @@ CORE_KEEL_SKILLS = {
80
80
  "keel-debug-failure",
81
81
  "keel-handoff",
82
82
  "keel-review-checklist",
83
- "keel-run-single-task-goal",
84
83
  "keel-tdd-or-test-first",
85
84
  }
86
85
  LEGACY_PROFILE_SKILLS = (
@@ -142,7 +141,8 @@ RESIDENT_BLOCKS = [
142
141
  # Touch and a `bound…` word in one statement. The other prose
143
142
  # entries stay literal until one of them needs the same freedom.
144
143
  re.compile(r"Touch\b[^\n]*\bbound", re.IGNORECASE),
145
- "read-only report/evidence",
144
+ # #414: subagents are the model's choice, treated as the main agent.
145
+ "treated as the main agent is",
146
146
  "native plugin",
147
147
  "keel --init",
148
148
  # Routing is the one durable rule with no gate behind it, so the
@@ -260,7 +260,7 @@ SKILL_DOC_REQUIREMENTS = [
260
260
  "required": [
261
261
  "Follow-ups are limited to directly observed blockers, risks, missing scope, or escalation needs",
262
262
  "Do not include roadmap suggestions, new feature suggestions, unrelated architecture critique, or opportunistic refactor suggestions",
263
- "same failure at most 2 attempts",
263
+ "There is no fixed attempt count",
264
264
  "## Context to read",
265
265
  "## Standalone use",
266
266
  "candidate completion gate",
@@ -770,8 +770,8 @@ def validate_openspec_schema(errors: list[str]) -> None:
770
770
  "Report",
771
771
  "Execution recommendation",
772
772
  "Autonomy boundary",
773
- "current Keel agent remains task owner and executor",
774
- "Keep task decisions in the current agent",
773
+ "A subagent is the model's choice and is treated as the main agent is",
774
+ "approved `tasks.md` in order",
775
775
  "Modify only files listed under Touch",
776
776
  "repository-wide read authority is read-only",
777
777
  "Out-of-scope Need",
@@ -1235,10 +1235,7 @@ def validate_target_surface_scenario() -> int:
1235
1235
  or "native plugin runtime: manual" not in claude_doctor.stdout
1236
1236
  or "Target capabilities (claude):" not in claude_doctor.stdout
1237
1237
  or "gate.change-close: manual" not in claude_doctor.stdout
1238
- or "execution.goal: manual" not in claude_doctor.stdout
1239
- or "helper byteStability: enforced" not in claude_doctor.stdout
1240
- or "helper nestedDelegationPrevention: enforced" not in claude_doctor.stdout
1241
- or "helper execution: manual" not in claude_doctor.stdout
1238
+ or "execution.worktree: manual" not in claude_doctor.stdout
1242
1239
  ):
1243
1240
  report("target-surface scenario Claude doctor did not report full surface.")
1244
1241
  report((claude_doctor.stderr or claude_doctor.stdout).strip())
@@ -1265,10 +1262,7 @@ def validate_target_surface_scenario() -> int:
1265
1262
  or "native plugin runtime: manual" not in codex_doctor.stdout
1266
1263
  or "Target capabilities (codex):" not in codex_doctor.stdout
1267
1264
  or "gate.change-close: manual" not in codex_doctor.stdout
1268
- or "execution.goal: manual" not in codex_doctor.stdout
1269
- or "helper byteStability: enforced" not in codex_doctor.stdout
1270
- or "helper nestedDelegationPrevention: enforced" not in codex_doctor.stdout
1271
- or "helper execution: manual" not in codex_doctor.stdout
1265
+ or "execution.worktree: manual" not in codex_doctor.stdout
1272
1266
  ):
1273
1267
  report("target-surface scenario Codex doctor did not report full surface.")
1274
1268
  report((codex_doctor.stderr or codex_doctor.stdout).strip())
@@ -10148,7 +10142,7 @@ def validate_expectation_completion_gates_scenario() -> int:
10148
10142
  "reason:",
10149
10143
  ]
10150
10144
  archive_overlay_snippets = [
10151
- "owns final sync/archive decisions",
10145
+ "keel gate change-close --action archive",
10152
10146
  "critical expectation",
10153
10147
  "behavior evidence",
10154
10148
  "durable follow-up owner",
@@ -10809,22 +10803,20 @@ def assert_openspec_overlay(path: Path, action: str) -> str | None:
10809
10803
  if content.count(OPENSPEC_SURFACE_OVERLAY_END) != 1:
10810
10804
  return f"{path} must contain exactly one Keel overlay end marker"
10811
10805
 
10806
+ # Since #414 the overlay says one neutral thing about subagents and assigns
10807
+ # no ownership; apply continues through an approved task list.
10812
10808
  required = [
10813
10809
  "Keel rules below take precedence",
10814
- "Target-native subagent gate",
10815
- "current agent remains",
10816
- "return report/evidence only",
10817
- "Keel ownership",
10810
+ "A subagent is the model's choice and is treated as the main agent is",
10818
10811
  ]
10819
10812
  if action == "apply":
10820
10813
  required.extend(
10821
10814
  [
10822
- "Keel task owner",
10815
+ "approved `tasks.md` in order",
10823
10816
  "Task Authoring Gate",
10824
10817
  "Slice Start Gate",
10825
10818
  "source expectations",
10826
10819
  "Rough future slices",
10827
- "cannot mark tasks complete",
10828
10820
  # A confirmation the owner already declared is routed to the
10829
10821
  # declaration; one they did not declare is still asked for, and
10830
10822
  # neither case touches the proof.
@@ -10836,12 +10828,12 @@ def assert_openspec_overlay(path: Path, action: str) -> str | None:
10836
10828
  else:
10837
10829
  required.extend(
10838
10830
  [
10839
- "owns final sync/archive decisions",
10831
+ "keel gate change-close --action archive",
10832
+ "keel-review-checklist",
10840
10833
  "critical expectation",
10841
10834
  "behavior evidence",
10842
10835
  "durable follow-up owner",
10843
10836
  "explicit discard reason",
10844
- "cannot archive, sync, change acceptance, or bypass completion gates",
10845
10837
  "standing-authorizes `archive`",
10846
10838
  "completion gate and follow-up ownership checks still run",
10847
10839
  ]
@@ -13930,10 +13922,9 @@ def validate_the_spec_names_the_managed_set_scenario() -> int:
13930
13922
  created. It is therefore the location most likely to drift and the one
13931
13923
  least likely to be noticed, which is why it is checked by name here.
13932
13924
 
13933
- Two named locations, not a scan. Three statements in the published specs
13934
- name a proper subset of the managed set and are correct — the doctor's
13935
- command-surface label, which excludes the authoring action on purpose;
13936
- `sync/archive decisions`, which names what the current agent owns; and
13925
+ Two named locations, not a scan. Statements in the published specs name a
13926
+ proper subset of the managed set and are correct — the doctor's
13927
+ command-surface label, which excludes the authoring action on purpose, and
13937
13928
  `authoring/apply/archive/sync`, which spells `propose` as authoring. A
13938
13929
  check that refused those would cost more than the drift it catches.
13939
13930
  """
@@ -14057,11 +14048,14 @@ def validate_the_spec_names_the_managed_set_scenario() -> int:
14057
14048
  "move with it rather than be dropped."
14058
14049
  )
14059
14050
  return 1
14060
- if "sync/archive decisions" not in published:
14051
+ # `sync/archive decisions` left the overlay spec with the ownership
14052
+ # requirements (#414); `authoring/apply/archive/sync` is the correct subset
14053
+ # spelling that remains in it.
14054
+ if "authoring/apply/archive/sync" not in published:
14061
14055
  report(
14062
- f"{label}: the overlay spec no longer carries `sync/archive "
14063
- "decisions`, the third correct subset spelling this check must "
14064
- "not refuse."
14056
+ f"{label}: the overlay spec no longer carries "
14057
+ "`authoring/apply/archive/sync`, the correct subset spelling this "
14058
+ "check must not refuse."
14065
14059
  )
14066
14060
  return 1
14067
14061
 
@@ -18049,10 +18043,6 @@ def validate_guard_containment_is_resolved_scenario() -> int:
18049
18043
  looked like a path outside it, and the guard returned before reading the
18050
18044
  manifest at all. Measured 2026-08-02: the same out-of-Touch file was denied
18051
18045
  by its resolved path and allowed through a link to the same directory.
18052
-
18053
- `src/core/helper.js` had the mirror image, calling a path inside the
18054
- worktree external, which is why `native-helper-read-only` was red on macOS
18055
- — where `/tmp` is a link — and green on Linux CI.
18056
18046
  """
18057
18047
  label = "guard-containment-is-resolved"
18058
18048
  with tempfile.TemporaryDirectory(prefix="keel-containment-") as raw:
@@ -18147,38 +18137,6 @@ def validate_guard_containment_is_resolved_scenario() -> int:
18147
18137
  ]):
18148
18138
  return 1
18149
18139
 
18150
- # M4 — the same question, asked by the helper about its baseline.
18151
- def capture(target: Path) -> subprocess.CompletedProcess[str]:
18152
- return run_keel(
18153
- repo, "project", "helper", "--target", "codex",
18154
- "--capture-baseline", "--baseline", str(target), "--json",
18155
- )
18156
-
18157
- inside_via_link = capture(link / "baseline.json")
18158
- if inside_via_link.returncode == 0:
18159
- report(
18160
- f"{label} M4 captured a helper baseline at a path that resolves "
18161
- "inside the worktree, because it was named through a symlink. "
18162
- "The baseline must live outside the repository it snapshots."
18163
- )
18164
- return 1
18165
- if (repo / "baseline.json").exists():
18166
- report(
18167
- f"{label} M4 refused the capture but the baseline file was "
18168
- "written into the repository anyway."
18169
- )
18170
- return 1
18171
- outside = capture(root / "outside.json")
18172
- if outside.returncode != 0:
18173
- report(
18174
- f"{label} M4 refused a baseline that genuinely resolves outside "
18175
- "the worktree, so the containment fix blocks correct use."
18176
- )
18177
- report((outside.stderr or outside.stdout).strip())
18178
- return 1
18179
- if not (root / "outside.json").is_file():
18180
- report(f"{label} M4 reported a capture that wrote no baseline.")
18181
- return 1
18182
18140
  if label not in {name for name, _ in SCENARIOS}:
18183
18141
  report(f"{label}: the scenario registry does not include it.")
18184
18142
  return 1
@@ -22936,11 +22894,7 @@ def validate_target_capability_adapters_scenario() -> int:
22936
22894
  "gate.task-start",
22937
22895
  "gate.task-complete",
22938
22896
  "gate.change-close",
22939
- "execution.goal",
22940
- "execution.task-view",
22941
22897
  "execution.worktree",
22942
- "delegation.context",
22943
- "delegation.return",
22944
22898
  )
22945
22899
  with tempfile.TemporaryDirectory(prefix="keel-capabilities-") as raw_tmp:
22946
22900
  root = Path(raw_tmp)
@@ -22999,14 +22953,8 @@ def validate_target_capability_adapters_scenario() -> int:
22999
22953
  report(doctor.stdout.strip())
23000
22954
  return 1
23001
22955
  # Native target capabilities never claim enforced behavior without
23002
- # runtime evidence; the deterministic Keel Core helper dimensions
23003
- # (byte-stability, nested-delegation prevention) are a separate,
23004
- # legitimately enforced surface reported on their own helper lines.
23005
- native_surface = "\n".join(
23006
- line
23007
- for line in doctor.stdout.splitlines()
23008
- if not line.startswith("helper ")
23009
- )
22956
+ # runtime evidence.
22957
+ native_surface = doctor.stdout
23010
22958
  if "enforced" in native_surface:
23011
22959
  report(
23012
22960
  f"target-capability-adapters {target} invented enforced behavior."
@@ -23377,7 +23325,6 @@ PLUGIN_SKILLS = (
23377
23325
  "keel-debug-failure",
23378
23326
  "keel-handoff",
23379
23327
  "keel-review-checklist",
23380
- "keel-run-single-task-goal",
23381
23328
  "keel-tdd-or-test-first",
23382
23329
  )
23383
23330
 
@@ -23847,7 +23794,8 @@ SESSION_START_DISCLOSURE = "to the user in your first reply"
23847
23794
  RESIDENT_SESSION_START_REQUIRED = (
23848
23795
  SESSION_START_DISCLOSURE,
23849
23796
  "keel context",
23850
- "never infer continuity from native memory",
23797
+ # #414: memory and transcripts may inform; `keel context` still decides.
23798
+ "`keel context` decides the current task",
23851
23799
  )
23852
23800
 
23853
23801
 
@@ -27545,8 +27493,6 @@ def validate_native_runtime_projection_scenario() -> int:
27545
27493
  payload.get("contract") != gate_contract
27546
27494
  or projection.get("fingerprint")
27547
27495
  != gate_contract.get("fingerprint")
27548
- or projection.get("helperAuthority")
27549
- != "read-only-evidence-only"
27550
27496
  or projection.get("prohibitions")
27551
27497
  != gate_contract.get("capsule", {}).get("prohibitions")
27552
27498
  ):
@@ -27556,179 +27502,7 @@ def validate_native_runtime_projection_scenario() -> int:
27556
27502
  report(json.dumps(payload, indent=2))
27557
27503
  return 1
27558
27504
 
27559
- unauthorized_goal = run_keel(
27560
- repo,
27561
- "project",
27562
- "--target",
27563
- target,
27564
- "--event",
27565
- "goal",
27566
- "--change",
27567
- "demo",
27568
- "--task",
27569
- "1.1",
27570
- "--json",
27571
- env=env,
27572
- )
27573
- if (
27574
- unauthorized_goal.returncode != 0
27575
- or json.loads(unauthorized_goal.stdout).get("status") != "blocked"
27576
- ):
27577
- report(f"native-runtime-projection {target} enabled goal implicitly.")
27578
- return 1
27579
-
27580
- authorized_task_view = run_keel(
27581
- repo,
27582
- "project",
27583
- "--target",
27584
- target,
27585
- "--event",
27586
- "task-view",
27587
- "--authorize",
27588
- "task-view",
27589
- "--change",
27590
- "demo",
27591
- "--task",
27592
- "1.1",
27593
- "--json",
27594
- env=env,
27595
- )
27596
- if (
27597
- authorized_task_view.returncode != 0
27598
- or json.loads(authorized_task_view.stdout).get("status") != "ready"
27599
- or "[ ] 1.1" not in tasks_path.read_text(encoding="utf-8")
27600
- ):
27601
- report(
27602
- f"native-runtime-projection {target} task view was not one-way."
27603
- )
27604
- return 1
27605
-
27606
- authorized_goal = run_keel(
27607
- repo,
27608
- "project",
27609
- "--target",
27610
- target,
27611
- "--event",
27612
- "goal",
27613
- "--authorize",
27614
- "goal",
27615
- "--change",
27616
- "demo",
27617
- "--task",
27618
- "1.1",
27619
- "--native-complete",
27620
- "--json",
27621
- env=env,
27622
- )
27623
- goal_payload = json.loads(authorized_goal.stdout)
27624
- if (
27625
- authorized_goal.returncode != 0
27626
- or goal_payload.get("status") != "ready"
27627
- or goal_payload.get("projection", {}).get("acceptance")
27628
- != ["observable result"]
27629
- or not goal_payload.get("projection", {}).get("stopBoundary")
27630
- or not any(
27631
- "ignored" in warning.lower()
27632
- for warning in goal_payload.get("warnings", [])
27633
- )
27634
- or "[ ] 1.1" not in tasks_path.read_text(encoding="utf-8")
27635
- ):
27636
- report(
27637
- f"native-runtime-projection {target} authorized goal violated "
27638
- "one-way projection."
27639
- )
27640
- report((authorized_goal.stderr or authorized_goal.stdout).strip())
27641
- return 1
27642
-
27643
- unauthorized_subagent = run_keel(
27644
- repo,
27645
- "project",
27646
- "--target",
27647
- target,
27648
- "--event",
27649
- "subagent-start",
27650
- "--change",
27651
- "demo",
27652
- "--task",
27653
- "1.1",
27654
- "--json",
27655
- env=env,
27656
- )
27657
- if json.loads(unauthorized_subagent.stdout).get("status") != "ready":
27658
- report(
27659
- f"native-runtime-projection {target} requires extra helper activation."
27660
- )
27661
- return 1
27662
-
27663
- authorized_subagent = run_keel(
27664
- repo,
27665
- "project",
27666
- "--target",
27667
- target,
27668
- "--event",
27669
- "subagent-start",
27670
- "--authorize",
27671
- "subagent",
27672
- "--change",
27673
- "demo",
27674
- "--task",
27675
- "1.1",
27676
- "--json",
27677
- env=env,
27678
- )
27679
- subagent_payload = json.loads(authorized_subagent.stdout)
27680
- bounded = subagent_payload.get("projection", {})
27681
- if (
27682
- authorized_subagent.returncode != 0
27683
- or bounded.get("read")
27684
- != subagent_payload.get("contract", {}).get("capsule", {}).get("read")
27685
- or "README.md" not in bounded.get("read", [])
27686
- or "openspec/changes/demo/tasks.md" not in bounded.get("read", [])
27687
- or bounded.get("touch") != ["src/feature.js"]
27688
- or "M1: node test.js" not in bounded.get("evidenceContract", [])
27689
- or not any(
27690
- "must not mark tasks complete" in item
27691
- for item in bounded.get("prohibitions", [])
27692
- )
27693
- ):
27694
- report(
27695
- f"native-runtime-projection {target} subagent context was unbounded."
27696
- )
27697
- report(
27698
- (authorized_subagent.stderr or authorized_subagent.stdout).strip()
27699
- )
27700
- return 1
27701
-
27702
- subagent_return = run_keel(
27703
- repo,
27704
- "project",
27705
- "--target",
27706
- target,
27707
- "--event",
27708
- "subagent-stop",
27709
- "--authorize",
27710
- "subagent",
27711
- "--change",
27712
- "demo",
27713
- "--task",
27714
- "1.1",
27715
- "--native-complete",
27716
- "--json",
27717
- env=env,
27718
- )
27719
- if (
27720
- subagent_return.returncode != 0
27721
- or json.loads(subagent_return.stdout)
27722
- .get("projection", {})
27723
- .get("returnAuthority")
27724
- != "report-and-evidence-only"
27725
- or "[ ] 1.1" not in tasks_path.read_text(encoding="utf-8")
27726
- ):
27727
- report(
27728
- f"native-runtime-projection {target} accepted subagent completion."
27729
- )
27730
- return 1
27731
- completion_after_subagent = run_keel(
27505
+ completion_without_evidence = run_keel(
27732
27506
  repo,
27733
27507
  "gate",
27734
27508
  "task-complete",
@@ -27740,12 +27514,12 @@ def validate_native_runtime_projection_scenario() -> int:
27740
27514
  env=env,
27741
27515
  )
27742
27516
  if (
27743
- completion_after_subagent.returncode != 3
27744
- or json.loads(completion_after_subagent.stdout).get("status")
27517
+ completion_without_evidence.returncode != 3
27518
+ or json.loads(completion_without_evidence.stdout).get("status")
27745
27519
  != "fail"
27746
27520
  ):
27747
27521
  report(
27748
- f"native-runtime-projection {target} subagent result satisfied "
27522
+ f"native-runtime-projection {target} a projection satisfied "
27749
27523
  "task-complete."
27750
27524
  )
27751
27525
  return 1
@@ -27984,9 +27758,6 @@ def validate_native_runtime_projection_scenario() -> int:
27984
27758
  return 0
27985
27759
 
27986
27760
 
27987
- NATIVE_GOAL_VERSION = "keel-native-goal/v1"
27988
-
27989
-
27990
27761
  def _goal_tasks_file(blocks: list[str]) -> str:
27991
27762
  return "# Tasks\n\n## Invalidates\n\n- None.\n\n" + "\n\n".join(blocks) + "\n"
27992
27763
 
@@ -28073,311 +27844,6 @@ def _goal_task_block(
28073
27844
  return "\n".join(lines)
28074
27845
 
28075
27846
 
28076
- def validate_native_goal_projection_scenario() -> int:
28077
- with tempfile.TemporaryDirectory(prefix="keel-native-goal-") as raw_tmp:
28078
- root = Path(raw_tmp)
28079
- goals: dict[str, dict] = {}
28080
- for target in ("codex", "claude"):
28081
- repo = root / target
28082
- repo.mkdir()
28083
- env = dict(os.environ)
28084
- if target == "codex":
28085
- env["CODEX_HOME"] = str(root / "codex-home")
28086
- if run_keel(repo, "--install", "--target", target, env=env).returncode != 0:
28087
- report("native-goal-projection %s install failed." % target)
28088
- return 1
28089
- write_text(
28090
- repo / "openspec/changes/sample-change/tasks.md",
28091
- _goal_tasks_file([_goal_task_block(strategy="vertical-tdd")]),
28092
- )
28093
- # A native "already complete" signal must never be treated as authority.
28094
- write_text(
28095
- repo / (".%s/transcripts/session.json" % target),
28096
- '{"complete": true}\n',
28097
- )
28098
- before = snapshot_files(repo)
28099
- projected = run_keel(
28100
- repo, "project", "goal",
28101
- "--target", target,
28102
- "--change", "sample-change",
28103
- "--task", "1.1",
28104
- "--json",
28105
- env=env,
28106
- )
28107
- if projected.returncode != 0:
28108
- report("native-goal-projection %s did not compile a ready goal." % target)
28109
- report((projected.stderr or projected.stdout).strip())
28110
- return 1
28111
- payload = json.loads(projected.stdout)
28112
- goal = payload.get("goal") or {}
28113
- gate = run_keel(
28114
- repo, "gate", "task-start",
28115
- "--change", "sample-change", "--task", "1.1", "--no-guard",
28116
- "--json",
28117
- env=env,
28118
- )
28119
- fingerprint = json.loads(gate.stdout).get("contract", {}).get("fingerprint", {})
28120
- if gate.returncode != 0 or not fingerprint:
28121
- report("native-goal-projection %s could not compile the gate fingerprint." % target)
28122
- return 1
28123
- if (
28124
- payload.get("version") != NATIVE_GOAL_VERSION
28125
- or payload.get("status") != "ready"
28126
- or payload.get("target") != target
28127
- or goal.get("version") != NATIVE_GOAL_VERSION
28128
- or goal.get("change") != "sample-change"
28129
- or goal.get("task") != "1.1"
28130
- or goal.get("fingerprint") != fingerprint
28131
- or goal.get("objective") != "Deliver one bounded behavior"
28132
- or goal.get("acceptance") != ["Observable result is proven by M1."]
28133
- or goal.get("commands") != ["M1: node test.js"]
28134
- or goal.get("verificationStrategy") != "vertical-tdd"
28135
- or goal.get("touch") != ["src/feature.js"]
28136
- or goal.get("ownership") != "current-agent-sole-writer"
28137
- or goal.get("terminalStates") != ["complete", "blocked", "paused"]
28138
- or not goal.get("stopBoundary")
28139
- or not goal.get("condition")
28140
- or goal.get("authorizationEvidence", {}).get("fingerprint")
28141
- != fingerprint.get("value")
28142
- ):
28143
- report("native-goal-projection %s payload was incomplete." % target)
28144
- report(json.dumps(payload, indent=2))
28145
- return 1
28146
- if "task-complete passes" not in goal.get("condition", ""):
28147
- report("native-goal-projection %s omitted the terminal completion condition." % target)
28148
- return 1
28149
- # The projection is disposable: no Keel-owned goal/cursor state is written.
28150
- if before != snapshot_files(repo):
28151
- report("native-goal-projection %s mutated durable state." % target)
28152
- return 1
28153
- if target == "claude" and goal.get("conditionLength", 0) > 4000:
28154
- report("native-goal-projection claude exceeded the 4,000-character budget.")
28155
- return 1
28156
- goals[target] = goal
28157
-
28158
- # Codex and Claude normalize to the same semantic fields.
28159
- def _semantic(goal: dict) -> dict:
28160
- copy = dict(goal)
28161
- copy.pop("target", None)
28162
- copy.pop("authorizationEvidence", None)
28163
- return copy
28164
-
28165
- if _semantic(goals["codex"]) != _semantic(goals["claude"]):
28166
- report("native-goal-projection codex and claude diverged on semantic fields.")
28167
- return 1
28168
-
28169
- # Rejections never write task, goal, or session state.
28170
- repo = root / "codex"
28171
- env = dict(os.environ)
28172
- env["CODEX_HOME"] = str(root / "codex-home")
28173
-
28174
- def _reject(args: list[str], label: str) -> bool:
28175
- before = snapshot_files(repo)
28176
- result = run_keel(repo, "project", "goal", *args, "--json", env=env)
28177
- if result.returncode == 0:
28178
- report("native-goal-projection accepted %s." % label)
28179
- return False
28180
- payload = json.loads(result.stdout)
28181
- if payload.get("status") != "blocked" or payload.get("goal") is not None:
28182
- report("native-goal-projection %s was not a clean block." % label)
28183
- return False
28184
- if before != snapshot_files(repo):
28185
- report("native-goal-projection %s mutated state." % label)
28186
- return False
28187
- return True
28188
-
28189
- # Unsupported OpenCode target.
28190
- if not _reject(
28191
- ["--target", "opencode", "--change", "sample-change", "--task", "1.1"],
28192
- "opencode target",
28193
- ):
28194
- return 1
28195
- # Missing explicit task selection.
28196
- if not _reject(
28197
- ["--target", "codex", "--change", "sample-change"],
28198
- "missing task selection",
28199
- ):
28200
- return 1
28201
- # Task-group / ambiguous selection (a section id, not one executable task).
28202
- if not _reject(
28203
- ["--target", "codex", "--change", "sample-change", "--task", "1"],
28204
- "task-group selection",
28205
- ):
28206
- return 1
28207
-
28208
- # A completed task never re-activates.
28209
- write_text(
28210
- repo / "openspec/changes/sample-change/tasks.md",
28211
- _goal_tasks_file(
28212
- [
28213
- _goal_task_block(task_id="1.1", checked=True, filled=True),
28214
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
28215
- ]
28216
- ),
28217
- )
28218
- if not _reject(
28219
- ["--target", "codex", "--change", "sample-change", "--task", "1.1"],
28220
- "completed task",
28221
- ):
28222
- return 1
28223
-
28224
- # An invalid task-start contract never compiles a goal.
28225
- write_text(
28226
- repo / "openspec/changes/sample-change/tasks.md",
28227
- _goal_tasks_file([_goal_task_block(strategy="teleport")]),
28228
- )
28229
- if not _reject(
28230
- ["--target", "codex", "--change", "sample-change", "--task", "1.1"],
28231
- "invalid task-start contract",
28232
- ):
28233
- return 1
28234
-
28235
- # A projection that could not fit executable authority on Claude is refused
28236
- # rather than silently truncated; Codex, without the limit, still compiles.
28237
- huge = ("Acceptance " + ("A" * 4200) + " is proven by M1.",)
28238
- oversized = _goal_tasks_file([_goal_task_block(acceptance=huge, strategy="vertical-tdd")])
28239
- write_text(repo / "openspec/changes/sample-change/tasks.md", oversized)
28240
- write_text((root / "claude") / "openspec/changes/sample-change/tasks.md", oversized)
28241
- claude_over = run_keel(
28242
- root / "claude", "project", "goal",
28243
- "--target", "claude",
28244
- "--change", "sample-change", "--task", "1.1", "--json",
28245
- env=dict(os.environ),
28246
- )
28247
- claude_payload = json.loads(claude_over.stdout)
28248
- if claude_over.returncode == 0 or claude_payload.get("status") != "blocked":
28249
- report("native-goal-projection claude accepted an oversized condition.")
28250
- return 1
28251
- if "4,000" not in " ".join(claude_payload.get("reasons", [])) and "4000" not in " ".join(
28252
- claude_payload.get("reasons", [])
28253
- ):
28254
- report("native-goal-projection claude blocked without citing the character budget.")
28255
- return 1
28256
- codex_over = run_keel(
28257
- repo, "project", "goal",
28258
- "--target", "codex",
28259
- "--change", "sample-change", "--task", "1.1", "--json",
28260
- env=env,
28261
- )
28262
- if codex_over.returncode != 0 or json.loads(codex_over.stdout).get("status") != "ready":
28263
- report("native-goal-projection codex rejected a valid oversized-for-claude condition.")
28264
- return 1
28265
-
28266
- report("native-goal-projection scenario passed.")
28267
- return 0
28268
-
28269
-
28270
- NATIVE_TASKS_VIEW_VERSION = "keel-native-tasks/v1"
28271
-
28272
-
28273
- def validate_native_tasks_view_scenario() -> int:
28274
- with tempfile.TemporaryDirectory(prefix="keel-native-tasks-") as raw_tmp:
28275
- repo = Path(raw_tmp) / "repo"
28276
- repo.mkdir()
28277
- write_text(
28278
- repo / "openspec/changes/sample-change/tasks.md",
28279
- _goal_tasks_file(
28280
- [
28281
- _goal_task_block(
28282
- task_id="1.1", checked=True, filled=True,
28283
- strategy="vertical-tdd",
28284
- ),
28285
- _goal_task_block(
28286
- task_id="1.2", title="Second bounded behavior",
28287
- strategy="vertical-tdd",
28288
- ),
28289
- ]
28290
- ),
28291
- )
28292
-
28293
- # E1: the view compiles the whole checklist without writing anything.
28294
- before = snapshot_files(repo)
28295
- compiled = run_keel(
28296
- repo, "project", "tasks",
28297
- "--target", "claude", "--change", "sample-change", "--json",
28298
- )
28299
- if compiled.returncode != 0:
28300
- report("native-tasks-view did not compile a ready view.")
28301
- report((compiled.stderr or compiled.stdout).strip())
28302
- return 1
28303
- payload = json.loads(compiled.stdout)
28304
- view = payload.get("view") or {}
28305
- gate = run_keel(
28306
- repo, "gate", "task-start",
28307
- "--change", "sample-change", "--task", "1.2", "--no-guard", "--json",
28308
- )
28309
- fingerprint = json.loads(gate.stdout).get("contract", {}).get("fingerprint", {})
28310
- if gate.returncode != 0 or not fingerprint:
28311
- report("native-tasks-view could not compile the gate fingerprint.")
28312
- return 1
28313
- if (
28314
- payload.get("version") != NATIVE_TASKS_VIEW_VERSION
28315
- or payload.get("status") != "ready"
28316
- or payload.get("target") != "claude"
28317
- or payload.get("source", {}).get("authority") != "OpenSpec"
28318
- or view.get("version") != NATIVE_TASKS_VIEW_VERSION
28319
- or view.get("change") != "sample-change"
28320
- or view.get("tasks") != [
28321
- {
28322
- "id": "1.1",
28323
- "title": "Deliver one bounded behavior",
28324
- "checked": True,
28325
- },
28326
- {
28327
- "id": "1.2",
28328
- "title": "Second bounded behavior",
28329
- "checked": False,
28330
- },
28331
- ]
28332
- or view.get("defaultTask") != "1.2"
28333
- or view.get("fingerprint") != fingerprint
28334
- or view.get("mirroring") != "current-agent-manual"
28335
- ):
28336
- report("native-tasks-view payload was incomplete.")
28337
- report(json.dumps(payload, indent=2))
28338
- return 1
28339
- if before != snapshot_files(repo):
28340
- report("native-tasks-view mutated durable state.")
28341
- return 1
28342
-
28343
- # Non-Claude targets are refused without writing anything.
28344
- for target in ("codex", "opencode"):
28345
- refused = run_keel(
28346
- repo, "project", "tasks",
28347
- "--target", target, "--change", "sample-change", "--json",
28348
- )
28349
- if refused.returncode == 0:
28350
- report("native-tasks-view accepted the %s target." % target)
28351
- return 1
28352
- refusal = json.loads(refused.stdout)
28353
- if refusal.get("status") != "blocked" or refusal.get("view") is not None:
28354
- report("native-tasks-view %s refusal was not a clean block." % target)
28355
- return 1
28356
- if before != snapshot_files(repo):
28357
- report("native-tasks-view %s refusal mutated state." % target)
28358
- return 1
28359
-
28360
- # The view projects a change checklist, never one task selection.
28361
- singled = run_keel(
28362
- repo, "project", "tasks",
28363
- "--target", "claude", "--change", "sample-change", "--task", "1.2",
28364
- )
28365
- if singled.returncode == 0:
28366
- report("native-tasks-view accepted a --task selection.")
28367
- return 1
28368
-
28369
- readme = (ROOT / "README.zh-CN.md").read_text(encoding="utf-8")
28370
- if "keel project tasks" not in readme:
28371
- report("native-tasks-view: README lacks the tasks-view command.")
28372
- return 1
28373
- if "native-tasks-view" not in {name for name, _ in SCENARIOS}:
28374
- report("native-tasks-view: the scenario registry does not include it.")
28375
- return 1
28376
-
28377
- report("native-tasks-view scenario passed.")
28378
- return 0
28379
-
28380
-
28381
27847
  def validate_verification_layering_docs_scenario() -> int:
28382
27848
  en = (ROOT / "README.md").read_text(encoding="utf-8")
28383
27849
  for needle in (
@@ -29524,158 +28990,6 @@ def validate_triage_admits_from_the_repository_scenario() -> int:
29524
28990
  return 0
29525
28991
 
29526
28992
 
29527
- def validate_delegation_declaration_scenario() -> int:
29528
- """Who runs a task is a declaration, never an inference from its size.
29529
-
29530
- The tier names a capability the work requires. It is never derived from
29531
- Touch size, diff size, or apparent difficulty, because that is the agent's
29532
- guess about difficulty — the judgement 5.7.0 already refused for triage.
29533
- """
29534
-
29535
- def declare(repo: Path, body: str | None) -> None:
29536
- (repo / "keel").mkdir(parents=True, exist_ok=True)
29537
- text = "fast_check: echo check\n"
29538
- if body is not None:
29539
- text += body
29540
- (repo / "keel" / "config.yaml").write_text(text, encoding="utf-8")
29541
-
29542
- # Two distinct failures live here — the reader threw, or it returned
29543
- # something that is not JSON — and they send a reader to different places.
29544
- # Collapsing both into one `None` would report whichever message the caller
29545
- # happened to write, which is the defect the review checklist names.
29546
- def resolve(repo: Path, label: str) -> dict | None:
29547
- probe = subprocess.run(
29548
- [
29549
- "node", "-e",
29550
- "const {readDelegationPolicy}=require(process.argv[1]);"
29551
- "process.stdout.write("
29552
- "JSON.stringify(readDelegationPolicy(process.argv[2])));",
29553
- str(ROOT / "src/core/config.js"),
29554
- str(repo),
29555
- ],
29556
- text=True, encoding="utf-8", capture_output=True, check=False,
29557
- )
29558
- if probe.returncode != 0:
29559
- report(f"delegation: reading the {label} repo threw.")
29560
- report((probe.stderr or probe.stdout).strip())
29561
- return None
29562
- try:
29563
- return json.loads(probe.stdout)
29564
- except json.JSONDecodeError:
29565
- report(
29566
- f"delegation: the {label} repo returned non-JSON: "
29567
- f"{probe.stdout!r}"
29568
- )
29569
- return None
29570
-
29571
- with tempfile.TemporaryDirectory(prefix="keel-delegation-") as raw_tmp:
29572
- root = Path(raw_tmp)
29573
-
29574
- # M1 — a declared tier resolves; absence in any of its three shapes
29575
- # leaves delegation unauthorized.
29576
- declared = root / "declared"
29577
- declared.mkdir()
29578
- declare(declared, "delegation:\n tier: standard\n")
29579
- resolved = resolve(declared, "declared")
29580
- if resolved is None:
29581
- return 1
29582
- if resolved.get("tier") != "standard":
29583
- report(f"delegation: a declared tier did not resolve: {resolved}")
29584
- return 1
29585
- if resolved.get("declared") is not True:
29586
- report(f"delegation: a declared block did not report declared: {resolved}")
29587
- return 1
29588
-
29589
- for label, body in (
29590
- ("absent", None),
29591
- ("empty", "delegation:\n"),
29592
- ("other-keys-only", "triage:\n - auto\n"),
29593
- ):
29594
- silent = root / f"silent-{label}"
29595
- silent.mkdir()
29596
- declare(silent, body)
29597
- quiet = resolve(silent, label)
29598
- if quiet is None:
29599
- return 1
29600
- if quiet.get("tier") is not None:
29601
- report(f"delegation: the {label} repo resolved a tier: {quiet}")
29602
- return 1
29603
- if quiet.get("declared") is not False:
29604
- report(f"delegation: the {label} repo reported a declaration: {quiet}")
29605
- return 1
29606
-
29607
- # M2 — an unrecognized tier is reported by name, carries the accepted
29608
- # set so a caller can name it too, and authorizes nothing.
29609
- typo = root / "typo"
29610
- typo.mkdir()
29611
- declare(typo, "delegation:\n tier: turbo\n")
29612
- rejected = resolve(typo, "unrecognized-tier")
29613
- if rejected is None:
29614
- return 1
29615
- if rejected.get("tier") is not None:
29616
- report(f"delegation: an unrecognized tier still resolved: {rejected}")
29617
- return 1
29618
- if "turbo" not in (rejected.get("unknown") or []):
29619
- report(f"delegation: the offending entry is not named: {rejected}")
29620
- return 1
29621
- accepted = rejected.get("accepted") or []
29622
- for name in ("routine", "standard", "deep"):
29623
- if name not in accepted:
29624
- report(f"delegation: the accepted tier {name} is not reported: {rejected}")
29625
- return 1
29626
- # The vocabulary is closed, so a name outside it must not appear.
29627
- if len(accepted) != 3:
29628
- report(f"delegation: the accepted set is not the closed three: {rejected}")
29629
- return 1
29630
-
29631
- # M3 — `authorize:` is not a delegation channel. Listing `delegate`
29632
- # there is reported against that block's own closed set, and delegation
29633
- # stays unauthorized because it is a different declaration entirely.
29634
- misplaced = root / "misplaced"
29635
- misplaced.mkdir()
29636
- declare(misplaced, "authorize:\n - commit\n - delegate\n")
29637
- standing = subprocess.run(
29638
- [
29639
- "node", "-e",
29640
- "const c=require(process.argv[1]);"
29641
- "process.stdout.write(JSON.stringify({"
29642
- "standing:c.readStandingAuthorization(process.argv[2]),"
29643
- "delegation:c.readDelegationPolicy(process.argv[2]),"
29644
- "actions:c.STANDING_AUTHORIZATION_ACTIONS}));",
29645
- str(ROOT / "src/core/config.js"),
29646
- str(misplaced),
29647
- ],
29648
- text=True, encoding="utf-8", capture_output=True, check=False,
29649
- )
29650
- if standing.returncode != 0:
29651
- report("delegation: the misplaced-entry repo could not be read.")
29652
- report((standing.stderr or standing.stdout).strip())
29653
- return 1
29654
- try:
29655
- both = json.loads(standing.stdout)
29656
- except json.JSONDecodeError:
29657
- report(f"delegation: the misplaced-entry probe returned no JSON: {standing.stdout!r}")
29658
- return 1
29659
- if "delegate" not in (both["standing"].get("unknown") or []):
29660
- report(f"delegation: `delegate` was not reported by authorize: {both['standing']}")
29661
- return 1
29662
- if both["standing"].get("declared"):
29663
- report(f"delegation: a rejected authorize block still granted actions: {both['standing']}")
29664
- return 1
29665
- if "delegate" in both["actions"]:
29666
- report("delegation: `delegate` leaked into the authorize vocabulary.")
29667
- return 1
29668
- if both["delegation"].get("declared") is not False:
29669
- report(f"delegation: authorize granted a delegation: {both['delegation']}")
29670
- return 1
29671
- if both["delegation"].get("tier") is not None:
29672
- report(f"delegation: authorize resolved a tier: {both['delegation']}")
29673
- return 1
29674
-
29675
- report("delegation-declaration scenario passed.")
29676
- return 0
29677
-
29678
-
29679
28993
  def validate_delegation_resident_text_scenario() -> int:
29680
28994
  """The resident protocol, the config header, and both templates agree.
29681
28995
 
@@ -29686,14 +29000,14 @@ def validate_delegation_resident_text_scenario() -> int:
29686
29000
  def flat(path: Path) -> str:
29687
29001
  return re.sub(r"\s+", " ", path.read_text(encoding="utf-8"))
29688
29002
 
29689
- # M1 — the resident protocol carries the condition and the model limit.
29003
+ # M1 — the resident protocol carries the subagent rule and the model limit.
29004
+ # Since #414 a subagent is the model's choice and is treated as the main
29005
+ # agent is; the gates and the Touch guard are what bind it.
29690
29006
  agents = ROOT / "AGENTS.md"
29691
29007
  text = flat(agents)
29692
29008
  for needle in (
29693
- "implementation delegates use the selected task write authority inside",
29694
- "a guard manifest is active",
29695
- "re-runs each",
29696
- "check itself before recording Evidence",
29009
+ "is the model's choice and is treated as the main agent is",
29010
+ "the evidence rules apply to whoever runs a step",
29697
29011
  "never a model name",
29698
29012
  "declared rather than inferred from a task's size",
29699
29013
  ):
@@ -29701,18 +29015,19 @@ def validate_delegation_resident_text_scenario() -> int:
29701
29015
  report(f"delegation-resident-text: AGENTS.md omits: {needle}")
29702
29016
  return 1
29703
29017
 
29704
- # M1 — the consumer bootstrap deliberately does NOT carry the delegation
29705
- # clause. Its block has a byte budget (BOOTSTRAP_BLOCK_BYTE_BUDGET) with
29706
- # little headroom, and delegation is inert until declared, so an installing
29707
- # repository that declares nothing is fully served by the sentence already
29708
- # there. What the check enforces is that the sentence stays true by default,
29709
- # and that the budget is not quietly spent later — the budget moved once, in
29710
- # 5.63.0 for the routing rule (#131), with the argument recorded at the
29711
- # constant; a raise with no reason beside it is the drift this guards.
29018
+ # M1 — the consumer bootstrap carries the subagent sentence, not the
29019
+ # delegation clause. Its block has a byte budget (BOOTSTRAP_BLOCK_BYTE_BUDGET)
29020
+ # with little headroom, and delegation is inert until declared, so an
29021
+ # installing repository that declares nothing is fully served by the
29022
+ # sentence already there. What the check enforces is that the sentence stays
29023
+ # true by default, and that the budget is not quietly spent later — the
29024
+ # budget moved once, in 5.63.0 for the routing rule (#131), with the argument
29025
+ # recorded at the constant; a raise with no reason beside it is the drift
29026
+ # this guards.
29712
29027
  bootstrap = ROOT / "assets/bootstrap/AGENTS.md"
29713
29028
  boot = flat(bootstrap)
29714
- if re.sub(r"\s+", " ", "One agent owns decisions") not in boot:
29715
- report("delegation-resident-text: the bootstrap lost its single-writer default.")
29029
+ if re.sub(r"\s+", " ", "is the model's choice and is treated as the main agent is") not in boot:
29030
+ report("delegation-resident-text: the bootstrap lost its subagent sentence.")
29716
29031
  return 1
29717
29032
  block = bootstrap.read_text(encoding="utf-8")
29718
29033
  body = block.split("<!-- keel:start", 1)[1].split("<!-- keel:end -->", 1)[0]
@@ -29749,9 +29064,6 @@ def validate_delegation_resident_text_scenario() -> int:
29749
29064
  if header_problem:
29750
29065
  report(f"delegation-resident-text: {header_problem}")
29751
29066
  return 1
29752
- if "delegation" not in cfg:
29753
- report("delegation-resident-text: the config header does not document delegation.")
29754
- return 1
29755
29067
 
29756
29068
  # M2 — both task templates state the new default, and the source and its
29757
29069
  # installed copy stay byte-identical.
@@ -29759,14 +29071,13 @@ def validate_delegation_resident_text_scenario() -> int:
29759
29071
  installed = ROOT / "openspec/schemas/keel-spec-driven/templates/tasks.md"
29760
29072
  for path in (source, installed):
29761
29073
  body = flat(path)
29762
- # The helper clause stays true and is deliberately not removed — a
29763
- # helper is still read-only. What was wrong was the sentence stopping
29764
- # there, so the assertion is that it now continues.
29765
- if re.sub(r"\s+", " ", "helpers stay read-only/evidence-only") not in body:
29766
- report(f"delegation-resident-text: {path.relative_to(ROOT)} dropped the helper default.")
29074
+ # Since #414 the template states the subagent sentence and the default
29075
+ # continuation, and no longer limits helpers or delegates.
29076
+ if re.sub(r"\s+", " ", "subagent is the model's choice, treated as the main agent is") not in body:
29077
+ report(f"delegation-resident-text: {path.relative_to(ROOT)} does not state the subagent default.")
29767
29078
  return 1
29768
- if re.sub(r"\s+", " ", "matching active guard") not in body:
29769
- report(f"delegation-resident-text: {path.relative_to(ROOT)} does not state the implementation guard boundary.")
29079
+ if "cross-task continuation stay unauthorized" in body:
29080
+ report(f"delegation-resident-text: {path.relative_to(ROOT)} still says continuing needs authorization.")
29770
29081
  return 1
29771
29082
  if source.read_bytes() != installed.read_bytes():
29772
29083
  report("delegation-resident-text: the template source and its installed copy diverged.")
@@ -29796,16 +29107,13 @@ def validate_delegation_overlay_scenario() -> int:
29796
29107
  report(f"delegation-overlay: missing generated surface {path.relative_to(ROOT)}")
29797
29108
  return 1
29798
29109
 
29799
- # M1 — the gate states the delegate's condition, its boundary, and what
29800
- # its results are worth. Asserted on every generated copy, because the
29801
- # overlay is what a subagent on that surface actually reads.
29110
+ # M1 — the surface says what binds a subagent and nothing else (#414): it
29111
+ # is the model's choice and is treated as the main agent is. Asserted on
29112
+ # every generated copy, because the overlay is what a subagent on that
29113
+ # surface actually reads.
29802
29114
  needles = (
29803
- "using existing task write authority",
29804
- "a guard manifest is active",
29805
- "only inside `Touch`",
29806
- "re-runs each `M<n>` check itself before recording Evidence",
29807
- "Delegation is refused with no active guard manifest",
29808
- "may mark tasks complete",
29115
+ "A subagent is the model's choice and is treated as the main agent is",
29116
+ "the `Touch` write guard, and the evidence rules apply to whoever runs a step",
29809
29117
  )
29810
29118
  for path in generated:
29811
29119
  text = re.sub(r"\s+", " ", path.read_text(encoding="utf-8"))
@@ -29822,6 +29130,8 @@ def validate_delegation_overlay_scenario() -> int:
29822
29130
  for stale in (
29823
29131
  "Target-native subagents return report/evidence only; the current agent reviews the output before acting.",
29824
29132
  "Target-native subagents return report/evidence only; they cannot mark tasks complete",
29133
+ "Delegation is refused with no active guard manifest",
29134
+ "re-runs each `M<n>` check itself before recording Evidence",
29825
29135
  ):
29826
29136
  if re.sub(r"\s+", " ", stale) in text:
29827
29137
  report(f"delegation-overlay: {path.relative_to(ROOT)} still carries an unconditional sentence: {stale[:60]}")
@@ -29858,128 +29168,6 @@ def validate_delegation_overlay_scenario() -> int:
29858
29168
  return 0
29859
29169
 
29860
29170
 
29861
- def validate_delegation_never_weakens_scenario() -> int:
29862
- """Declaring who runs a task changes nothing about proving it was done.
29863
-
29864
- Same shape as the standing-authorization and precedent inertness
29865
- scenarios, and for the same reason: every check passes when two
29866
- repositories agree, so a declaration that silently failed to load would
29867
- make each comparison trivially true. The positive control asserts the
29868
- difference exists before asserting it is inert.
29869
- """
29870
-
29871
- complete_task = (
29872
- "- [ ] 1.1 Behavior\n"
29873
- " - Covers:\n"
29874
- " - E1: public behavior\n"
29875
- " - Touch:\n"
29876
- " - src/feature.js\n"
29877
- " - Verify:\n"
29878
- " - Strategy: evidence-first\n"
29879
- " - Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
29880
- " - M1: node test.js proves the public behavior\n"
29881
- " - Evidence:\n"
29882
- " - Contract: pending\n"
29883
- " - M1: node test.js printed ok\n"
29884
- " - Review:\n"
29885
- " - Status: pass\n"
29886
- " - Acceptance check: reviewed\n"
29887
- " - Scope check: reviewed\n"
29888
- " - Findings: none\n"
29889
- " - Blocker: none\n"
29890
- )
29891
- missing_evidence_task = complete_task.replace(
29892
- " - M1: node test.js printed ok\n", " - M1: pending\n"
29893
- )
29894
-
29895
- def gate(repo: Path, stage: str) -> dict | None:
29896
- result = run_keel(
29897
- repo, "gate", stage, "--change", "demo", "--task", "1.1",
29898
- "--json", "--no-guard",
29899
- )
29900
- try:
29901
- payload = json.loads(result.stdout)
29902
- except json.JSONDecodeError:
29903
- report(f"delegation-never-weakens: {stage} returned no JSON: {result.stdout!r}")
29904
- return None
29905
- # The fingerprint legitimately differs between the two repositories,
29906
- # because a declared delegation is part of the compiled capsule. What
29907
- # must not differ is the verdict or the problems.
29908
- return {
29909
- "status": payload.get("status"),
29910
- "problems": [p.get("code") for p in (payload.get("problems") or [])],
29911
- }
29912
-
29913
- def build(root: Path, name: str, config: str, task: str) -> Path:
29914
- repo = root / name
29915
- repo.mkdir()
29916
- write_gate_fixture(repo, task)
29917
- write_authorize_config(repo, config)
29918
- return repo
29919
-
29920
- declaring = "fast_check: echo c\ndelegation:\n tier: standard\n"
29921
- silent = "fast_check: echo c\n"
29922
-
29923
- with tempfile.TemporaryDirectory(prefix="keel-delinert-") as raw_tmp:
29924
- root = Path(raw_tmp)
29925
-
29926
- # Positive control — the declaration reaches the capsule at all. If it
29927
- # did not, every comparison below would pass for the wrong reason.
29928
- control = build(root, "control", declaring, complete_task)
29929
- probe = run_keel(
29930
- control, "gate", "task-start", "--change", "demo", "--task", "1.1",
29931
- "--json", "--no-guard",
29932
- )
29933
- capsule = json.loads(probe.stdout)["contract"]["capsule"]
29934
- if (capsule.get("delegation") or {}).get("tier") != "standard":
29935
- report(
29936
- "delegation-never-weakens: the declaration never reached the "
29937
- f"capsule, so inertness would be trivially true: {capsule.get('delegation')}"
29938
- )
29939
- return 1
29940
-
29941
- # M1 — identical verdicts and problem sets, passing and failing alike.
29942
- for label, task in (("passing", complete_task), ("failing", missing_evidence_task)):
29943
- loud = build(root, f"loud-{label}", declaring, task)
29944
- quiet = build(root, f"quiet-{label}", silent, task)
29945
- for stage in ("task-start", "task-complete"):
29946
- a = gate(loud, stage)
29947
- b = gate(quiet, stage)
29948
- if a is None or b is None:
29949
- return 1
29950
- if a != b:
29951
- report(
29952
- f"delegation-never-weakens: {stage} differed on the {label} "
29953
- f"task: declaring={a} silent={b}"
29954
- )
29955
- return 1
29956
- # And the failing case must actually fail, or "identical" is a
29957
- # statement about two passes and proves nothing about refusals.
29958
- failed = gate(loud, "task-complete")
29959
- if label == "failing" and failed and failed["status"] == "pass":
29960
- report("delegation-never-weakens: the failing fixture passed, so the comparison is empty.")
29961
- return 1
29962
-
29963
- # M2 — context selection and triage are unchanged.
29964
- for stage_args, key in ((("context",), "nextAction"), (("triage", "--labels", "auto"), "status")):
29965
- loud = build(root, f"loud-{key}", declaring + "triage:\n - auto\n", complete_task)
29966
- quiet = build(root, f"quiet-{key}", silent + "triage:\n - auto\n", complete_task)
29967
- outs = []
29968
- for repo in (loud, quiet):
29969
- result = run_keel(repo, *stage_args, "--json")
29970
- try:
29971
- outs.append(json.loads(result.stdout).get(key))
29972
- except json.JSONDecodeError:
29973
- report(f"delegation-never-weakens: {stage_args[0]} returned no JSON: {result.stdout!r}")
29974
- return 1
29975
- if outs[0] != outs[1]:
29976
- report(f"delegation-never-weakens: {stage_args[0]} differed: {outs[0]} != {outs[1]}")
29977
- return 1
29978
-
29979
- report("delegation-never-weakens scenario passed.")
29980
- return 0
29981
-
29982
-
29983
29171
  def validate_delegation_guard_binds_scenario() -> int:
29984
29172
  """The guard binds a delegated writer identically, and always did.
29985
29173
 
@@ -30111,476 +29299,6 @@ def validate_delegation_guard_binds_scenario() -> int:
30111
29299
  return 0
30112
29300
 
30113
29301
 
30114
- def validate_delegation_goal_budget_scenario() -> int:
30115
- """The delegation fields live inside the activation budget, not beside it.
30116
-
30117
- A field that never reaches the condition cannot overflow it, so asserting
30118
- the refusal means first asserting the fields are actually carried.
30119
- """
30120
-
30121
- def goal(repo: Path) -> dict | None:
30122
- result = run_keel(
30123
- repo, "project", "goal", "--target", "claude",
30124
- "--change", "demo", "--task", "1.1", "--json",
30125
- )
30126
- try:
30127
- payload = json.loads(result.stdout)
30128
- except json.JSONDecodeError:
30129
- report(f"delegation-goal-budget: goal returned no JSON: {result.stdout!r}")
30130
- report((result.stderr or "").strip())
30131
- return None
30132
- # Two shapes share this command. A compiled goal is nested under
30133
- # `goal`; a refusal carries `goal: null` with the reason on the
30134
- # envelope. Reading only one of them would report a refusal as a
30135
- # missing field, which is a different problem in a different place.
30136
- nested = payload.get("goal") or {}
30137
- return {
30138
- **nested,
30139
- "status": payload.get("status"),
30140
- "reasons": payload.get("reasons") or [],
30141
- }
30142
-
30143
- def task(padding: str = "") -> str:
30144
- return (
30145
- "- [ ] 1.1 Behavior\n"
30146
- " - Covers:\n"
30147
- " - E1: public behavior\n"
30148
- " - Touch:\n"
30149
- " - src/feature.js\n"
30150
- + padding
30151
- + " - Verify:\n"
30152
- " - Strategy: evidence-first\n"
30153
- " - Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
30154
- " - M1: node test.js proves the public behavior\n"
30155
- " - Evidence:\n"
30156
- " - Contract: pending\n"
30157
- " - M1: pending\n"
30158
- " - Review:\n"
30159
- " - Status: pending\n"
30160
- " - Acceptance check: pending\n"
30161
- " - Scope check: pending\n"
30162
- " - Findings: pending\n"
30163
- " - Blocker: none\n"
30164
- )
30165
-
30166
- with tempfile.TemporaryDirectory(prefix="keel-delbudget-") as raw_tmp:
30167
- root = Path(raw_tmp)
30168
-
30169
- # M1 — the declared tier reaches the compiled condition.
30170
- fits = root / "fits"
30171
- fits.mkdir()
30172
- write_gate_fixture(fits, task())
30173
- write_authorize_config(fits, "fast_check: echo c\ndelegation:\n tier: routine\n")
30174
- compiled = goal(fits)
30175
- if compiled is None:
30176
- return 1
30177
- if compiled.get("status") != "ready":
30178
- report(f"delegation-goal-budget: a fitting goal did not compile: {compiled.get('reasons')}")
30179
- return 1
30180
- condition = compiled.get("condition") or ""
30181
- if "routine" not in condition:
30182
- report("delegation-goal-budget: the declared tier is not in the goal condition.")
30183
- return 1
30184
-
30185
- # M1 — pushed past the budget, activation refuses and names it. The
30186
- # padding is Touch paths, so the overflow comes from real capsule
30187
- # content rather than from a string invented for the test.
30188
- over = root / "over"
30189
- over.mkdir()
30190
- padding = "".join(f" - src/generated/module_{i:03d}_long_enough_to_count.js\n" for i in range(90))
30191
- write_gate_fixture(over, task(padding))
30192
- write_authorize_config(over, "fast_check: echo c\ndelegation:\n tier: routine\n")
30193
- refused = goal(over)
30194
- if refused is None:
30195
- return 1
30196
- if refused.get("status") != "blocked":
30197
- length = len(refused.get("condition") or "")
30198
- report(f"delegation-goal-budget: an over-budget goal was not refused (condition {length} chars).")
30199
- return 1
30200
- reason = " ".join(refused.get("reasons") or [])
30201
- if "4000" not in reason:
30202
- report(f"delegation-goal-budget: the refusal does not name the budget: {reason}")
30203
- return 1
30204
- # Nothing is dropped to make it fit: the refusal is the whole response,
30205
- # and no truncated condition is offered in its place.
30206
- if refused.get("condition"):
30207
- report("delegation-goal-budget: a condition was still offered alongside the refusal.")
30208
- return 1
30209
-
30210
- report("delegation-goal-budget scenario passed.")
30211
- return 0
30212
-
30213
-
30214
- def validate_delegation_sole_authority_scenario() -> int:
30215
- """The invariant is restated, not removed.
30216
-
30217
- Its purpose was never that one process performs the writes — it was that
30218
- one party is answerable for them. A delegate writes inside a boundary that
30219
- authority already defined, and acquires none of the owned decisions.
30220
- """
30221
-
30222
- canonical = ROOT / "src/skills/keel-run-single-task-goal/SKILL.md"
30223
- packaged = ROOT / "plugins/keel/skills/keel-run-single-task-goal/SKILL.md"
30224
- claude = ROOT / "plugins/keel/agents/keel-single-task-goal-claude.md"
30225
- codex = ROOT / "plugins/keel/agents/keel-single-task-goal-codex.md"
30226
- goal = ROOT / "src/core/goal.js"
30227
- for path in (canonical, packaged, claude, codex, goal):
30228
- if not path.exists():
30229
- report(f"delegation-sole-authority: missing {path.relative_to(ROOT)}")
30230
- return 1
30231
-
30232
- def flat(path: Path) -> str:
30233
- return re.sub(r"\s+", " ", path.read_text(encoding="utf-8"))
30234
-
30235
- # M1 — the restatement, in the canonical skill and in the goal projection
30236
- # the adapters actually read.
30237
- for path in (canonical, goal):
30238
- text = flat(path)
30239
- if re.sub(r"\s+", " ", "sole holder of write authority") not in text:
30240
- report(f"delegation-sole-authority: {path.name} does not restate the invariant.")
30241
- return 1
30242
- if re.sub(r"\s+", " ", "re-runs each") not in text:
30243
- report(f"delegation-sole-authority: {path.name} does not say the current agent re-runs the checks.")
30244
- return 1
30245
-
30246
- # M1 — the stop list refuses an undeclared delegation and no longer
30247
- # refuses a declared one outright.
30248
- skill_text = flat(canonical)
30249
- if re.sub(r"\s+", " ", "matching active guard") not in skill_text:
30250
- report("delegation-sole-authority: the stop list omits guarded task authority.")
30251
- return 1
30252
- if re.sub(r"\s+", " ", "any request to delegate implementation to another agent") in skill_text:
30253
- report("delegation-sole-authority: the stop list still refuses every delegation outright.")
30254
- return 1
30255
-
30256
- # M1 — both adapters carry it, and neither still advertises read-only
30257
- # helpers as the whole of what a subagent may do.
30258
- for path in (claude, codex):
30259
- text = flat(path)
30260
- if re.sub(r"\s+", " ", "write authority") not in text:
30261
- report(f"delegation-sole-authority: {path.name} does not carry the restatement.")
30262
- return 1
30263
- if re.sub(r"\s+", " ", "read-only subagent helpers only") in text:
30264
- report(f"delegation-sole-authority: {path.name} still says read-only helpers only.")
30265
- return 1
30266
- if "matching active guard" not in text or "host policy" not in text.lower():
30267
- report(f"delegation-sole-authority: {path.name} omits guard or host boundary.")
30268
- return 1
30269
-
30270
- # M2 — the canonical source and its distribution copy stay byte-identical.
30271
- if canonical.read_bytes() != packaged.read_bytes():
30272
- report("delegation-sole-authority: the canonical and packaged skills diverged.")
30273
- return 1
30274
-
30275
- # M3 — a native evaluator declaring success still completes nothing.
30276
- for path in (canonical, claude, codex):
30277
- text = flat(path)
30278
- if "never" not in text or "complete" not in text:
30279
- report(f"delegation-sole-authority: {path.name} lost its evaluator-success rule.")
30280
- return 1
30281
-
30282
- report("delegation-sole-authority scenario passed.")
30283
- return 0
30284
-
30285
-
30286
- def validate_model_chosen_subagents_scenario() -> int:
30287
- label = "model-chosen-subagents:"
30288
- with tempfile.TemporaryDirectory(prefix="keel-model-subagents-") as raw:
30289
- repo = Path(raw)
30290
- write_gate_fixture(repo, standing_authorization_task())
30291
- def project(*extra: str) -> dict:
30292
- result = run_keel(repo, "project", "--target", "codex",
30293
- "--event", "subagent-start", "--change", "demo", "--task", "1.1", "--json", *extra)
30294
- return json.loads(result.stdout)
30295
- helper = project()
30296
- if helper.get("status") != "ready":
30297
- report(f"{label} ordinary helper still requires activation: {helper.get('reasons')}")
30298
- return 1
30299
- if helper["projection"].get("subagentMode") != "helper" or helper["projection"].get("delegation"):
30300
- report(f"{label} helper posture grants delegation")
30301
- return 1
30302
- write_authorize_config(repo, "delegation:\n tier: turbo\n")
30303
- if project().get("status") != "ready":
30304
- report(f"{label} helper depends on implementation tier metadata")
30305
- return 1
30306
- write_authorize_config(repo, "fast_check: echo ok\n")
30307
- if project("--subagent-mode", "implementation").get("status") == "ready":
30308
- report(f"{label} unguarded implementation allowed")
30309
- return 1
30310
- started = run_keel(repo, "gate", "task-start", "--change", "demo", "--task", "1.1", "--record", "--json")
30311
- if json.loads(started.stdout).get("status") != "pass":
30312
- report(f"{label} valid task did not start: {started.stdout}")
30313
- return 1
30314
- delegate = project("--subagent-mode", "implementation")
30315
- if delegate.get("status") != "ready":
30316
- report(f"{label} guarded implementation requires tier: {delegate.get('reasons')}")
30317
- return 1
30318
- brief = delegate["projection"]
30319
- if brief.get("delegation", {}).get("writeBoundary") != ["src/feature.js"] or brief["delegation"].get("tier") is not None:
30320
- report(f"{label} delegate boundary or absent tier incorrect")
30321
- return 1
30322
- 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"]):
30323
- report(f"{label} ownership prohibitions lost")
30324
- return 1
30325
- manifest_path = repo / "keel/guard.json"
30326
- saved = manifest_path.read_bytes()
30327
- manifest_path.write_text("{}")
30328
- if project().get("status") != "ready":
30329
- report(f"{label} malformed implementation guard blocked read-only help")
30330
- return 1
30331
- if project("--subagent-mode", "implementation").get("status") == "ready":
30332
- report(f"{label} malformed guard allowed implementation")
30333
- return 1
30334
- manifest_path.write_bytes(saved)
30335
- manifest = json.loads(saved)
30336
- manifest["fingerprint"]["value"] = "0" * 64
30337
- manifest_path.write_text(json.dumps(manifest))
30338
- if project("--subagent-mode", "implementation").get("status") == "ready":
30339
- report(f"{label} drifted guard allowed implementation")
30340
- return 1
30341
- manifest_path.write_bytes(saved)
30342
- manifest = json.loads(saved)
30343
- manifest["touch"].append("src/outside.js")
30344
- manifest_path.write_text(json.dumps(manifest))
30345
- if project("--subagent-mode", "implementation").get("status") == "ready":
30346
- report(f"{label} widened manifest Touch allowed implementation")
30347
- return 1
30348
- manifest = json.loads(saved)
30349
- manifest["task"] = "9.9"
30350
- manifest_path.write_text(json.dumps(manifest))
30351
- if project("--subagent-mode", "implementation").get("status") == "ready":
30352
- report(f"{label} different task guard allowed implementation")
30353
- return 1
30354
- manifest_path.write_bytes(saved)
30355
- shutil.copytree(repo / "openspec/changes/demo", repo / "openspec/changes/other")
30356
- other_start = run_keel(repo, "gate", "task-start", "--change", "other", "--task", "1.1", "--record", "--json")
30357
- if json.loads(other_start.stdout).get("status") != "pass":
30358
- report(f"{label} other task guard fixture did not start")
30359
- return 1
30360
- mismatch = project("--subagent-mode", "implementation")
30361
- if mismatch.get("status") == "ready":
30362
- report(f"{label} active guard for another owner allowed implementation")
30363
- return 1
30364
- if "matching" not in " ".join(mismatch.get("reasons", [])):
30365
- report(f"{label} other-owner refusal did not name guard mismatch")
30366
- return 1
30367
- manifest_path.write_bytes(saved)
30368
- task_path = repo / "openspec/changes/demo/tasks.md"
30369
- task_before = task_path.read_text()
30370
- task_path.write_text(task_before.replace("src/feature.js", "src/other.js"))
30371
- if project("--subagent-mode", "implementation").get("status") == "ready":
30372
- report(f"{label} authority drift allowed implementation")
30373
- return 1
30374
- task_path.write_text(task_before)
30375
- returned = run_keel(repo, "project", "--event", "subagent-stop", "--subagent-mode", "implementation", "--native-complete", "--change", "demo", "--task", "1.1", "--json")
30376
- returned_payload = json.loads(returned.stdout)
30377
- if task_path.read_text() != task_before:
30378
- report(f"{label} delegate completion modified task authority or records")
30379
- return 1
30380
- if returned_payload.get("projection", {}).get("returnAuthority") != "report-and-evidence-only":
30381
- report(f"{label} delegate return did not remain evidence-only")
30382
- return 1
30383
- goal = run_keel(repo, "project", "--event", "goal", "--change", "demo", "--task", "1.1", "--json")
30384
- if json.loads(goal.stdout).get("status") != "blocked":
30385
- report(f"{label} goal activation became implicit")
30386
- return 1
30387
- configured = repo / "configured"
30388
- configured.mkdir()
30389
- write_gate_fixture(configured, standing_authorization_task())
30390
- write_authorize_config(configured, "delegation:\n tier: deep\n")
30391
- explicit = run_keel(configured, "project", "--event", "subagent-start", "--authorize", "subagent", "--subagent-mode", "helper", "--change", "demo", "--task", "1.1", "--json")
30392
- payload = json.loads(explicit.stdout)
30393
- if payload.get("status") != "ready" or payload["projection"].get("delegation"):
30394
- report(f"{label} explicit helper became writer due to tier metadata")
30395
- return 1
30396
- for name,task,config in [
30397
- ("bad-task-tier", standing_authorization_task().replace(" - Covers:", " - Delegation: turbo\n - Covers:"), ""),
30398
- ("bad-config-tier", standing_authorization_task(), "delegation:\n tier: turbo\n"),
30399
- ("plan-first", standing_authorization_task().replace(" - Covers:", " - Mode: plan-first\n - Covers:"), ""),
30400
- ("diagnose-only", standing_authorization_task().replace(" - Covers:", " - Mode: diagnose-only\n - Covers:").replace(" - src/feature.js", " - none"), ""),
30401
- ("repo-action", standing_authorization_task().replace(" - Covers:", " - Mode: repo-action\n - Covers:").replace(" - src/feature.js", " - none"), ""),
30402
- ]:
30403
- other = repo / name
30404
- other.mkdir()
30405
- write_gate_fixture(other, task)
30406
- write_authorize_config(other, config)
30407
- result = run_keel(other, "project", "--event", "subagent-start", "--change", "demo", "--task", "1.1", "--json")
30408
- if json.loads(result.stdout).get("status") != "ready":
30409
- report(f"{label} read-only helper refused for {name}: {result.stdout}")
30410
- return 1
30411
- result = run_keel(other, "project", "--event", "subagent-start", "--subagent-mode", "implementation", "--change", "demo", "--task", "1.1", "--json")
30412
- rejected = json.loads(result.stdout)
30413
- if rejected.get("status") == "ready":
30414
- report(f"{label} implementation allowed for {name}")
30415
- return 1
30416
- expected = "turbo" if "tier" in name else "implementation task"
30417
- if expected not in " ".join(rejected.get("reasons", [])):
30418
- report(f"{label} {name} refusal named wrong cause: {rejected.get('reasons')}")
30419
- return 1
30420
- report("model-chosen-subagents scenario passed.")
30421
- return 0
30422
-
30423
-
30424
- def validate_delegation_projection_scenario() -> int:
30425
- """The projection Keel already publishes carries the delegation, and
30426
- refuses where the preconditions for one do not hold.
30427
-
30428
- No second carrier is built: the host spawns the subagent, and this is the
30429
- one-way view of OpenSpec it is handed.
30430
- """
30431
-
30432
- def project(repo: Path, *extra: str) -> dict | None:
30433
- result = run_keel(
30434
- repo, "project", "--target", "claude",
30435
- "--event", "subagent-start", "--authorize", "subagent",
30436
- "--change", "demo", "--task", "1.1", "--json", *extra,
30437
- )
30438
- try:
30439
- return json.loads(result.stdout)
30440
- except json.JSONDecodeError:
30441
- report(f"delegation-projection: project returned no JSON: {result.stdout!r}")
30442
- report((result.stderr or "").strip())
30443
- return None
30444
-
30445
- def guard_manifest(repo: Path) -> None:
30446
- contract = run_keel(
30447
- repo, "gate", "task-start", "--change", "demo",
30448
- "--task", "1.1", "--json", "--no-guard",
30449
- )
30450
- fingerprint = json.loads(contract.stdout)["contract"]["fingerprint"]["value"]
30451
- authority = repo / "openspec/changes/demo/tasks.md"
30452
- write_text(
30453
- repo / "keel/guard.json",
30454
- json.dumps({
30455
- "schema": "keel-write-guard/v1",
30456
- "change": "demo",
30457
- "task": "1.1",
30458
- "fingerprint": {"algorithm": "sha256", "value": fingerprint},
30459
- "touch": ["src/feature.js"],
30460
- "authority": [{
30461
- "path": "openspec/changes/demo/tasks.md",
30462
- "sha256": hashlib.sha256(authority.read_bytes()).hexdigest(),
30463
- }],
30464
- }, indent=2) + "\n",
30465
- )
30466
-
30467
- with tempfile.TemporaryDirectory(prefix="keel-delproj-") as raw_tmp:
30468
- root = Path(raw_tmp)
30469
-
30470
- # M1 — a declaring repository with an active manifest projects the
30471
- # write boundary and the declared tier.
30472
- ready = root / "ready"
30473
- ready.mkdir()
30474
- write_gate_fixture(ready, standing_authorization_task())
30475
- write_authorize_config(ready, "fast_check: echo c\ndelegation:\n tier: deep\n")
30476
- guard_manifest(ready)
30477
- got = project(ready)
30478
- if got is None:
30479
- return 1
30480
- if got.get("status") != "ready":
30481
- report(f"delegation-projection: a ready delegation did not project: {got.get('reasons')}")
30482
- return 1
30483
- projection = got.get("projection") or {}
30484
- delegation = projection.get("delegation")
30485
- if delegation is None:
30486
- report(f"delegation-projection: the brief carries no delegation: {sorted(projection)}")
30487
- return 1
30488
- if delegation.get("tier") != "deep":
30489
- report(f"delegation-projection: the declared tier is not carried: {delegation}")
30490
- return 1
30491
- if not projection.get("touch"):
30492
- report("delegation-projection: the brief carries no write boundary.")
30493
- return 1
30494
- note = json.dumps(delegation)
30495
- if "select" not in note or "observe" not in note:
30496
- report(
30497
- "delegation-projection: the brief does not say Keel neither "
30498
- f"selects nor observes a model: {delegation}"
30499
- )
30500
- return 1
30501
-
30502
- # M2 — no manifest refuses, and the refusal names what is missing.
30503
- (ready / "keel" / "guard.json").unlink()
30504
- unguarded = project(ready)
30505
- if unguarded is None:
30506
- return 1
30507
- if unguarded.get("status") == "ready":
30508
- report("delegation-projection: delegation projected with no active manifest.")
30509
- return 1
30510
- reasons = " ".join(unguarded.get("reasons") or [])
30511
- if "guard" not in reasons or "task-start" not in reasons:
30512
- report(f"delegation-projection: the refusal does not name the manifest: {reasons}")
30513
- return 1
30514
-
30515
- # M2 — an unprovidable tier refuses and reports the alternatives
30516
- # rather than quietly running at a tier nobody declared.
30517
- typo = root / "typo"
30518
- typo.mkdir()
30519
- write_gate_fixture(typo, standing_authorization_task())
30520
- write_authorize_config(typo, "fast_check: echo c\ndelegation:\n tier: turbo\n")
30521
- guard_manifest(typo)
30522
- bad = project(typo)
30523
- if bad is None:
30524
- return 1
30525
- if bad.get("status") == "ready":
30526
- report("delegation-projection: an unrecognized tier still projected.")
30527
- return 1
30528
- bad_reasons = " ".join(bad.get("reasons") or [])
30529
- if "turbo" not in bad_reasons:
30530
- report(f"delegation-projection: the refusal does not name the tier: {bad_reasons}")
30531
- return 1
30532
- for name in ("routine", "standard", "deep"):
30533
- if name not in bad_reasons:
30534
- report(f"delegation-projection: the refusal omits accepted tier {name}: {bad_reasons}")
30535
- return 1
30536
-
30537
- # M3 — a silent repository still projects, without a delegation, and
30538
- # the stop side still returns evidence-only.
30539
- silent = root / "silent"
30540
- silent.mkdir()
30541
- write_gate_fixture(silent, standing_authorization_task())
30542
- write_authorize_config(silent, "fast_check: echo c\n")
30543
- guard_manifest(silent)
30544
- plain = project(silent)
30545
- if plain is None:
30546
- return 1
30547
- if plain.get("status") != "ready":
30548
- report(f"delegation-projection: a silent repository stopped projecting: {plain.get('reasons')}")
30549
- return 1
30550
- if (plain.get("projection") or {}).get("delegation") is not None:
30551
- report("delegation-projection: a silent repository projected a delegation.")
30552
- return 1
30553
- stop = run_keel(
30554
- silent, "project", "--target", "claude",
30555
- "--event", "subagent-stop", "--authorize", "subagent",
30556
- "--change", "demo", "--task", "1.1", "--json",
30557
- )
30558
- try:
30559
- stopped = json.loads(stop.stdout)
30560
- except json.JSONDecodeError:
30561
- report(f"delegation-projection: subagent-stop returned no JSON: {stop.stdout!r}")
30562
- return 1
30563
- if (stopped.get("projection") or {}).get("returnAuthority") != "report-and-evidence-only":
30564
- report(f"delegation-projection: the stop side lost its return authority: {stopped.get('projection')}")
30565
- return 1
30566
- unauthorized = run_keel(
30567
- silent, "project", "--target", "claude",
30568
- "--event", "subagent-start", "--change", "demo",
30569
- "--task", "1.1", "--json",
30570
- )
30571
- try:
30572
- refused = json.loads(unauthorized.stdout)
30573
- except json.JSONDecodeError:
30574
- report(f"delegation-projection: unauthorized start returned no JSON: {unauthorized.stdout!r}")
30575
- return 1
30576
- if refused.get("status") != "ready":
30577
- report("delegation-projection: ordinary helper required extra authorization.")
30578
- return 1
30579
-
30580
- report("delegation-projection scenario passed.")
30581
- return 0
30582
-
30583
-
30584
29302
  def validate_native_capability_scope_scenario() -> int:
30585
29303
  """A capability the target provides natively is not Keel's to build.
30586
29304
 
@@ -30641,107 +29359,6 @@ def validate_native_capability_scope_scenario() -> int:
30641
29359
  return 0
30642
29360
 
30643
29361
 
30644
- def validate_delegation_inheritance_scenario() -> int:
30645
- """A task keeps what it authored and inherits only where it authored none.
30646
-
30647
- The capsule names the source of an inherited entry, so a tier the
30648
- repository supplied is never mistaken for one this task decided.
30649
- """
30650
-
30651
- def capsule(repo: Path) -> dict | None:
30652
- result = run_keel(
30653
- repo, "gate", "task-start",
30654
- "--change", "demo", "--task", "1.1", "--json", "--no-guard",
30655
- )
30656
- try:
30657
- payload = json.loads(result.stdout)
30658
- except json.JSONDecodeError:
30659
- report(f"delegation-inheritance: task-start returned no JSON: {result.stdout!r}")
30660
- report((result.stderr or "").strip())
30661
- return None
30662
- capsule_value = (payload.get("contract") or {}).get("capsule")
30663
- if capsule_value is None:
30664
- report(f"delegation-inheritance: task-start returned no capsule: {payload}")
30665
- return None
30666
- return capsule_value
30667
-
30668
- with tempfile.TemporaryDirectory(prefix="keel-delinherit-") as raw_tmp:
30669
- root = Path(raw_tmp)
30670
-
30671
- # M1 — a task authoring no entry inherits the declared tier, and the
30672
- # capsule says the repository supplied it.
30673
- inherits = root / "inherits"
30674
- inherits.mkdir()
30675
- write_gate_fixture(inherits, standing_authorization_task())
30676
- write_authorize_config(
30677
- inherits, "fast_check: echo c\ndelegation:\n tier: deep\n"
30678
- )
30679
- got = capsule(inherits)
30680
- if got is None:
30681
- return 1
30682
- delegation = got.get("delegation")
30683
- if delegation is None:
30684
- report(f"delegation-inheritance: the capsule carries no delegation: {got.keys()}")
30685
- return 1
30686
- if delegation.get("tier") != "deep":
30687
- report(f"delegation-inheritance: the declared tier did not reach the capsule: {delegation}")
30688
- return 1
30689
- if "config.yaml" not in (delegation.get("source") or ""):
30690
- report(f"delegation-inheritance: the inherited entry does not name its source: {delegation}")
30691
- return 1
30692
-
30693
- # M2 — a task authoring its own entry keeps it, and names itself, while
30694
- # the repository declares something different.
30695
- authored = root / "authored"
30696
- authored.mkdir()
30697
- write_gate_fixture(
30698
- authored, standing_authorization_task(" - Delegation: routine\n")
30699
- )
30700
- write_authorize_config(
30701
- authored, "fast_check: echo c\ndelegation:\n tier: deep\n"
30702
- )
30703
- own = capsule(authored)
30704
- if own is None:
30705
- return 1
30706
- mine = own.get("delegation") or {}
30707
- if mine.get("tier") != "routine":
30708
- report(f"delegation-inheritance: the authored tier was overridden: {mine}")
30709
- return 1
30710
- if "config.yaml" in (mine.get("source") or ""):
30711
- report(f"delegation-inheritance: an authored entry was attributed to the declaration: {mine}")
30712
- return 1
30713
-
30714
- # M2 control — a silent repository leaves the task undelegated, so the
30715
- # two comparisons above are not both trivially true.
30716
- silent = root / "silent"
30717
- silent.mkdir()
30718
- write_gate_fixture(silent, standing_authorization_task())
30719
- write_authorize_config(silent, "fast_check: echo c\n")
30720
- none_of_it = capsule(silent)
30721
- if none_of_it is None:
30722
- return 1
30723
- absent = none_of_it.get("delegation") or {}
30724
- if absent.get("tier") is not None:
30725
- report(f"delegation-inheritance: a silent repository delegated: {absent}")
30726
- return 1
30727
-
30728
- # M3 — a helper is still read-only. A delegate is a different role, not
30729
- # a helper with the restriction removed.
30730
- for label, repo in (("inherits", inherits), ("authored", authored), ("silent", silent)):
30731
- again = capsule(repo)
30732
- if again is None:
30733
- return 1
30734
- if again.get("helperAuthority") != "read-only-evidence-only":
30735
- report(
30736
- f"delegation-inheritance: {label} changed helper authority: "
30737
- f"{again.get('helperAuthority')}"
30738
- )
30739
- return 1
30740
-
30741
- report("delegation-inheritance scenario passed.")
30742
- return 0
30743
-
30744
-
30745
29362
  def validate_review_checks_content_scenario() -> int:
30746
29363
  """Both checks concern content a gate can only shape-check.
30747
29364
 
@@ -31577,45 +30194,19 @@ ACCEPTED_AUTHORIZE_NAMES = (
31577
30194
  def validate_continuation_docs_scenario() -> int:
31578
30195
  """Every text an agent reads at the between-task boundary names the word (#94).
31579
30196
 
31580
- The declaration only works if the boundary's readers know it exists: the
31581
- goal skill's stop rule is what an agent obeys at the boundary, the README
31582
- and the config comment are where an owner learns the vocabulary, and the
31583
- resident protocol is what the enforcing agent holds in context.
30197
+ The README and the config comment are where an owner learns the
30198
+ vocabulary, and the resident protocol is what the agent holds in context.
30199
+ The goal skill's stop rule was the third reader until the skill was
30200
+ removed in 5.173.0 (#414).
31584
30201
  """
31585
30202
  label = "continuation-docs"
31586
30203
 
31587
- src_skill = (
31588
- ROOT / "src/skills/keel-run-single-task-goal/SKILL.md"
31589
- ).read_text(encoding="utf-8")
31590
- plugin_skill = (
31591
- ROOT / "plugins/keel/skills/keel-run-single-task-goal/SKILL.md"
31592
- ).read_text(encoding="utf-8")
31593
- if src_skill != plugin_skill:
31594
- report(f"{label}: the src/ and plugins/ skill copies diverge.")
31595
- return 1
31596
-
31597
- step7 = next(
31598
- (line for line in plugin_skill.splitlines() if line.startswith("7. ")), ""
31599
- )
31600
- if not step7.startswith("7. Stop."):
31601
- report(f"{label}: the goal skill lost its stop step: {step7!r}")
31602
- return 1
31603
- for needle in (
31604
- "standing `continuation` authorization",
31605
- "keel/config.yaml",
31606
- "next unchecked task of the same change",
31607
- "its own recorded fingerprint",
31608
- "no hidden scheduler",
31609
- ):
31610
- if needle not in step7:
31611
- report(f"{label}: the stop rule lacks: {needle}")
31612
- report(step7)
31613
- return 1
31614
-
31615
30204
  readme = (ROOT / "README.md").read_text(encoding="utf-8")
30205
+ # Since #414 crossing the boundary needs no confirmation by default, and the
30206
+ # README says so where it names the word.
31616
30207
  for needle in (
31617
30208
  "next unchecked task of the same change",
31618
- "the stop that re-asks for an approval already given",
30209
+ "needs no confirmation by default",
31619
30210
  ):
31620
30211
  if needle not in readme:
31621
30212
  report(f"{label}: README.md lacks: {needle}")
@@ -31665,8 +30256,8 @@ def validate_continuation_docs_scenario() -> int:
31665
30256
  return 1
31666
30257
  section = parts[1].split("\n## ", 1)[0]
31667
30258
  for needle in (
31668
- "standing `continuation` authorization",
31669
- "next unchecked task of the same change",
30259
+ "declared `continuation` is accepted and changes nothing",
30260
+ "next unchecked task of the same approved change needs no confirmation",
31670
30261
  "its own recorded fingerprint",
31671
30262
  ):
31672
30263
  if needle not in section:
@@ -31936,984 +30527,6 @@ def validate_verify_layer_tag_scenario() -> int:
31936
30527
  return 0
31937
30528
 
31938
30529
 
31939
- def validate_native_goal_gate_order_scenario() -> int:
31940
- with tempfile.TemporaryDirectory(prefix="keel-goal-order-") as raw_tmp:
31941
- root = Path(raw_tmp)
31942
- repo = root / "codex"
31943
- repo.mkdir()
31944
- env = dict(os.environ)
31945
- env["CODEX_HOME"] = str(root / "codex-home")
31946
- if run_keel(repo, "--install", "--target", "codex", env=env).returncode != 0:
31947
- report("native-goal-gate-order install failed.")
31948
- return 1
31949
- tasks_path = repo / "openspec/changes/sample-change/tasks.md"
31950
- write_text(tasks_path, _goal_tasks_file([_goal_task_block()]))
31951
- # A native evaluator claiming success must never stand in for the gates.
31952
- write_text(repo / ".codex/transcripts/session.json", '{"complete": true}\n')
31953
-
31954
- goal_result = run_keel(
31955
- repo, "project", "goal",
31956
- "--target", "codex",
31957
- "--change", "sample-change", "--task", "1.1", "--json",
31958
- env=env,
31959
- )
31960
- goal = json.loads(goal_result.stdout).get("goal") or {}
31961
- presentation = goal.get("evidencePresentation") or []
31962
- if (
31963
- len(presentation) != 3
31964
- or "Done only when: task-complete passes" not in goal.get("condition", "")
31965
- or "durably checked" not in goal.get("condition", "")
31966
- ):
31967
- report("native-goal-gate-order goal did not encode the durable completion order.")
31968
- report(json.dumps(goal, indent=2))
31969
- return 1
31970
-
31971
- # 1. task-start passes and yields the fingerprint authorization.
31972
- start = run_keel(
31973
- repo, "gate", "task-start",
31974
- "--change", "sample-change", "--task", "1.1", "--json",
31975
- env=env,
31976
- )
31977
- if start.returncode != 0:
31978
- report("native-goal-gate-order task-start failed.")
31979
- return 1
31980
-
31981
- # 2. Premature completion is rejected before implementation/evidence exist,
31982
- # even with a native "complete" transcript present.
31983
- before_tasks = tasks_path.read_text(encoding="utf-8")
31984
- premature = run_keel(
31985
- repo, "gate", "task-complete",
31986
- "--change", "sample-change", "--task", "1.1", "--json",
31987
- env=env,
31988
- )
31989
- if premature.returncode == 0:
31990
- report("native-goal-gate-order allowed premature completion.")
31991
- return 1
31992
-
31993
- # 3. Compiling the goal never checks the box; the current agent owns it.
31994
- run_keel(
31995
- repo, "project", "goal",
31996
- "--target", "codex",
31997
- "--change", "sample-change", "--task", "1.1", "--json",
31998
- env=env,
31999
- )
32000
- if tasks_path.read_text(encoding="utf-8") != before_tasks:
32001
- report("native-goal-gate-order goal projection mutated the task owner.")
32002
- return 1
32003
-
32004
- # 4. With evidence and a passing Review recorded, task-complete passes.
32005
- write_text(tasks_path, _goal_tasks_file([_goal_task_block(filled=True)]))
32006
- record_contract_anchor(repo, "sample-change")
32007
- completed = run_keel(
32008
- repo, "gate", "task-complete",
32009
- "--change", "sample-change", "--task", "1.1", "--json",
32010
- env=env,
32011
- )
32012
- if completed.returncode != 0:
32013
- report("native-goal-gate-order rejected a completed task after evidence and Review.")
32014
- report((completed.stderr or completed.stdout).strip())
32015
- return 1
32016
-
32017
- # 5. A blocked state never satisfies completion.
32018
- write_text(
32019
- tasks_path,
32020
- _goal_tasks_file(
32021
- [_goal_task_block(filled=True, blocker="native runtime lost the goal condition")]
32022
- ),
32023
- )
32024
- blocked = run_keel(
32025
- repo, "gate", "task-complete",
32026
- "--change", "sample-change", "--task", "1.1", "--json",
32027
- env=env,
32028
- )
32029
- if blocked.returncode == 0:
32030
- report("native-goal-gate-order let a blocked task complete.")
32031
- return 1
32032
-
32033
- # 6. After the current agent durably checks the box, the goal stops.
32034
- write_text(tasks_path, _goal_tasks_file([_goal_task_block(checked=True, filled=True)]))
32035
- stopped = run_keel(
32036
- repo, "project", "goal",
32037
- "--target", "codex",
32038
- "--change", "sample-change", "--task", "1.1", "--json",
32039
- env=env,
32040
- )
32041
- stopped_payload = json.loads(stopped.stdout)
32042
- if stopped.returncode == 0 or stopped_payload.get("status") != "blocked":
32043
- report("native-goal-gate-order did not stop after completion.")
32044
- return 1
32045
-
32046
- report("native-goal-gate-order scenario passed.")
32047
- return 0
32048
-
32049
-
32050
- def validate_native_goal_continuity_scenario() -> int:
32051
- with tempfile.TemporaryDirectory(prefix="keel-goal-continuity-") as raw_tmp:
32052
- root = Path(raw_tmp)
32053
- repo = root / "codex"
32054
- repo.mkdir()
32055
- env = dict(os.environ)
32056
- env["CODEX_HOME"] = str(root / "codex-home")
32057
- if run_keel(repo, "--install", "--target", "codex", env=env).returncode != 0:
32058
- report("native-goal-continuity install failed.")
32059
- return 1
32060
- tasks_path = repo / "openspec/changes/sample-change/tasks.md"
32061
- write_text(
32062
- tasks_path,
32063
- _goal_tasks_file(
32064
- [
32065
- _goal_task_block(task_id="1.1"),
32066
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
32067
- ]
32068
- ),
32069
- )
32070
- owner = "openspec/changes/sample-change/tasks.md#1.1"
32071
-
32072
- def _goal(*args: str) -> subprocess.CompletedProcess[str]:
32073
- return run_keel(
32074
- repo, "project", "goal",
32075
- "--target", "codex",
32076
- "--change", "sample-change", "--task", "1.1",
32077
- *args,
32078
- "--json",
32079
- env=env,
32080
- )
32081
-
32082
- # Continuity is reconstructed from OpenSpec/Git, not a Keel cursor/cache.
32083
- before = snapshot_files(repo)
32084
- first = _goal()
32085
- second = _goal()
32086
- if before != snapshot_files(repo):
32087
- report("native-goal-continuity wrote a Keel cursor or cache.")
32088
- return 1
32089
- first_goal = json.loads(first.stdout).get("goal") or {}
32090
- second_goal = json.loads(second.stdout).get("goal") or {}
32091
- if not first_goal or first_goal != second_goal:
32092
- report("native-goal-continuity did not reconstruct an identical goal.")
32093
- return 1
32094
- recorded = first_goal.get("fingerprint", {}).get("value")
32095
-
32096
- # A matching authorized resume is accepted.
32097
- resume = _goal("--expected-fingerprint", recorded, "--expected-owner", owner)
32098
- if resume.returncode != 0 or json.loads(resume.stdout).get("status") != "ready":
32099
- report("native-goal-continuity rejected a matching authorized resume.")
32100
- return 1
32101
-
32102
- def _blocks(result: subprocess.CompletedProcess[str], label: str) -> bool:
32103
- if result.returncode == 0:
32104
- report("native-goal-continuity accepted %s." % label)
32105
- return False
32106
- payload = json.loads(result.stdout)
32107
- if payload.get("status") != "blocked" or payload.get("goal") is not None:
32108
- report("native-goal-continuity %s was not a clean block." % label)
32109
- return False
32110
- return True
32111
-
32112
- # Missing authorization (a resume with no explicit task) never auto-advances
32113
- # to the proposed next task.
32114
- missing = run_keel(
32115
- repo, "project", "goal",
32116
- "--target", "codex", "--change", "sample-change", "--json",
32117
- env=env,
32118
- )
32119
- if not _blocks(missing, "missing authorization"):
32120
- return 1
32121
-
32122
- # Checkout divergence: the recorded owner no longer matches.
32123
- if not _blocks(
32124
- _goal("--expected-owner", "openspec/changes/other/tasks.md#9.9"),
32125
- "checkout divergence",
32126
- ):
32127
- return 1
32128
-
32129
- # Fingerprint drift: a real source change makes the recompiled capsule
32130
- # diverge from the recorded authorization.
32131
- write_text(
32132
- tasks_path,
32133
- _goal_tasks_file(
32134
- [
32135
- _goal_task_block(
32136
- task_id="1.1",
32137
- acceptance=("A different observable result is proven by M1.",),
32138
- ),
32139
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
32140
- ]
32141
- ),
32142
- )
32143
- recompiled = json.loads(_goal().stdout).get("goal") or {}
32144
- if recompiled.get("fingerprint", {}).get("value") == recorded:
32145
- report("native-goal-continuity did not track the durable source change.")
32146
- return 1
32147
- if not _blocks(
32148
- _goal("--expected-fingerprint", recorded),
32149
- "fingerprint drift",
32150
- ):
32151
- return 1
32152
-
32153
- # Completed authorization stops; the next task is never auto-selected.
32154
- write_text(
32155
- tasks_path,
32156
- _goal_tasks_file(
32157
- [
32158
- _goal_task_block(task_id="1.1", checked=True, filled=True),
32159
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
32160
- ]
32161
- ),
32162
- )
32163
- if not _blocks(_goal(), "completed authorization"):
32164
- return 1
32165
- next_task = run_keel(
32166
- repo, "project", "goal",
32167
- "--target", "codex", "--change", "sample-change", "--json",
32168
- env=env,
32169
- )
32170
- if not _blocks(next_task, "auto-advance to the next task"):
32171
- return 1
32172
-
32173
- report("native-goal-continuity scenario passed.")
32174
- return 0
32175
-
32176
-
32177
- def validate_native_helper_brief_scenario() -> int:
32178
- with tempfile.TemporaryDirectory(prefix="keel-helper-brief-") as raw_tmp:
32179
- root = Path(raw_tmp)
32180
- repo = root / "repo"
32181
- (repo / "src").mkdir(parents=True)
32182
- write_text(repo / "src/goal.js", "// sample\n")
32183
-
32184
- def _helper(*args: str) -> subprocess.CompletedProcess[str]:
32185
- return run_keel(repo, "project", "helper", *args, "--json")
32186
-
32187
- # A bounded read-only question compiles a non-writing, non-delegating brief.
32188
- before = snapshot_files(repo)
32189
- question = _helper(
32190
- "--target", "codex",
32191
- "--brief", "Which function in src/goal.js renders the condition?",
32192
- "--read", "src/goal.js",
32193
- )
32194
- payload = json.loads(question.stdout)
32195
- brief = payload.get("brief") or {}
32196
- if (
32197
- question.returncode != 0
32198
- or payload.get("version") != "keel-helper-brief/v1"
32199
- or payload.get("status") != "ready"
32200
- or brief.get("mode") != "question"
32201
- or brief.get("authority") != "read-only-evidence-only"
32202
- or brief.get("writesProducts") is not False
32203
- or brief.get("delegates") is not False
32204
- or brief.get("completionAuthority") is not False
32205
- or brief.get("reads") != ["src/goal.js"]
32206
- or not brief.get("reportSchema")
32207
- ):
32208
- report("native-helper-brief did not compile a bounded question brief.")
32209
- report(json.dumps(payload, indent=2))
32210
- return 1
32211
-
32212
- # An exact repository-byte-stable verification command is also accepted.
32213
- command = _helper(
32214
- "--target", "claude",
32215
- "--command", "node scripts/run_python.js scripts/validate_plugin.py --scenario cli",
32216
- )
32217
- if (
32218
- command.returncode != 0
32219
- or json.loads(command.stdout).get("brief", {}).get("mode")
32220
- != "verification-command"
32221
- ):
32222
- report("native-helper-brief rejected a byte-stable verification command.")
32223
- return 1
32224
-
32225
- if before != snapshot_files(repo):
32226
- report("native-helper-brief mutated the repository while compiling briefs.")
32227
- return 1
32228
-
32229
- def _reject(args: list[str], label: str) -> bool:
32230
- snap = snapshot_files(repo)
32231
- result = _helper(*args)
32232
- if result.returncode == 0:
32233
- report("native-helper-brief accepted %s." % label)
32234
- return False
32235
- payload = json.loads(result.stdout)
32236
- if payload.get("status") != "blocked" or payload.get("brief") is not None:
32237
- report("native-helper-brief %s was not a clean block." % label)
32238
- return False
32239
- if snap != snapshot_files(repo):
32240
- report("native-helper-brief %s mutated state." % label)
32241
- return False
32242
- return True
32243
-
32244
- checks = [
32245
- (["--target", "codex", "--brief", "Implement the renderer in src/goal.js"],
32246
- "implementation delegation"),
32247
- (["--target", "codex", "--brief", "What is X? What is Y unrelated thing?"],
32248
- "multiple unrelated questions"),
32249
- (["--target", "codex", "--brief", "Ask a subagent to summarize src/goal.js"],
32250
- "nested delegation"),
32251
- (["--target", "codex", "--brief", "Please mark the task complete and sync"],
32252
- "completion-authority request"),
32253
- (["--target", "codex", "--command", "node build.js > dist/out.txt"],
32254
- "artifact-generating command"),
32255
- (["--target", "codex", "--command", "git commit -am done"],
32256
- "commit command"),
32257
- (["--target", "codex", "--command", "node test.js", "--external", "src/tmp.json"],
32258
- "in-repo declared output"),
32259
- (["--target", "opencode", "--brief", "Which file defines the gate?"],
32260
- "opencode target"),
32261
- (["--target", "codex"], "empty brief"),
32262
- ]
32263
- for args, label in checks:
32264
- if not _reject(args, label):
32265
- return 1
32266
-
32267
- report("native-helper-brief scenario passed.")
32268
- return 0
32269
-
32270
-
32271
- def validate_native_helper_read_only_scenario() -> int:
32272
- with tempfile.TemporaryDirectory(prefix="keel-helper-ro-") as raw_tmp:
32273
- root = Path(raw_tmp)
32274
- repo = root / "repo"
32275
- (repo / "src").mkdir(parents=True)
32276
- write_text(repo / "src/a.txt", "alpha\n")
32277
- write_text(repo / "src/b.txt", "beta\n")
32278
- baseline = root / "baseline.json"
32279
-
32280
- def _capture(target_baseline: Path) -> subprocess.CompletedProcess[str]:
32281
- return run_keel(
32282
- repo, "project", "helper",
32283
- "--target", "codex", "--capture-baseline",
32284
- "--baseline", str(target_baseline), "--json",
32285
- )
32286
-
32287
- def _verify() -> subprocess.CompletedProcess[str]:
32288
- return run_keel(
32289
- repo, "project", "helper",
32290
- "--target", "codex", "--verify",
32291
- "--baseline", str(baseline), "--json",
32292
- )
32293
-
32294
- # A baseline must live outside the worktree.
32295
- inside = _capture(repo / "baseline.json")
32296
- if inside.returncode == 0:
32297
- report("native-helper-read-only wrote a baseline inside the repository.")
32298
- return 1
32299
-
32300
- # Pre-existing dirty bytes are captured into the baseline and never
32301
- # attributed to the helper.
32302
- write_text(repo / "src/pre-existing.txt", "already changed by the current agent\n")
32303
- if _capture(baseline).returncode != 0:
32304
- report("native-helper-read-only could not capture an external baseline.")
32305
- return 1
32306
- clean = _verify()
32307
- if clean.returncode != 0 or json.loads(clean.stdout).get("status") != "verified":
32308
- report("native-helper-read-only rejected an unchanged repository.")
32309
- report((clean.stderr or clean.stdout).strip())
32310
- return 1
32311
- # The pre-existing file is preserved, not cleaned up or attributed.
32312
- if not (repo / "src/pre-existing.txt").exists():
32313
- report("native-helper-read-only removed a pre-existing path.")
32314
- return 1
32315
-
32316
- def _expect_reject(mutation, label: str, expected: dict[str, str]) -> bool:
32317
- mutation()
32318
- result = _verify()
32319
- payload = json.loads(result.stdout)
32320
- if result.returncode == 0 or payload.get("status") != "rejected":
32321
- report("native-helper-read-only accepted %s." % label)
32322
- return False
32323
- changes = {c["path"]: c["kind"] for c in payload.get("changes", [])}
32324
- for path_key, kind in expected.items():
32325
- if changes.get(path_key) != kind:
32326
- report(
32327
- "native-helper-read-only %s misreported changes: %s"
32328
- % (label, json.dumps(changes))
32329
- )
32330
- return False
32331
- if payload.get("cleanup") != "none":
32332
- report("native-helper-read-only %s attempted cleanup." % label)
32333
- return False
32334
- return True
32335
-
32336
- # modified
32337
- if not _expect_reject(
32338
- lambda: write_text(repo / "src/a.txt", "alpha-changed\n"),
32339
- "a modified path",
32340
- {"src/a.txt": "modified"},
32341
- ):
32342
- return 1
32343
- # restore for isolation, re-baseline
32344
- write_text(repo / "src/a.txt", "alpha\n")
32345
- if _capture(baseline).returncode != 0:
32346
- return 1
32347
- # added
32348
- if not _expect_reject(
32349
- lambda: write_text(repo / "src/c.txt", "added\n"),
32350
- "an added path",
32351
- {"src/c.txt": "added"},
32352
- ):
32353
- return 1
32354
- (repo / "src/c.txt").unlink()
32355
- if _capture(baseline).returncode != 0:
32356
- return 1
32357
- # deleted
32358
- if not _expect_reject(
32359
- lambda: (repo / "src/b.txt").unlink(),
32360
- "a deleted path",
32361
- {"src/b.txt": "removed"},
32362
- ):
32363
- return 1
32364
- write_text(repo / "src/b.txt", "beta\n")
32365
- if _capture(baseline).returncode != 0:
32366
- return 1
32367
- # renamed -> reported as removed + added
32368
- if not _expect_reject(
32369
- lambda: (repo / "src/b.txt").rename(repo / "src/b-renamed.txt"),
32370
- "a renamed path",
32371
- {"src/b.txt": "removed", "src/b-renamed.txt": "added"},
32372
- ):
32373
- return 1
32374
-
32375
- # A command whose byte stability cannot be established remains current-agent
32376
- # work rather than a silent pass.
32377
- missing = run_keel(
32378
- repo, "project", "helper",
32379
- "--target", "codex", "--verify",
32380
- "--baseline", str(root / "does-not-exist.json"), "--json",
32381
- )
32382
- if missing.returncode == 0 or json.loads(missing.stdout).get("status") != "unverifiable":
32383
- report("native-helper-read-only accepted an unestablished baseline.")
32384
- return 1
32385
-
32386
- report("native-helper-read-only scenario passed.")
32387
- return 0
32388
-
32389
-
32390
- def validate_native_goal_capabilities_scenario() -> int:
32391
- with tempfile.TemporaryDirectory(prefix="keel-helper-caps-") as raw_tmp:
32392
- root = Path(raw_tmp)
32393
- for target in ("codex", "claude"):
32394
- repo = root / target
32395
- repo.mkdir()
32396
- env = dict(os.environ)
32397
- if target == "codex":
32398
- env["CODEX_HOME"] = str(root / "codex-home")
32399
- if run_keel(repo, "--install", "--target", target, env=env).returncode != 0:
32400
- report("native-goal-capabilities %s install failed." % target)
32401
- return 1
32402
- probed = run_keel(repo, "capabilities", "--target", target, "--json", env=env)
32403
- payload = json.loads(probed.stdout)
32404
- helper = payload.get("helper") or {}
32405
- dimensions = (
32406
- "discovery",
32407
- "toolRestriction",
32408
- "nestedDelegationPrevention",
32409
- "byteStability",
32410
- "execution",
32411
- )
32412
- if any(dim not in helper for dim in dimensions):
32413
- report("native-goal-capabilities %s omitted a helper dimension." % target)
32414
- report(json.dumps(helper, indent=2))
32415
- return 1
32416
- levels = {helper[dim].get("level") for dim in dimensions}
32417
- # enforced, advisory, and manual are reported separately.
32418
- if not {"enforced", "advisory", "manual"}.issubset(levels):
32419
- report("native-goal-capabilities %s did not separate enforcement levels." % target)
32420
- return 1
32421
- if (
32422
- helper["nestedDelegationPrevention"].get("level") != "enforced"
32423
- or helper["byteStability"].get("level") != "enforced"
32424
- or helper["execution"].get("level") != "manual"
32425
- ):
32426
- report("native-goal-capabilities %s mislabeled a helper dimension." % target)
32427
- return 1
32428
- # Helper absence never disables current-agent goal execution.
32429
- if payload.get("capabilities", {}).get("execution.goal", {}).get("level") != "manual":
32430
- report("native-goal-capabilities %s dropped goal execution." % target)
32431
- return 1
32432
- if not any(
32433
- "Helper absence never disables" in warning
32434
- for warning in payload.get("warnings", [])
32435
- ):
32436
- report("native-goal-capabilities %s did not assert helper independence." % target)
32437
- return 1
32438
-
32439
- report("native-goal-capabilities scenario passed.")
32440
- return 0
32441
-
32442
-
32443
- # The referenced half of a split skill. Returns "" for a skill with one body, so
32444
- # every assertion about a skill's content reads the same shape whether or not it
32445
- # was split — a split must not be able to drop a required statement, and a
32446
- # scenario must not have to know which skills were split to stay correct.
32447
- def skill_guidance_text(skill_md: Path) -> str:
32448
- guidance = skill_md.parent / "guidance.md"
32449
- return guidance.read_text(encoding="utf-8") if guidance.is_file() else ""
32450
-
32451
-
32452
- SINGLE_TASK_GOAL_SKILL = "keel-run-single-task-goal"
32453
- OFFICIAL_GOAL_SOURCES = (
32454
- "https://learn.chatgpt.com/use-cases/follow-goals",
32455
- "https://developers.openai.com/codex/subagents",
32456
- "https://code.claude.com/docs/en/goal",
32457
- "https://code.claude.com/docs/en/sub-agents",
32458
- )
32459
-
32460
-
32461
- def validate_single_task_goal_skill_scenario() -> int:
32462
- canonical = ROOT / "src/skills" / SINGLE_TASK_GOAL_SKILL / "SKILL.md"
32463
- projection = ROOT / "plugins/keel/skills" / SINGLE_TASK_GOAL_SKILL / "SKILL.md"
32464
- if not canonical.is_file() or not projection.is_file():
32465
- report("single-task-goal-skill missing canonical skill or native projection.")
32466
- return 1
32467
- canonical_bytes = canonical.read_bytes()
32468
- if canonical_bytes != projection.read_bytes():
32469
- report("single-task-goal-skill projection is not byte-equal to the canonical source.")
32470
- return 1
32471
- # A skill split into a body and a referenced `guidance.md` carries its
32472
- # content across both files. What these assertions require is that the skill
32473
- # states the thing, not that SKILL.md does, so the split must not be able to
32474
- # drop a required statement by moving it — and must not be able to keep one
32475
- # only in a file the plugin does not ship, which `native-plugin-manifests`
32476
- # checks byte-for-byte alongside the body.
32477
- text = canonical_bytes.decode("utf-8") + skill_guidance_text(canonical)
32478
-
32479
- # Authoritative official sources are linked, and provenance/license is recorded.
32480
- for source in OFFICIAL_GOAL_SOURCES:
32481
- if source not in text:
32482
- report("single-task-goal-skill did not link official source: %s" % source)
32483
- return 1
32484
- lowered = text.lower()
32485
- if (
32486
- "provenance" not in lowered
32487
- or "license note" not in lowered
32488
- or "not copied" not in lowered
32489
- or "paraphrase" not in lowered
32490
- ):
32491
- report("single-task-goal-skill did not record provenance/license and paraphrase intent.")
32492
- return 1
32493
- # Paraphrase, not bundle: no verbatim external doc dumped inside a fenced block.
32494
- if "```" in text:
32495
- report("single-task-goal-skill bundled a fenced external block instead of paraphrasing.")
32496
- return 1
32497
-
32498
- # Positive triggers for explicit one-task automatic execution and resume.
32499
- if not (
32500
- "## When to activate" in text
32501
- and "resume" in lowered
32502
- and ("one task" in lowered or "one" in lowered)
32503
- and "explicit" in lowered
32504
- ):
32505
- report("single-task-goal-skill lacks explicit one-task/resume positive triggers.")
32506
- return 1
32507
- # Negative triggers.
32508
- negatives = ("/opsx:apply", "proposal", "ambiguous", "opencode", "deleg", "helper")
32509
- if "## When NOT to activate" not in text or any(
32510
- neg not in lowered for neg in negatives
32511
- ):
32512
- report("single-task-goal-skill lacks the required negative triggers.")
32513
- return 1
32514
- # Manual fallback and the exact copy/paste command.
32515
- if "## Manual fallback" not in text or "keel project goal" not in text:
32516
- report("single-task-goal-skill lacks a manual fallback with the exact command.")
32517
- return 1
32518
-
32519
- # Thin activation adapters exist for both native targets and no others.
32520
- agents_dir = ROOT / "plugins/keel/agents"
32521
- agent_files = sorted(p.name for p in agents_dir.glob("*.md")) if agents_dir.is_dir() else []
32522
- expected_agents = [
32523
- "keel-single-task-goal-claude.md",
32524
- "keel-single-task-goal-codex.md",
32525
- ]
32526
- if agent_files != expected_agents:
32527
- report("single-task-goal-skill adapters are not exactly the codex and claude pair.")
32528
- return 1
32529
- for name, target in (
32530
- ("keel-single-task-goal-codex.md", "codex"),
32531
- ("keel-single-task-goal-claude.md", "claude"),
32532
- ):
32533
- adapter = (agents_dir / name).read_text(encoding="utf-8")
32534
- if ("target: %s" % target) not in adapter or "read-only" not in adapter.lower():
32535
- report("single-task-goal-skill %s adapter is missing target or read-only helper policy." % target)
32536
- return 1
32537
-
32538
- report("single-task-goal-skill scenario passed.")
32539
- return 0
32540
-
32541
-
32542
- def validate_single_task_goal_real_tasks_scenario() -> int:
32543
- cases = (
32544
- ("bug-fix", "vertical-tdd", True),
32545
- ("generator", "characterization", False),
32546
- ("rendered", "rendered-behavior", False),
32547
- )
32548
- with tempfile.TemporaryDirectory(prefix="keel-real-tasks-") as raw_tmp:
32549
- root = Path(raw_tmp)
32550
- for name, strategy, redgreen in cases:
32551
- repo = root / name
32552
- repo.mkdir()
32553
- env = dict(os.environ)
32554
- env["CODEX_HOME"] = str(root / ("codex-home-" + name))
32555
- if run_keel(repo, "--install", "--target", "codex", env=env).returncode != 0:
32556
- report("single-task-goal-real-tasks %s install failed." % name)
32557
- return 1
32558
- tasks_path = repo / "openspec/changes/sample-change/tasks.md"
32559
- write_text(tasks_path, _goal_tasks_file([_goal_task_block(strategy=strategy)]))
32560
-
32561
- start = run_keel(
32562
- repo, "gate", "task-start",
32563
- "--change", "sample-change", "--task", "1.1", "--json", env=env,
32564
- )
32565
- if start.returncode != 0:
32566
- report("single-task-goal-real-tasks %s task-start failed." % name)
32567
- return 1
32568
- goal = run_keel(
32569
- repo, "project", "goal",
32570
- "--target", "codex", "--change", "sample-change", "--task", "1.1",
32571
- "--json", env=env,
32572
- )
32573
- gpayload = json.loads(goal.stdout).get("goal") or {}
32574
- if goal.returncode != 0 or gpayload.get("verificationStrategy") != strategy:
32575
- report("single-task-goal-real-tasks %s goal did not carry its strategy." % name)
32576
- return 1
32577
-
32578
- # Complete the one task through its approved strategy evidence.
32579
- write_text(
32580
- tasks_path,
32581
- _goal_tasks_file(
32582
- [_goal_task_block(strategy=strategy, filled=True, redgreen=redgreen)]
32583
- ),
32584
- )
32585
- record_contract_anchor(repo, "sample-change")
32586
- done = run_keel(
32587
- repo, "gate", "task-complete",
32588
- "--change", "sample-change", "--task", "1.1", "--json", env=env,
32589
- )
32590
- if done.returncode != 0:
32591
- report("single-task-goal-real-tasks %s task-complete failed." % name)
32592
- report((done.stderr or done.stdout).strip())
32593
- return 1
32594
-
32595
- # Current agent checks the one box; the run then stops at that boundary.
32596
- write_text(
32597
- tasks_path,
32598
- _goal_tasks_file(
32599
- [_goal_task_block(strategy=strategy, checked=True, filled=True, redgreen=redgreen)]
32600
- ),
32601
- )
32602
- stopped = run_keel(
32603
- repo, "project", "goal",
32604
- "--target", "codex", "--change", "sample-change", "--task", "1.1",
32605
- "--json", env=env,
32606
- )
32607
- if stopped.returncode == 0 or json.loads(stopped.stdout).get("status") != "blocked":
32608
- report("single-task-goal-real-tasks %s did not stop after one task." % name)
32609
- return 1
32610
- # No next fixture task exists or was auto-created.
32611
- if "1.2" in tasks_path.read_text(encoding="utf-8"):
32612
- report("single-task-goal-real-tasks %s started a next task." % name)
32613
- return 1
32614
-
32615
- report("single-task-goal-real-tasks scenario passed.")
32616
- return 0
32617
-
32618
-
32619
- def _goal_target_surface(target: str) -> int:
32620
- with tempfile.TemporaryDirectory(prefix="keel-goal-%s-" % target) as raw_tmp:
32621
- root = Path(raw_tmp)
32622
- repo = root / target
32623
- repo.mkdir()
32624
- env = dict(os.environ)
32625
- if target == "codex":
32626
- env["CODEX_HOME"] = str(root / "codex-home")
32627
- if run_keel(repo, "--install", "--target", target, env=env).returncode != 0:
32628
- report("native-goal-%s install failed." % target)
32629
- return 1
32630
- write_text(
32631
- repo / "openspec/changes/sample-change/tasks.md",
32632
- _goal_tasks_file([_goal_task_block(strategy="vertical-tdd")]),
32633
- )
32634
-
32635
- # The plugin ships the portable skill and this target's activation adapter.
32636
- adapter = ROOT / "plugins/keel/agents" / ("keel-single-task-goal-%s.md" % target)
32637
- if not (ROOT / "plugins/keel/skills" / SINGLE_TASK_GOAL_SKILL).is_dir() or not adapter.is_file():
32638
- report("native-goal-%s missing portable skill or activation adapter." % target)
32639
- return 1
32640
-
32641
- # Explicit activation, resume, drift stop, and single-task termination.
32642
- activated = run_keel(
32643
- repo, "project", "goal", "--target", target,
32644
- "--change", "sample-change", "--task", "1.1", "--json", env=env,
32645
- )
32646
- apayload = json.loads(activated.stdout)
32647
- goal = apayload.get("goal") or {}
32648
- if activated.returncode != 0 or apayload.get("status") != "ready":
32649
- report("native-goal-%s did not activate one task." % target)
32650
- return 1
32651
- if target == "claude" and goal.get("conditionLength", 0) > 4000:
32652
- report("native-goal-claude condition exceeded the 4,000-character budget.")
32653
- return 1
32654
- recorded = goal.get("fingerprint", {}).get("value")
32655
- owner = "openspec/changes/sample-change/tasks.md#1.1"
32656
- resume = run_keel(
32657
- repo, "project", "goal", "--target", target,
32658
- "--change", "sample-change", "--task", "1.1",
32659
- "--expected-fingerprint", recorded, "--expected-owner", owner, "--json", env=env,
32660
- )
32661
- if resume.returncode != 0 or json.loads(resume.stdout).get("status") != "ready":
32662
- report("native-goal-%s could not resume the authorized task." % target)
32663
- return 1
32664
- drift = run_keel(
32665
- repo, "project", "goal", "--target", target,
32666
- "--change", "sample-change", "--task", "1.1",
32667
- "--expected-fingerprint", "deadbeef", "--json", env=env,
32668
- )
32669
- if drift.returncode == 0 or json.loads(drift.stdout).get("status") != "blocked":
32670
- report("native-goal-%s did not stop on drift." % target)
32671
- return 1
32672
-
32673
- # Capabilities surface the goal at manual with a copy/paste command fallback.
32674
- caps = run_keel(repo, "capabilities", "--target", target, "--json", env=env)
32675
- cpayload = json.loads(caps.stdout)
32676
- goal_cap = cpayload.get("capabilities", {}).get("execution.goal", {})
32677
- if goal_cap.get("level") != "manual" or not goal_cap.get("command"):
32678
- report("native-goal-%s did not report an advisory goal command fallback." % target)
32679
- return 1
32680
-
32681
- # The skill carries the target-specific fallback guidance.
32682
- skill_body = ROOT / "plugins/keel/skills" / SINGLE_TASK_GOAL_SKILL / "SKILL.md"
32683
- skill_text = skill_body.read_text(encoding="utf-8") + skill_guidance_text(
32684
- skill_body
32685
- )
32686
- if target == "claude" and "disabled hooks" not in skill_text.lower():
32687
- report("native-goal-claude skill lacks the disabled-hooks fallback.")
32688
- return 1
32689
- if target == "codex" and "advisory" not in skill_text.lower():
32690
- report("native-goal-codex skill lacks the advisory activation fallback.")
32691
- return 1
32692
- return 0
32693
-
32694
-
32695
- def validate_native_goal_codex_scenario() -> int:
32696
- status = _goal_target_surface("codex")
32697
- if status == 0:
32698
- report("native-goal-codex scenario passed.")
32699
- return status
32700
-
32701
-
32702
- def validate_native_goal_claude_scenario() -> int:
32703
- status = _goal_target_surface("claude")
32704
- if status == 0:
32705
- report("native-goal-claude scenario passed.")
32706
- return status
32707
-
32708
-
32709
- def validate_native_helper_targets_scenario() -> int:
32710
- with tempfile.TemporaryDirectory(prefix="keel-helper-targets-") as raw_tmp:
32711
- root = Path(raw_tmp)
32712
- for target in ("codex", "claude"):
32713
- repo = root / target
32714
- repo.mkdir()
32715
- env = dict(os.environ)
32716
- if target == "codex":
32717
- env["CODEX_HOME"] = str(root / "codex-home")
32718
- if run_keel(repo, "--install", "--target", target, env=env).returncode != 0:
32719
- report("native-helper-targets %s install failed." % target)
32720
- return 1
32721
- caps = run_keel(repo, "capabilities", "--target", target, "--json", env=env)
32722
- helper = json.loads(caps.stdout).get("helper") or {}
32723
- # Write and delegation authority are removed where supported (enforced),
32724
- # and dimensions downgrade independently (mixed levels).
32725
- if (
32726
- helper.get("nestedDelegationPrevention", {}).get("level") != "enforced"
32727
- or helper.get("byteStability", {}).get("level") != "enforced"
32728
- or helper.get("toolRestriction", {}).get("level") != "advisory"
32729
- or helper.get("execution", {}).get("level") != "manual"
32730
- ):
32731
- report("native-helper-targets %s did not downgrade helper dimensions independently." % target)
32732
- return 1
32733
- # Only byte-stable read-only briefs are accepted.
32734
- ok = run_keel(
32735
- repo, "project", "helper", "--target", target,
32736
- "--brief", "Which file defines the gate?", "--json", env=env,
32737
- )
32738
- if ok.returncode != 0 or json.loads(ok.stdout).get("status") != "ready":
32739
- report("native-helper-targets %s rejected a bounded read-only brief." % target)
32740
- return 1
32741
- bad = run_keel(
32742
- repo, "project", "helper", "--target", target,
32743
- "--brief", "Delegate the fix to a subagent", "--json", env=env,
32744
- )
32745
- if bad.returncode == 0 or json.loads(bad.stdout).get("status") != "blocked":
32746
- report("native-helper-targets %s accepted a delegating helper." % target)
32747
- return 1
32748
-
32749
- # No agent team or OpenCode v4 artifact is introduced: the adapter set is
32750
- # exactly the codex and claude pair.
32751
- agents_dir = ROOT / "plugins/keel/agents"
32752
- names = sorted(p.name for p in agents_dir.glob("*.md"))
32753
- if names != ["keel-single-task-goal-claude.md", "keel-single-task-goal-codex.md"]:
32754
- report("native-helper-targets adapter set is not exactly the codex and claude pair.")
32755
- return 1
32756
- # No global Stop hook is registered in either native manifest.
32757
- for runtime in (".codex-plugin", ".claude-plugin"):
32758
- manifest = json.loads(
32759
- (ROOT / "plugins/keel" / runtime / "plugin.json").read_text(encoding="utf-8")
32760
- )
32761
- hooks = json.dumps(manifest.get("hooks", {})).lower()
32762
- if "stop" in hooks:
32763
- report("native-helper-targets registered a global Stop hook in %s." % runtime)
32764
- return 1
32765
-
32766
- report("native-helper-targets scenario passed.")
32767
- return 0
32768
-
32769
-
32770
- def _single_task_matrix_target(target: str, root: Path) -> int:
32771
- repo = root / target
32772
- repo.mkdir()
32773
- env = dict(os.environ)
32774
- if target == "codex":
32775
- env["CODEX_HOME"] = str(root / ("codex-home-" + target))
32776
- if run_keel(repo, "--install", "--target", target, env=env).returncode != 0:
32777
- report("native-single-task-matrix %s install failed." % target)
32778
- return 1
32779
- tasks_path = repo / "openspec/changes/sample-change/tasks.md"
32780
-
32781
- def two_tasks(checked_first: bool = False, blocker: str = "none") -> str:
32782
- return _goal_tasks_file(
32783
- [
32784
- _goal_task_block(
32785
- task_id="1.1", strategy="vertical-tdd",
32786
- checked=checked_first, filled=checked_first, redgreen=checked_first,
32787
- blocker=blocker,
32788
- ),
32789
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
32790
- ]
32791
- )
32792
-
32793
- write_text(tasks_path, two_tasks())
32794
- # A native "already complete" transcript must never act as authority.
32795
- write_text(repo / (".%s/transcripts/session.json" % target), '{"complete": true}\n')
32796
-
32797
- def goal(*args: str) -> subprocess.CompletedProcess[str]:
32798
- return run_keel(
32799
- repo, "project", "goal", "--target", target,
32800
- "--change", "sample-change", "--task", "1.1", *args, "--json", env=env,
32801
- )
32802
-
32803
- # Explicit one-task activation with the vertical strategy carried through.
32804
- activated = json.loads(goal().stdout)
32805
- if activated.get("status") != "ready" or activated["goal"]["verificationStrategy"] != "vertical-tdd":
32806
- report("native-single-task-matrix %s did not activate one vertical task." % target)
32807
- return 1
32808
- recorded = activated["goal"]["fingerprint"]["value"]
32809
- owner = "openspec/changes/sample-change/tasks.md#1.1"
32810
-
32811
- # Compaction reconstruction is identical and writes no Keel cursor/cache.
32812
- before = snapshot_files(repo)
32813
- if json.loads(goal().stdout)["goal"] != activated["goal"]:
32814
- report("native-single-task-matrix %s reconstruction diverged." % target)
32815
- return 1
32816
- if before != snapshot_files(repo):
32817
- report("native-single-task-matrix %s wrote Keel goal/cursor state." % target)
32818
- return 1
32819
-
32820
- # Exact resume; drift and ambiguous checkout hard-stop; premature success ignored.
32821
- if json.loads(goal("--expected-fingerprint", recorded, "--expected-owner", owner).stdout)["status"] != "ready":
32822
- report("native-single-task-matrix %s rejected an exact resume." % target)
32823
- return 1
32824
- if json.loads(goal("--expected-fingerprint", "deadbeef").stdout)["status"] != "blocked":
32825
- report("native-single-task-matrix %s did not stop on drift." % target)
32826
- return 1
32827
- if json.loads(goal("--expected-owner", "openspec/changes/other/tasks.md#9.9").stdout)["status"] != "blocked":
32828
- report("native-single-task-matrix %s did not stop on ambiguous checkout." % target)
32829
- return 1
32830
-
32831
- # Current-agent order: task-complete fails before evidence, passes after, and a
32832
- # blocked task never completes; failure never rolls back or escalates.
32833
- start = run_keel(repo, "gate", "task-start", "--change", "sample-change", "--task", "1.1", "--json", env=env)
32834
- if start.returncode != 0:
32835
- report("native-single-task-matrix %s task-start failed." % target)
32836
- return 1
32837
- pre = snapshot_files(repo)
32838
- if run_keel(repo, "gate", "task-complete", "--change", "sample-change", "--task", "1.1", "--json", env=env).returncode == 0:
32839
- report("native-single-task-matrix %s allowed premature completion." % target)
32840
- return 1
32841
- if pre != snapshot_files(repo):
32842
- report("native-single-task-matrix %s failing gate mutated the tree." % target)
32843
- return 1
32844
- # A blocked task never completes, even with evidence and a passing Review.
32845
- write_text(
32846
- tasks_path,
32847
- _goal_tasks_file(
32848
- [
32849
- _goal_task_block(
32850
- task_id="1.1", strategy="vertical-tdd", filled=True, redgreen=True,
32851
- blocker="native runtime lost the goal condition",
32852
- ),
32853
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
32854
- ]
32855
- ),
32856
- )
32857
- if run_keel(repo, "gate", "task-complete", "--change", "sample-change", "--task", "1.1", "--json", env=env).returncode == 0:
32858
- report("native-single-task-matrix %s let a blocked task complete." % target)
32859
- return 1
32860
-
32861
- # Helper success and helper write/delegation rejection.
32862
- ok = run_keel(repo, "project", "helper", "--target", target, "--brief", "Which file defines the gate?", "--json", env=env)
32863
- if json.loads(ok.stdout).get("status") != "ready":
32864
- report("native-single-task-matrix %s rejected a bounded helper." % target)
32865
- return 1
32866
- bad = run_keel(repo, "project", "helper", "--target", target, "--brief", "Delegate the fix to a subagent", "--json", env=env)
32867
- if json.loads(bad.stdout).get("status") != "blocked":
32868
- report("native-single-task-matrix %s accepted a delegating helper." % target)
32869
- return 1
32870
-
32871
- # Successful completion: evidence + Review, task-complete passes, current agent
32872
- # checks the box, then the goal stops and never selects the next task.
32873
- write_text(
32874
- tasks_path,
32875
- _goal_tasks_file(
32876
- [
32877
- _goal_task_block(task_id="1.1", strategy="vertical-tdd", filled=True, redgreen=True),
32878
- _goal_task_block(task_id="1.2", title="Second bounded behavior"),
32879
- ]
32880
- ),
32881
- )
32882
- record_contract_anchor(repo, "sample-change")
32883
- done = run_keel(repo, "gate", "task-complete", "--change", "sample-change", "--task", "1.1", "--json", env=env)
32884
- if done.returncode != 0:
32885
- report("native-single-task-matrix %s could not complete with evidence." % target)
32886
- report((done.stderr or done.stdout).strip())
32887
- return 1
32888
- write_text(tasks_path, two_tasks(checked_first=True))
32889
- if json.loads(goal().stdout)["status"] != "blocked":
32890
- report("native-single-task-matrix %s did not stop after completion." % target)
32891
- return 1
32892
- no_task = run_keel(repo, "project", "goal", "--target", target, "--change", "sample-change", "--json", env=env)
32893
- if json.loads(no_task.stdout)["status"] != "blocked":
32894
- report("native-single-task-matrix %s auto-advanced to the next task." % target)
32895
- return 1
32896
-
32897
- # No Keel cursor, goal id, scheduler, queue, or global Stop hook state exists.
32898
- forbidden = (".keel", "keel-cursor.json", "goal-id.json", "scheduler.json", "queue.json")
32899
- for name in forbidden:
32900
- if list(repo.rglob(name)):
32901
- report("native-single-task-matrix %s created forbidden Keel state: %s" % (target, name))
32902
- return 1
32903
- return 0
32904
-
32905
-
32906
- def validate_native_single_task_matrix_scenario() -> int:
32907
- with tempfile.TemporaryDirectory(prefix="keel-matrix-") as raw_tmp:
32908
- root = Path(raw_tmp)
32909
- for target in ("codex", "claude"):
32910
- status = _single_task_matrix_target(target, root)
32911
- if status != 0:
32912
- return status
32913
- report("native-single-task-matrix scenario passed.")
32914
- return 0
32915
-
32916
-
32917
30530
  def validate_thin_native_install_scenario() -> int:
32918
30531
  with tempfile.TemporaryDirectory(prefix="keel-thin-install-") as raw_tmp:
32919
30532
  tmp = Path(raw_tmp)
@@ -34823,7 +32436,7 @@ def validate_domain_execution_references_scenario() -> int:
34823
32436
  for needle in (
34824
32437
  "keel/lenses/",
34825
32438
  "Execution and review checks",
34826
- "load only that one",
32439
+ "the lens whose `Applies when:` header matches",
34827
32440
  "no lens matches",
34828
32441
  ):
34829
32442
  if needle not in text:
@@ -35665,7 +33278,7 @@ def validate_guard_status_stale_manifest_scenario() -> int:
35665
33278
  # operands (the gate did not fail the way the fixture requires, whichever half
35666
33279
  # was wrong), and every site prints the full problem payload alongside it, so
35667
33280
  # a reader is never left with only the sentence.
35668
- OR_GUARDED_ASSERTION_SITES = 80
33281
+ OR_GUARDED_ASSERTION_SITES = 74
35669
33282
 
35670
33283
 
35671
33284
  def or_guarded_assertion_sites(source: str) -> list[int]:
@@ -37407,10 +35020,12 @@ def validate_output_survives_the_pipe_scenario() -> int:
37407
35020
  [_goal_task_block(acceptance=huge, strategy="vertical-tdd")]
37408
35021
  )
37409
35022
 
35023
+ # A task-start result carries the whole compiled capsule, so a long
35024
+ # Acceptance makes it larger than the shrunken pipe. (It was `keel project
35025
+ # goal` until that command was removed in 5.173.0, #414.)
37410
35026
  goal_args = (
37411
- "project", "goal",
37412
- "--target", "codex",
37413
- "--change", "sample-change", "--task", "1.1", "--json",
35027
+ "gate", "task-start",
35028
+ "--change", "sample-change", "--task", "1.1", "--json", "--no-guard",
37414
35029
  )
37415
35030
 
37416
35031
  with tempfile.TemporaryDirectory(prefix="keel-pipe-") as raw:
@@ -37433,7 +35048,7 @@ def validate_output_survives_the_pipe_scenario() -> int:
37433
35048
  redirected = run_keel(repo, *goal_args)
37434
35049
  if redirected.returncode != 0:
37435
35050
  report(
37436
- f"{label}: the fixture did not produce a goal projection to "
35051
+ f"{label}: the fixture did not produce a task-start result to "
37437
35052
  f"measure against; keel exited {redirected.returncode}."
37438
35053
  )
37439
35054
  report((redirected.stderr or redirected.stdout).strip()[:400])
@@ -41099,7 +38714,6 @@ def validate_a_count_is_derived_from_what_it_counts_scenario() -> int:
41099
38714
  "authorize",
41100
38715
  "precedents",
41101
38716
  "triage",
41102
- "delegation",
41103
38717
  "full_mode_paths",
41104
38718
  ):
41105
38719
  if expected not in names:
@@ -41447,6 +39061,142 @@ def validate_guidance_is_referenced_and_carries_no_criterion_scenario() -> int:
41447
39061
  return 0
41448
39062
 
41449
39063
 
39064
+ def validate_native_projections_removed_scenario() -> int:
39065
+ """Issue #414: Keel projects no goal, helper, task view, or subagent brief.
39066
+
39067
+ The owner removed the tooling built for the stance that subagents and native
39068
+ goals had to be shaped by Keel. Each surface is checked from the outside: the
39069
+ command a model would type, the doctor line it would read, and the plugin
39070
+ files a host would load. `keel project --event startup` is the control —
39071
+ a `keel project` that refused everything would pass the rest.
39072
+ """
39073
+ label = "native-projections-removed"
39074
+ with tempfile.TemporaryDirectory(prefix="keel-414-", ignore_cleanup_errors=True) as raw:
39075
+ repo = Path(raw)
39076
+ init = run_keel(repo, "--init", "--target", "claude")
39077
+ if init.returncode != 0:
39078
+ report(f"{label}: keel --init failed: {(init.stderr or init.stdout).strip()}")
39079
+ return 1
39080
+ for args in (
39081
+ ("project", "goal"),
39082
+ ("project", "tasks"),
39083
+ ("project", "helper"),
39084
+ ("project", "--event", "subagent-start"),
39085
+ ):
39086
+ result = run_keel(repo, *args)
39087
+ said = (result.stdout + result.stderr).lower()
39088
+ if result.returncode == 0:
39089
+ report(f"{label}: keel {' '.join(args)} exited 0.")
39090
+ return 1
39091
+ if "unknown" not in said and "unsupported" not in said:
39092
+ report(f"{label}: keel {' '.join(args)} was not refused as unknown: {(result.stdout or result.stderr).strip()[:120]!r}")
39093
+ return 1
39094
+ control = run_keel(repo, "project", "--event", "startup", "--target", "claude")
39095
+ if control.returncode != 0:
39096
+ report(f"{label}: keel project --event startup no longer works: {(control.stderr or control.stdout).strip()}")
39097
+ return 1
39098
+ doctor = run_keel(repo, "--doctor", "--target", "claude")
39099
+ for prefix in ("execution.goal", "execution.task-view", "delegation.", "helper "):
39100
+ hit = [line for line in doctor.stdout.splitlines() if line.strip().startswith(prefix)]
39101
+ if hit:
39102
+ report(f"{label}: doctor still prints {hit[0].strip()!r}.")
39103
+ return 1
39104
+ for gone in (
39105
+ ROOT / PLUGIN_ROOT / "skills/keel-run-single-task-goal",
39106
+ ROOT / "src/skills/keel-run-single-task-goal",
39107
+ ROOT / PLUGIN_ROOT / "agents",
39108
+ ):
39109
+ if gone.exists():
39110
+ report(f"{label}: {gone.relative_to(ROOT)} still ships.")
39111
+ return 1
39112
+ for manifest in (ROOT / ".claude-plugin/plugin.json", ROOT / PLUGIN_ROOT / ".codex-plugin/plugin.json"):
39113
+ if "agents" in json.loads(manifest.read_text(encoding="utf-8")):
39114
+ report(f"{label}: {manifest.relative_to(ROOT)} still names agents.")
39115
+ return 1
39116
+ if label not in {name for name, _ in SCENARIOS}:
39117
+ report(f"{label}: the scenario registry does not include it.")
39118
+ return 1
39119
+ report(f"{label} scenario passed.")
39120
+ return 0
39121
+
39122
+
39123
+ NATIVE_CAPABILITY_SUPPRESSIONS = (
39124
+ "unbounded subagent",
39125
+ "bounded helpers return read-only",
39126
+ "Implementation delegation is refused",
39127
+ "Delegation is refused with no active guard",
39128
+ "Target-native subagent gate",
39129
+ "One agent owns decisions",
39130
+ "may help with bounded assessment",
39131
+ "goal/task-view projection requires explicit authorization",
39132
+ "small contiguous task group",
39133
+ "in the current agent conversation",
39134
+ "inside the current agent session",
39135
+ "never infer continuity",
39136
+ "never native memory",
39137
+ "at most 2 attempts",
39138
+ "Read only the documents needed",
39139
+ "minimal read list",
39140
+ "load only that one",
39141
+ "do not load unrelated lenses",
39142
+ "read only the returned paths",
39143
+ )
39144
+ NATIVE_SUBAGENT_SENTENCE = "the model's choice and is treated as the main agent is"
39145
+ NATIVE_CONTINUATION_SENTENCE = "approved `tasks.md` in order"
39146
+
39147
+
39148
+ def validate_native_capabilities_unrestricted_scenario() -> int:
39149
+ """Issue #414: Keel neither suppresses nor steers the host's native capabilities.
39150
+
39151
+ The owner reviewed each sentence that told the model to stay in one session,
39152
+ take one task, keep subagents to a read-only role, read a minimal list, or
39153
+ stop after two attempts, and removed them. This holds every one of them out
39154
+ of every model-facing surface, and requires the two sentences that replaced
39155
+ the subagent and continuation rules where the agent reads them first.
39156
+ """
39157
+ label = "native-capabilities-unrestricted"
39158
+ surfaces = [
39159
+ ROOT / "AGENTS.md",
39160
+ ROOT / "assets/bootstrap/AGENTS.md",
39161
+ ROOT / "assets/openspec/schemas/keel-spec-driven/schema.yaml",
39162
+ ROOT / "openspec/schemas/keel-spec-driven/schema.yaml",
39163
+ ]
39164
+ for action in ("apply", "archive", "sync", "propose"):
39165
+ surfaces.append(ROOT / f".claude/commands/opsx/{action}.md")
39166
+ for name in ("apply-change", "archive-change", "sync-specs", "propose"):
39167
+ surfaces.append(ROOT / f".claude/skills/openspec-{name}/SKILL.md")
39168
+ surfaces.append(ROOT / f".codex/skills/openspec-{name}/SKILL.md")
39169
+ surfaces.extend(sorted((ROOT / "src/skills").glob("*/SKILL.md")))
39170
+ surfaces.extend(sorted((ROOT / PLUGIN_ROOT / "skills").glob("*/SKILL.md")))
39171
+ for surface in surfaces:
39172
+ if not surface.is_file():
39173
+ report(f"{label}: {surface.relative_to(ROOT)} is missing, so it cannot be checked.")
39174
+ return 1
39175
+ text = surface.read_text(encoding="utf-8")
39176
+ for phrase in NATIVE_CAPABILITY_SUPPRESSIONS:
39177
+ if phrase in text:
39178
+ report(f"{label}: {surface.relative_to(ROOT)} still says {phrase!r}.")
39179
+ return 1
39180
+ for first_read in (
39181
+ ROOT / "AGENTS.md",
39182
+ ROOT / "assets/bootstrap/AGENTS.md",
39183
+ ROOT / ".claude/commands/opsx/apply.md",
39184
+ ROOT / ".codex/skills/openspec-apply-change/SKILL.md",
39185
+ ):
39186
+ text = first_read.read_text(encoding="utf-8")
39187
+ if NATIVE_SUBAGENT_SENTENCE not in text:
39188
+ report(f"{label}: {first_read.relative_to(ROOT)} does not say a subagent is {NATIVE_SUBAGENT_SENTENCE!r}.")
39189
+ return 1
39190
+ if NATIVE_CONTINUATION_SENTENCE not in text:
39191
+ report(f"{label}: {first_read.relative_to(ROOT)} does not say the agent works through an {NATIVE_CONTINUATION_SENTENCE!r}.")
39192
+ return 1
39193
+ if label not in {name for name, _ in SCENARIOS}:
39194
+ report(f"{label}: the scenario registry does not include it.")
39195
+ return 1
39196
+ report(f"{label} scenario passed.")
39197
+ return 0
39198
+
39199
+
41450
39200
  def validate_tdd_strategy_guide_scenario() -> int:
41451
39201
  """Issue #389: the skill an executor loads to plan its checks says how to choose.
41452
39202
 
@@ -42761,16 +40511,10 @@ def validate_external_agent_brief_scenario() -> int:
42761
40511
  payload, out = brief("dsh", "helper", repo)
42762
40512
  if not refused(payload, out, "sandbox", "worktree", what="a dsh helper over the checkout"):
42763
40513
  return 1
42764
- # Implementation with no guard: the projection's own reason.
42765
- projected = run_keel(repo, "project", "--target", "claude", "--event", "subagent-start",
42766
- "--subagent-mode", "implementation", "--change", "demo",
42767
- "--task", "1.1", "--json", env=env)
42768
- expected = " ".join(json.loads(projected.stdout).get("reasons") or [])
40514
+ # Implementation with no guard is refused, naming the guard: the host's
40515
+ # guard never sees an external process, so this is its only check.
42769
40516
  payload, out = brief("codex", "implementation", repo)
42770
- if not expected:
42771
- report(f"{label} the projection gave no reason to compare against: {projected.stdout[:400]}")
42772
- return 1
42773
- if not refused(payload, out, expected, what="an unguarded implementation"):
40517
+ if not refused(payload, out, "requires an active write guard", what="an unguarded implementation"):
42774
40518
  return 1
42775
40519
  started = run_keel(repo, "gate", "task-start", "--change", "demo", "--task", "1.1",
42776
40520
  "--record", "--json", env=env)
@@ -43141,7 +40885,6 @@ SCENARIOS: tuple = (
43141
40885
  ("sync-surface-overlay", validate_sync_surface_overlay_scenario),
43142
40886
  ("openspec-surface-overlay", validate_openspec_surface_overlay_scenario),
43143
40887
  ("update-restores-overlays", validate_update_restores_overlays_scenario),
43144
- ("model-chosen-subagents", validate_model_chosen_subagents_scenario),
43145
40888
  ("uninstall", validate_uninstall_scenario),
43146
40889
  (
43147
40890
  "uninstall-removes-the-overlay",
@@ -43214,14 +40957,8 @@ SCENARIOS: tuple = (
43214
40957
  "triage-admits-from-the-repository",
43215
40958
  validate_triage_admits_from_the_repository_scenario,
43216
40959
  ),
43217
- ("delegation-declaration", validate_delegation_declaration_scenario),
43218
- ("delegation-inheritance", validate_delegation_inheritance_scenario),
43219
40960
  ("native-capability-scope", validate_native_capability_scope_scenario),
43220
- ("delegation-projection", validate_delegation_projection_scenario),
43221
- ("delegation-sole-authority", validate_delegation_sole_authority_scenario),
43222
- ("delegation-goal-budget", validate_delegation_goal_budget_scenario),
43223
40961
  ("delegation-guard-binds", validate_delegation_guard_binds_scenario),
43224
- ("delegation-never-weakens", validate_delegation_never_weakens_scenario),
43225
40962
  ("delegation-overlay", validate_delegation_overlay_scenario),
43226
40963
  ("delegation-resident-text", validate_delegation_resident_text_scenario),
43227
40964
  (
@@ -43424,18 +41161,6 @@ SCENARIOS: tuple = (
43424
41161
  ("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
43425
41162
  ("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
43426
41163
  ("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
43427
- ("native-goal-projection", validate_native_goal_projection_scenario),
43428
- ("native-goal-gate-order", validate_native_goal_gate_order_scenario),
43429
- ("native-goal-continuity", validate_native_goal_continuity_scenario),
43430
- ("native-helper-brief", validate_native_helper_brief_scenario),
43431
- ("native-helper-read-only", validate_native_helper_read_only_scenario),
43432
- ("native-goal-capabilities", validate_native_goal_capabilities_scenario),
43433
- ("single-task-goal-skill", validate_single_task_goal_skill_scenario),
43434
- ("single-task-goal-real-tasks", validate_single_task_goal_real_tasks_scenario),
43435
- ("native-goal-codex", validate_native_goal_codex_scenario),
43436
- ("native-goal-claude", validate_native_goal_claude_scenario),
43437
- ("native-helper-targets", validate_native_helper_targets_scenario),
43438
- ("native-single-task-matrix", validate_native_single_task_matrix_scenario),
43439
41164
  ("touch-write-guard", validate_touch_write_guard_scenario),
43440
41165
  ("push-branch-guard", validate_push_branch_guard_scenario),
43441
41166
  ("push-guard-redirects", validate_push_guard_redirects_scenario),
@@ -43475,7 +41200,6 @@ SCENARIOS: tuple = (
43475
41200
  ("domain-lens-scaffold", validate_domain_lens_scaffold_scenario),
43476
41201
  ("domain-lens-doctor", validate_domain_lens_doctor_scenario),
43477
41202
  ("plan-funnel-guidance", validate_plan_funnel_guidance_scenario),
43478
- ("native-tasks-view", validate_native_tasks_view_scenario),
43479
41203
  (
43480
41204
  "declared-paths-are-read-whole",
43481
41205
  validate_declared_paths_are_read_whole_scenario,
@@ -43588,6 +41312,8 @@ SCENARIOS: tuple = (
43588
41312
  validate_guidance_is_referenced_and_carries_no_criterion_scenario,
43589
41313
  ),
43590
41314
  ("tdd-strategy-guide", validate_tdd_strategy_guide_scenario),
41315
+ ("native-capabilities-unrestricted", validate_native_capabilities_unrestricted_scenario),
41316
+ ("native-projections-removed", validate_native_projections_removed_scenario),
43591
41317
  (
43592
41318
  "a-tier-declares-what-is-skipped",
43593
41319
  validate_a_tier_declares_what_is_skipped_scenario,