Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions docs/instrumentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion scripts/cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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] = []

Expand All @@ -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))
Expand Down
37 changes: 31 additions & 6 deletions scripts/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,30 +200,55 @@ 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")

unknown = sorted(set(declared) - set(DEFAULT_PROFILES))
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

Expand Down
138 changes: 133 additions & 5 deletions scripts/run_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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,
Expand All @@ -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 = {}
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down
Loading
Loading