diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 292e060b..676fe062 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -27,6 +27,12 @@ jobs: with: python-version: '3.x' + - name: Install the configuration parser + # PyYAML is the runtime's one optional dependency, needed only to read a + # repository's `.code-cycle.yml`. Installed here so the configuration + # path is exercised rather than skipped. + run: python3 -m pip install --quiet pyyaml + - name: Validate skills and package metadata run: | python3 scripts/validate-package.py @@ -111,6 +117,9 @@ jobs: with: python-version: '3.x' + - name: Install the configuration parser + run: py -3 -m pip install --quiet pyyaml + - name: Validate package with Windows Python run: | py -3 scripts/validate-package.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b3e047f..8e9a27f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,6 +73,24 @@ All notable changes to this project are documented here. This project follows wrapper applies that to every result, so a started Orca worker can never be read as a finished stage. `dispatch()` now rebuilds its result with `dataclasses.replace`, so a new field cannot be dropped on the way out. +- The repository's configuration reaches routing: `run_cycle.py` loads + `.code-cycle.yml`, overlays `code_cycle.profiles` through `load_profiles`, and + passes the resolved profiles to `CycleRecorder`, which routes with them. + `code_cycle.repository.selector` supplies the repository when `--repo` is + absent. Until this, every run used the built-in profiles whatever the + repository declared. An unreadable configuration or an unknown profile name + stops the run before any dispatch; `--no-config` asks for the defaults. + Reading configuration needs PyYAML, the runtime's one optional dependency, + imported only when there is a file to parse. The repository and work item are + validated during planning through `telemetry.validate_reference`, the store's + own rule exported rather than copied, so a reference the store would refuse + never reaches an executor prompt; and `code_cycle`, `code_cycle.repository` + and `code_cycle.profiles` must be mappings, so valid YAML with the wrong shape + is refused rather than raising from whichever reader reached it first. + `load_profiles` refuses a declared profile that is not a mapping and a + `primary` or `fallback` that is not a target string, naming the profile: one + used to raise `TypeError` past every handler, and the other was carried into a + `Profile` as whatever it was. - `scripts/run_cycle.py`, the production wiring: probe once, label the work, then `implement → review → (resolve → rereview)*` with every stage through `CycleRecorder.stage()`. It decides nothing — no cost model, no learning — and diff --git a/README.md b/README.md index 72163f6f..5fea8526 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,19 @@ python3 ~/.code-cycle/runtime/run_cycle.py \ --repo owner/name --task API-7 --difficulty 2 --verifiability auto ``` +Reading `.code-cycle.yml` needs PyYAML, the runtime's one optional dependency +(`pip install pyyaml`). Nothing else in the toolkit needs it: a repository with +no configuration file runs on the standard library alone, and when a file is +present but the parser is not, the run stops and says so rather than quietly +using the defaults. + +It reads `.code-cycle.yml` from the working directory: `code_cycle.profiles` +overlays the built-in profiles, and `code_cycle.repository.selector` supplies +the repository when `--repo` is not given. A configuration that exists and +cannot be read stops the run instead of falling back to the defaults, because a +row recorded under the defaults while a file says otherwise describes a policy +nobody chose. `--no-config` asks for the defaults deliberately. + It probes the executors once, labels the work before routing anything, and runs `implement → review → (resolve → rereview)*` with every stage going through the recorder, so no dispatch can happen without leaving a row. It reads each diff --git a/docs/instrumentation.md b/docs/instrumentation.md index a3746704..738dd7d1 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -497,6 +497,29 @@ first version of this driver reviewed work that was still being written. The declaration is on the class, and the dispatch wrapper applies it, so an adapter cannot report finished work it only launched by forgetting a keyword. +The driver loads the configuration and the recorder only receives what was +resolved: `code_cycle.profiles` overlaid on the defaults by `load_profiles`, and +`code_cycle.repository.selector` when no repository was named. `CycleRecorder` +does not look for a file itself — a component that reads configuration on its +own can disagree with its caller about what the configuration says, and both +would be recording rows. An unknown profile name stops the run before anything +is dispatched, because learning that afterwards means paying for a cycle to find +a typo. + +The repository and work item are checked the same way and at the same moment, +through `telemetry.validate_reference` — the store's own rule, exported rather +than copied, because two validators agree until one of them is edited. A +reference the store will refuse is one no stage should run under: that stage is +dispatched, paid for, and then its row cannot be written, so the run happens and +leaves no trace of having happened. Configuration shape is checked with it: +`code_cycle`, `code_cycle.repository` and `code_cycle.profiles` must be mappings, +so a valid YAML document with the wrong shape is a stated refusal rather than a +traceback from whichever reader reached it first. `load_profiles` checks the +shapes below those names — every declared profile is a mapping, every `primary` +and `fallback` a target string — because a declared `primary: 3` used to be +carried into a `Profile` as the integer 3, and only something trying to route +with it ever found out. + The probe map is taken once and handed to the recorder. Without it each dispatch probes again on its own, so an availability could change between two stages with nothing recording that it had — and the decisions on either side stop being diff --git a/scripts/cycle.py b/scripts/cycle.py index e7e5cc6a..1158c139 100644 --- a/scripts/cycle.py +++ b/scripts/cycle.py @@ -92,6 +92,7 @@ def __init__( mode: RoutingMode = RoutingMode.PRODUCTION, policy: ReadinessPolicy | None = None, probes: dict | None = None, + profiles: dict | None = None, ) -> None: self.telemetry = telemetry self.repo_id = repo_id @@ -106,6 +107,11 @@ def __init__( # between two stages with nothing recording that it had — and the # decisions on either side of the change become unexplainable. self.probes = probes + # Already resolved by whoever loaded the repository's configuration. + # The recorder does not go looking for a file: a component that reads + # configuration on its own is one that can disagree with the caller + # about what the configuration says. + self.profiles = profiles self.iteration = 0 self.stages: list[StageOutcome] = [] @@ -120,7 +126,7 @@ def stage(self, role: str, task: str, **dispatch_kwargs) -> StageOutcome: for attempt in range(2): decision = route(role, self.signals, self.availability, - mode=self.mode, profiles=None) + mode=self.mode, profiles=self.profiles) if decision.blocked: outcome.decision = decision outcome.rows.append(self._record(role, decision, None)) diff --git a/scripts/router.py b/scripts/router.py index 822a5d2f..3b978665 100644 --- a/scripts/router.py +++ b/scripts/router.py @@ -200,10 +200,23 @@ def load_profiles(config: dict | None = None) -> dict[str, Profile]: A repository declares only what it wants to change. An unknown profile name is refused rather than ignored: a typo that silently routes nowhere is worse than one that stops the run. + + The same applies to every shape below the name. A declaration is a mapping + of target strings, and anything else is refused here — where the file is + being read and the error can name the profile — rather than surviving into + a `Profile` that only fails when something tries to route with it. A + declared `primary: 3` used to be accepted and carried as the integer 3. """ declared = {} if config: - declared = config.get("code_cycle", {}).get("profiles", {}) or {} + section = config.get("code_cycle") + if section is not None and not isinstance(section, dict): + # Silently reading the defaults out of a broken file would route by + # a policy nobody declared, which is the failure this whole function + # exists to prevent one level up. + raise RouterError( + f"code_cycle must be a mapping, not {type(section).__name__}") + declared = (section or {}).get("profiles") or {} if not isinstance(declared, dict): raise RouterError("code_cycle.profiles must be a mapping") @@ -211,19 +224,31 @@ def load_profiles(config: dict | None = None) -> dict[str, Profile]: if unknown: raise RouterError("unknown profile names: " + ", ".join(unknown)) + for name, spec in declared.items(): + if not isinstance(spec, dict): + raise RouterError( + f"profile {name!r} must be a mapping of targets, not " + f"{type(spec).__name__}") + for key in ("primary", "fallback"): + value = spec.get(key) + if value is None: + continue + if not isinstance(value, str) or not value.strip(): + raise RouterError( + f"profile {name!r} declares a {key} that is not a target " + f"string: {value!r}") + profiles = {} for name, spec in DEFAULT_PROFILES.items(): - merged = {**spec, **(declared.get(name) or {})} + merged = {**spec, **declared.get(name, {})} primary = merged.get("primary") if not primary: raise RouterError(f"profile {name!r} has no primary target") fallback = merged.get("fallback") profiles[name] = Profile( name=name, - primary=parse_target(primary) if isinstance(primary, str) else primary, - fallback=(parse_target(fallback) if isinstance(fallback, str) else fallback) - if fallback - else None, + primary=parse_target(primary), + fallback=parse_target(fallback) if fallback else None, ) return profiles diff --git a/scripts/run_cycle.py b/scripts/run_cycle.py index 8d5685f5..c8adcc9e 100644 --- a/scripts/run_cycle.py +++ b/scripts/run_cycle.py @@ -38,8 +38,16 @@ from cycle import CycleRecorder, StageOutcome from executors import DispatchResult, ReadinessPolicy, Registry -from router import RoutingMode, TaskSignals -from telemetry import Telemetry, default_database_path +from router import RouterError, RoutingMode, TaskSignals, load_profiles +from telemetry import ( + Telemetry, + TelemetryError, + default_database_path, + validate_reference, +) + +#: The repository's own declaration of how it wants to be run. +CONFIG_NAME = ".code-cycle.yml" #: The skill each role runs, as the executor is told to invoke it. SKILL_FOR_ROLE = { @@ -68,6 +76,59 @@ class CycleDriverError(RuntimeError): """The driver was asked for something it cannot honestly do.""" +def load_config(path: Path) -> dict: + """Read `.code-cycle.yml`, or say exactly why it could not be read. + + The toolkit is otherwise pure standard library, and a repository without a + configuration file needs no parser at all — so PyYAML is required only when + there is something to parse. Refusing loudly beats running with the built-in + defaults while a file on disk says otherwise: the whole point of recording a + run is that the row describes the policy that was actually in force. + """ + try: + import yaml + except ImportError as exc: # pragma: no cover - depends on the environment + raise CycleDriverError( + f"{path} exists but PyYAML is not installed, so its configuration " + "cannot be read; install PyYAML or pass --no-config to accept the " + "built-in defaults" + ) from exc + + try: + config = yaml.safe_load(path.read_text(encoding="utf-8")) + except Exception as exc: + raise CycleDriverError(f"{path} could not be read: {exc}") from exc + + if config is None: + return {} + if not isinstance(config, dict): + raise CycleDriverError(f"{path} must contain a mapping at the top level") + + # The shape, not only the top level. A valid YAML document can still say + # `code_cycle: not-a-mapping`, and every reader below would then crash on + # its own `.get` — a traceback where a stated refusal belongs. + for key in ("code_cycle", "code_cycle.repository", "code_cycle.profiles"): + section, value = config, None + for part in key.split("."): + if not isinstance(section, dict): + break + value = section.get(part) + section = value + if value is not None and not isinstance(value, dict): + raise CycleDriverError( + f"{path}: {key} must be a mapping, not " + f"{type(value).__name__}") + return config + + +def repository_of(config: dict) -> str | None: + """`code_cycle.repository.selector`, when the repository declares one.""" + section = config.get("code_cycle") + repository = section.get("repository") if isinstance(section, dict) else None + selector = repository.get("selector") if isinstance(repository, dict) else None + return selector if isinstance(selector, str) and selector else None + + @dataclass class CycleReport: """What the cycle did, and why it stopped there.""" @@ -147,6 +208,7 @@ def run_cycle( signals: TaskSignals, telemetry: Telemetry, *, + profiles: dict | None = None, registry: Registry | None = None, availability: dict | None = None, mode: RoutingMode = RoutingMode.PRODUCTION, @@ -167,7 +229,7 @@ def run_cycle( recorder = CycleRecorder( telemetry, repo_id, task_id, signals, availability=availability, registry=registry, mode=mode, policy=policy, - probes=probes, + probes=probes, profiles=profiles, ) report = CycleReport(repo_id=repo_id, task_id=task_id) dispatch_kwargs = {} @@ -284,12 +346,68 @@ def _why(outcome: StageOutcome) -> str: return f"{outcome.role} on {result.executor} {result.outcome.value}: {result.detail}" +def plan(args) -> tuple[str, dict]: + """Everything the configuration decides, decided before anything runs. + + An unknown profile name is refused by `load_profiles`, and learning that + after a stage has already run would mean paying for a cycle to discover a + typo. So this happens first, and it raises rather than falling back. + """ + config = resolve_config(args) + + repo = args.repo or repository_of(config) + if not repo: + raise CycleDriverError( + "no repository: pass --repo or declare " + f"code_cycle.repository.selector in {CONFIG_NAME}") + + # Checked by the store's own rule, here rather than at the first row. A + # reference the store will refuse is one no stage should be dispatched + # under: that run is paid for and its row cannot be written. + for field, value in (("repo_id", repo), ("task_id", getattr(args, "task", None))): + if value is None: + continue + try: + validate_reference(field, value) + except TelemetryError as error: + raise CycleDriverError(str(error)) from error + + try: + profiles = load_profiles(config) + except RouterError as error: + raise CycleDriverError(str(error)) from error + return repo, profiles + + +def resolve_config(args) -> dict: + """Which configuration this run is under, and none by accident. + + An explicit `--config` that is not there is an error, because somebody named + it. A file found beside the work is used when it exists. `--no-config` is + the only way to run on the built-in defaults while a file sits next to the + work, and it has to be asked for. + """ + if args.no_config: + if args.config: + raise CycleDriverError("--config and --no-config contradict each other") + return {} + if args.config: + path = Path(args.config) + if not path.is_file(): + raise CycleDriverError(f"no configuration at {path}") + return load_config(path) + path = Path(args.cwd or ".") / CONFIG_NAME + return load_config(path) if path.is_file() else {} + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="run_cycle", description="Run one work item through a recorded cycle.", ) - parser.add_argument("--repo", required=True, help="repository identifier, owner/name") + parser.add_argument("--repo", default=None, + help=("repository identifier, owner/name; defaults to " + f"code_cycle.repository.selector in {CONFIG_NAME}")) parser.add_argument("--task", required=True, help="work item identifier") # Labelled before routing, never after: choosing a model from a judgement # and then measuring by model measures the routing rather than the models. @@ -306,15 +424,25 @@ def main(argv: list[str] | None = None) -> int: help="seconds one dispatch may take") parser.add_argument("--database", default=None, help=f"telemetry database (default: {default_database_path()})") + parser.add_argument("--config", default=None, + help=f"path to {CONFIG_NAME} (default: alongside the work)") + parser.add_argument("--no-config", action="store_true", + help="run on the built-in defaults, ignoring any configuration") args = parser.parse_args(argv) + try: + repo, profiles = plan(args) + except CycleDriverError as error: + parser.error(str(error)) + telemetry = Telemetry(Path(args.database) if args.database else None) report = run_cycle( - args.repo, args.task, + repo, args.task, TaskSignals(difficulty=args.difficulty, verifiability=args.verifiability, security_sensitive=args.security_sensitive), telemetry, + profiles=profiles, mode=RoutingMode[args.mode.upper()], max_iterations=args.max_iterations, cwd=args.cwd, diff --git a/scripts/telemetry.py b/scripts/telemetry.py index ced33c5a..26adf041 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -320,6 +320,20 @@ def explain(self) -> str: ) +def validate_reference(field: str, value): + """Apply this store's rule for a field, before anything is spent on it. + + The same check `record_stage` would make, exported so a caller can make it + first. A repository or work item that this store will refuse is worth + refusing before a stage is dispatched under it: the alternative is an + executor run, paid for, whose row cannot be written. + + It is deliberately the same function rather than a second copy of the + rules. Two validators agree until one of them is edited. + """ + return _checked(field, value) + + def _checked(key: str, value): """Return the value if its shape matches what the field may hold. diff --git a/skills/cc-orchestrator/SKILL.md b/skills/cc-orchestrator/SKILL.md index 6959b6cb..e6e6c60b 100644 --- a/skills/cc-orchestrator/SKILL.md +++ b/skills/cc-orchestrator/SKILL.md @@ -237,6 +237,12 @@ python3 /run_cycle.py --repo owner/name --task API-7 \ --difficulty 2 --verifiability auto ``` +It reads `.code-cycle.yml` from the working directory, so `code_cycle.profiles` +is what routes and `code_cycle.repository.selector` supplies the repository when +`--repo` is absent. A configuration that cannot be read stops the run rather +than falling back to the defaults: a row recorded under the defaults while a +file says otherwise describes a policy nobody chose. + It reads a review's verdict from the structured result it asks the executor to emit, and stops when that block is absent rather than inferring a verdict from a successful exit. Use it, or do exactly what it does; an orchestration that routes diff --git a/tests/test_cycle.py b/tests/test_cycle.py index 91f8da5d..9127d9d0 100644 --- a/tests/test_cycle.py +++ b/tests/test_cycle.py @@ -292,6 +292,39 @@ def test_without_them_a_dispatch_has_to_find_out_for_itself(self) -> None: self.assertGreater(codex.probes, 0) +class ProfileTests(CycleTestCase): + """Whoever loaded the configuration decides; the recorder only carries it.""" + + def test_the_profiles_it_was_given_are_the_ones_it_routes_with(self) -> None: + profiles = router.load_profiles({"code_cycle": {"profiles": { + "cheap_coder": {"primary": "claude:anthropic/claude-opus-5 high"}}}}) + codex, claude = ScriptedAdapter("codex"), ScriptedAdapter("claude") + recorder = self.recorder([codex, claude], profiles=profiles) + + outcome = recorder.stage("implement", "work") + + self.assertEqual("claude", outcome.decision.target.executor) + self.assertEqual("claude-opus-5", outcome.decision.target.model) + self.assertEqual([], codex.dispatched) + + def test_without_them_the_built_in_defaults_apply(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + + outcome = recorder.stage("implement", "work") + + self.assertEqual("codex", outcome.decision.target.executor) + + def test_it_does_not_go_looking_for_a_configuration_file(self) -> None: + """A component that reads configuration on its own can disagree with + the caller about what the configuration says.""" + import inspect + + source = inspect.getsource(cy) + + self.assertNotIn("code-cycle.yml", source) + self.assertNotIn("load_profiles", source) + + class BlockedRoutingTests(CycleTestCase): def test_a_routing_that_never_reached_an_executor_still_leaves_a_row(self) -> None: """A run that stopped here would otherwise leave no trace of why.""" diff --git a/tests/test_router.py b/tests/test_router.py index b2abeaa3..110b5a81 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -234,5 +234,54 @@ def test_a_target_round_trips_readably(self) -> None: ) + +class DeclaredProfileShapeTests(unittest.TestCase): + """A declaration is a mapping of target strings, refused here or never.""" + + def load(self, profiles): + return router.load_profiles({"code_cycle": {"profiles": profiles}}) + + def test_a_profile_that_is_not_a_mapping_is_refused(self) -> None: + with self.assertRaises(router.RouterError) as refused: + self.load({"cheap_coder": "nope"}) + + self.assertIn("must be a mapping of targets", str(refused.exception)) + + def test_a_target_that_is_not_a_string_is_refused(self) -> None: + """It used to be carried through: `primary: 3` became the integer 3, + and only something trying to route with it ever found out.""" + for key, value in (("primary", 3), ("fallback", ["a", "b"]), + ("primary", {"model": "x"})): + with self.subTest(key=key, value=value): + with self.assertRaises(router.RouterError) as refused: + self.load({"cheap_coder": {"primary": "codex:openai/gpt-5.6-luna high", + key: value}}) + + self.assertIn("not a target string", str(refused.exception)) + + def test_an_empty_target_string_is_refused(self) -> None: + with self.assertRaises(router.RouterError): + self.load({"cheap_coder": {"primary": " "}}) + + def test_a_malformed_target_string_is_still_refused(self) -> None: + with self.assertRaises(router.RouterError) as refused: + self.load({"cheap_coder": {"primary": "nonsense"}}) + + self.assertIn("executor:provider/model effort", str(refused.exception)) + + def test_a_well_formed_declaration_still_loads(self) -> None: + profiles = self.load({"cheap_coder": { + "primary": "claude:anthropic/claude-sonnet-5 high", + "fallback": "codex:openai/gpt-5.6-luna high"}}) + + self.assertEqual("claude-sonnet-5", profiles["cheap_coder"].primary.model) + self.assertEqual("gpt-5.6-luna", profiles["cheap_coder"].fallback.model) + + def test_a_section_that_is_not_a_mapping_does_not_raise_its_own_error(self) -> None: + """`code_cycle: not-a-mapping` reached `.get` on a string.""" + with self.assertRaises(router.RouterError): + router.load_profiles({"code_cycle": "not-a-mapping"}) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index 6fe6787b..fe3a6651 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -161,5 +161,263 @@ def test_an_echoed_prompt_does_not_shadow_the_real_block(self) -> None: self.assertEqual(rc.APPROVED_END, report.status) +class Args: + """What argparse would have produced, without the parser.""" + + def __init__(self, **fields) -> None: + self.repo = None + self.task = "API-7" + self.cwd = None + self.config = None + self.no_config = False + self.__dict__.update(fields) + + +try: # The runtime's one optional dependency, and only for reading a config. + import yaml # noqa: F401 + HAS_YAML = True +except ImportError: # pragma: no cover - depends on the environment + HAS_YAML = False + + +@unittest.skipUnless(HAS_YAML, "reading a configuration needs PyYAML") +class ConfigurationTests(RunCycleTestCase): + """The repository's declaration reaches the router, or it decides nothing.""" + + def setUp(self) -> None: + super().setUp() + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.directory = Path(directory.name) + + def write(self, body: str) -> Path: + path = self.directory / ".code-cycle.yml" + path.write_text(body, encoding="utf-8") + return path + + def profiles_from(self, body: str) -> dict: + return rc.plan(Args(cwd=str(self.directory), repo="owner/api"))[1] + + def test_a_declared_profile_is_what_actually_runs(self) -> None: + """The whole point: without this the row describes a policy nobody chose.""" + self.write(""" +code_cycle: + profiles: + cheap_coder: + primary: claude:anthropic/claude-sonnet-5 high +""") + codex, claude = Talker("codex"), Talker("claude") + + report = rc.run_cycle( + "owner/api", "API-7", router.TaskSignals(), self.store, + profiles=self.profiles_from(""), + registry=ex.Registry([codex, claude]), + availability={"codex": ex.Availability.READY, + "claude": ex.Availability.READY}, + ) + + implement = report.stages[0] + self.assertEqual("claude", implement.result.executor) + self.assertEqual("claude-sonnet-5", implement.decision.target.model) + self.assertEqual([], codex.dispatched) + + def test_without_a_declaration_the_defaults_are_untouched(self) -> None: + report = rc.run_cycle( + "owner/api", "API-7", router.TaskSignals(), self.store, + profiles=rc.plan(Args(no_config=True, repo="owner/api"))[1], + registry=ex.Registry([Talker("codex"), Talker("claude")]), + availability={"codex": ex.Availability.READY, + "claude": ex.Availability.READY}, + ) + + implement = report.stages[0] + self.assertEqual("codex", implement.result.executor) + self.assertEqual("gpt-5.6-luna", implement.decision.target.model) + + def test_the_fallback_is_the_configured_one_not_the_built_in_one(self) -> None: + """A reroute must stay inside the policy the repository declared.""" + self.write(""" +code_cycle: + profiles: + cheap_coder: + primary: codex:openai/gpt-5.6-luna high + fallback: claude:anthropic/claude-opus-5 high +""") + codex = ScriptedAdapter( + "codex", outcomes=[(ex.DispatchOutcome.BLOCKED, "operating_quota")]) + claude = Talker("claude") + + report = rc.run_cycle( + "owner/api", "API-7", router.TaskSignals(), self.store, + profiles=self.profiles_from(""), + registry=ex.Registry([codex, claude]), + availability={"codex": ex.Availability.READY, + "claude": ex.Availability.READY}, + ) + + fallback = report.stages[0].attempts[1][0] + self.assertEqual("claude-opus-5", fallback.target.model) + self.assertTrue(fallback.used_fallback) + + def test_an_explicit_repository_wins_over_the_declared_one(self) -> None: + self.write(""" +code_cycle: + repository: + selector: org-name/service +""") + repo, _ = rc.plan(Args(cwd=str(self.directory), repo="owner/api")) + + self.assertEqual("owner/api", repo) + + def test_the_declared_repository_is_used_when_none_is_given(self) -> None: + self.write(""" +code_cycle: + repository: + selector: org-name/service +""") + repo, _ = rc.plan(Args(cwd=str(self.directory))) + + self.assertEqual("org-name/service", repo) + + def test_no_repository_anywhere_is_an_error_before_anything_runs(self) -> None: + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory))) + + self.assertIn("no repository", str(refused.exception)) + + def test_an_unknown_profile_name_stops_the_run_before_dispatch(self) -> None: + self.write(""" +code_cycle: + profiles: + cheep_coder: + primary: codex:openai/gpt-5.6-luna high +""") + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory), repo="owner/api")) + + self.assertIn("unknown profile names", str(refused.exception)) + + def test_unreadable_configuration_is_refused_not_ignored(self) -> None: + """Running on the defaults while a file says otherwise would record a + policy nobody declared.""" + self.write("code_cycle: [this is not a mapping") + + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory), repo="owner/api")) + + self.assertIn("could not be read", str(refused.exception)) + + def test_a_named_configuration_that_is_not_there_is_an_error(self) -> None: + with self.assertRaises(rc.CycleDriverError): + rc.plan(Args(config=str(self.directory / "absent.yml"), repo="owner/api")) + + def test_the_defaults_can_be_asked_for_explicitly(self) -> None: + self.write(""" +code_cycle: + profiles: + cheap_coder: + primary: claude:anthropic/claude-sonnet-5 high +""") + _, profiles = rc.plan(Args(cwd=str(self.directory), repo="owner/api", + no_config=True)) + + self.assertEqual("codex", profiles["cheap_coder"].primary.executor) + + def test_a_selector_the_store_would_refuse_is_refused_first(self) -> None: + """Otherwise a stage is dispatched, paid for, and its row cannot be + written — the run happens and leaves no trace of having happened.""" + self.write(""" +code_cycle: + repository: + selector: "bad selector" +""") + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory))) + + self.assertIn("not a reference", str(refused.exception)) + + def test_a_credential_shaped_selector_never_reaches_a_prompt(self) -> None: + self.write(""" +code_cycle: + repository: + selector: "ghp_000000000000000000" +""") + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory))) + + self.assertIn("credential prefix", str(refused.exception)) + + def test_an_explicit_repository_is_checked_the_same_way(self) -> None: + with self.assertRaises(rc.CycleDriverError): + rc.plan(Args(no_config=True, repo="not a repository")) + + def test_the_work_item_is_checked_too(self) -> None: + """Same class, same cost: a task id the store refuses wastes the stage.""" + with self.assertRaises(rc.CycleDriverError): + rc.plan(Args(no_config=True, repo="owner/api", task="API 7")) + + def test_nothing_is_dispatched_when_planning_refuses(self) -> None: + self.write(""" +code_cycle: + repository: + selector: "bad selector" +""") + codex, claude = Talker("codex"), Talker("claude") + + with self.assertRaises(rc.CycleDriverError): + repo, profiles = rc.plan(Args(cwd=str(self.directory))) + rc.run_cycle(repo, "API-7", router.TaskSignals(), self.store, + profiles=profiles, registry=ex.Registry([codex, claude]), + availability={"codex": ex.Availability.READY, + "claude": ex.Availability.READY}) + + self.assertEqual([], codex.dispatched) + self.assertEqual([], claude.dispatched) + self.assertEqual([], self.store.rows("owner/api")) + + def test_a_section_that_is_not_a_mapping_is_a_stated_refusal(self) -> None: + """Valid YAML, wrong shape. It used to reach a `.get` and traceback.""" + for body in ("code_cycle: not-a-mapping\n", + "code_cycle:\n repository: nope\n", + "code_cycle:\n profiles: nope\n"): + with self.subTest(body=body): + self.write(body) + + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory))) + + self.assertIn("must be a mapping", str(refused.exception)) + + def test_a_malformed_profile_entry_is_a_stated_refusal(self) -> None: + """Valid YAML, valid section, wrong entry. It used to reach a merge and + raise TypeError past every handler the CLI has.""" + for body in ("code_cycle:\n profiles:\n cheap_coder: nope\n", + "code_cycle:\n profiles:\n cheap_coder:\n primary: 3\n", + ("code_cycle:\n profiles:\n cheap_coder:\n" + " primary: codex:openai/gpt-5.6-luna high\n" + " fallback: [a, b]\n")): + with self.subTest(body=body): + self.write(body) + + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory), repo="owner/api")) + + self.assertIn("profile 'cheap_coder'", str(refused.exception)) + + def test_a_declared_target_that_is_not_a_target_never_becomes_one(self) -> None: + """`primary: 3` was accepted and carried as the integer 3.""" + self.write("code_cycle:\n profiles:\n cheap_coder:\n primary: 3\n") + + with self.assertRaises(rc.CycleDriverError) as refused: + rc.plan(Args(cwd=str(self.directory), repo="owner/api")) + + self.assertIn("not a target string", str(refused.exception)) + + def test_asking_for_both_at_once_is_refused(self) -> None: + with self.assertRaises(rc.CycleDriverError): + rc.plan(Args(config=str(self.write("code_cycle: {}")), + no_config=True, repo="owner/api")) + + if __name__ == "__main__": unittest.main()