## Summary
Ruff carried no complexity rule, so nothing bounded the number of paths through
a function. This adds `C901` with a ceiling chosen to stop the untestable and
nothing else.
**What the number means.** Cyclomatic complexity is the count of linearly
independent paths through a function, which makes it the floor on how many cases
a suite needs to walk them all. A body with a hundred of them has paths nobody
will ever write a case for, and those paths are first executed in production.
That is the failure this rule prevents; it is not a style preference.
Two properties of the metric matter for reading the numbers below. A nested
function's score is counted into its enclosing function as well as reported on
its own, so an outer function with no branches of its own scores one more than
the inner function it holds. And Ruff reports `C901` only when the score is
*greater* than `max-complexity`, so a function at exactly 40 passes a ceiling of
40 and needs no suppression.
**Where 40 comes from.** The measured distribution, not McCabe's recommendation
of 10:
| max-complexity | functions flagged |
|---|---|
| 10 | 253 |
| 25 | 26 |
| 30 | 17 |
| **40** | **9** |
| 50 | 5 |
Ten would flag 253 functions and be switched off within the week. Forty is not a
claim that 39 is fine -- it is where a function stops being complex and starts
being untestable. Tightening later means lowering the number, which is a
reviewed edit to `pyproject.toml`.
**The nine over the ceiling.** Each carries a `noqa: C901` naming its actual
score. Seven are in `raven/`, two in the oncall-flow plugin under `agents/`:
```
100 raven/agent/loop/turn_path.py _run_agent_loop
87 raven/cli/gateway_commands.py register
86 raven/cli/gateway_commands.py gateway
69 agents/raven-oncall/.../oncall_flow/tools/ops.py execute
68 raven/cli/gateway_commands.py run
54 agents/raven-oncall/.../oncall_flow/tools/ops.py execute
47 raven/agent/loop/turn_path.py _process_message
46 raven/config/loader.py _migrate_config
41 raven/agent/loop/turn_path.py _run_turn
```
A tenth suppression sits on `benchmarks/proactivity_eval/runners/_common/longrun_adapters.py`
(`tick_to`, 41). `benchmarks/` is outside `PYTHON_LINT_TARGETS` and so outside
CI, but inside what the pre-commit Ruff hook sees on a changed file -- marking it
means the gate does not ambush whoever next edits that adapter.
**Nine entries, fewer distinct problems.** In `gateway_commands.py` the three
are nested inside each other at indent 0, 4 and 8: `run` at 68 is the body,
`gateway` adds its own branches on top, and `register` contributes about one. In
`turn_path.py` the three are sibling methods, but `_run_turn` holds ten nested
callbacks (`on_token`, `on_tool`, `on_progress` and so on) which is most of its
41. The one that is a large body by itself is `_run_agent_loop`: 1134 lines with
only two nested functions, so its 100 is its own.
Per-function rather than per-file, on purpose: a whole-file ignore on
`gateway_commands.py` would let a new 80-path function in the same file through,
while these entries do not. The score is in the comment so the debt is visible
where the code is, not parked in a config file.
Nothing has to be refactored to land this. Normal work is undisturbed unless
someone writes a forty-one-path function.
**Why the PLR09xx rules are left out.** They count arguments (230 occurrences
here), branches (125), statements (78) and returns (81). All four are proxies
for what `C901` measures directly, so adding them would report one fact four
times and bury the signal under 230 argument-count warnings.
## Type
- [ ] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [x] Other
Other: a lint gate plus the `noqa` entries that let it land green. No runtime
code changes; every production edit is an end-of-line comment.
## Verification
Verified against the lint roster read out of the Makefile
(`PYTHON_LINT_TARGETS = raven evolver agents plugins-dist tests scripts`) rather
than a chosen subset, and then against the whole tree. The first revision of
this MR checked only `raven/` and went red in CI on the two `agents/` functions;
that is what the roster-wide check exists to prevent.
```
$ uv run --frozen --python 3.12 --extra dev ruff check --no-cache \
raven evolver agents plugins-dist tests scripts
All checks passed!
$ uv run --frozen --python 3.12 --extra dev ruff check --no-cache .
All checks passed!
$ uv run --frozen --python 3.12 --extra dev ruff check --no-cache \
--extend-select RUF100 raven evolver agents plugins-dist tests scripts
(no unused C901 directive)
$ uv run --frozen --python 3.12 --extra dev ruff format --check \
raven evolver agents plugins-dist tests scripts
1886 files already formatted
$ uv run --frozen --python 3.12 pytest tests/ -q -k "turn_path or gateway or loader or console or config_precedence"
511 passed, 19 skipped
$ uv run --frozen --python 3.12 lint-imports
Contracts: 9 kept, 0 broken.
$ make check-commits COMMIT_RANGE=origin/main..HEAD
exit 0
```
The 19 skips are pre-existing and environmental: `test_provider_resolution_invariants.py`
skips its gateway-only cases when no gateway is configured.
Checked in the failing direction, since a gate never seen red is not known to
work. A fresh forty-branch function appended to `config/loader.py` is reported,
and the `noqa` on `_migrate_config` in the same file keeps holding rather than
being swallowed by it:
```
raven/config/loader.py:1088:5: C901 `_probe_over_ceiling` is too complex (41 > 40)
Found 1 error.
```
The probe was reverted. Note for the reviewer: reverting that file also reverted
its `noqa`, which the roster-wide check caught immediately.
One entry was removed after review rather than kept: `settings_usage` scores
exactly 40, which a ceiling of 40 does not flag, so its suppression was dead.
`--extend-select RUF100` reports such a directive as unused, and keeping it would
have defeated the documented tightening path -- lowering the number later would
have left that function exempt with nothing to show it.
The production diff is comment-only and can be read as such:
```
- async def _run_agent_loop(
+ async def _run_agent_loop( # noqa: C901 (cc 100: pre-existing, above the ceiling)
```
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed
No user-facing surface changes.
## Risk
- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes
No behaviour change: every production edit is an end-of-line comment, and the
diff can be verified as such. The risk this carries is a false sense of
coverage, which is why the rationale in `pyproject.toml` states what the ceiling
does not mean. Two limits of the metric are worth a reviewer knowing: it does
not see nesting depth (five sequential `if`s and five nested ones both score 6),
and in Ruff's implementation boolean operators, ternaries and comprehension
conditions do not count at all. It is a filter for the untestable, not a
readability score.
Rollback is reverting the commits. Loosening instead of reverting is a one-line
change to `max-complexity`, which is the intended escape if the gate turns out
to obstruct real work.
## Related Issues
N/A
140 lines
4.9 KiB
Python
140 lines
4.9 KiB
Python
"""Factories for the tool face code-flow contributes (raven-plugin.toml names them).
|
|
|
|
Every factory reads the flow slice's ``tools`` section and declines (returns
|
|
None) when that section leaves the face off or the slice does not parse, so a
|
|
product that wants the host's own tools simply says so and gets them.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING
|
|
|
|
from loguru import logger
|
|
from pydantic import ValidationError
|
|
|
|
from code_flow.config import FlowConfig, ToolsConfig
|
|
from code_flow.tools.exec import SPILL_SUBDIR, CodeExecTool, CodeExecutor
|
|
from code_flow.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool
|
|
from code_flow.tools.read_state import owner_for
|
|
from code_flow.tools.search import GlobTool
|
|
from code_flow.tools.todo import STORES, TodoTool
|
|
|
|
if TYPE_CHECKING:
|
|
from raven.plugins.context import PluginContext
|
|
|
|
|
|
def _face(ctx: "PluginContext", seat: str) -> ToolsConfig | None:
|
|
"""The tool face's own section of the flow slice, or None to decline."""
|
|
try:
|
|
flow = FlowConfig.from_slice(dict(ctx.config or {}))
|
|
except ValidationError as exc:
|
|
logger.warning("code-flow: config slice is malformed; declining {}: {}", seat, exc)
|
|
return None
|
|
if not flow.tools.enabled:
|
|
return None
|
|
return flow.tools
|
|
|
|
|
|
def _fence(ctx: "PluginContext", cfg: ToolsConfig) -> tuple[Path, ...]:
|
|
"""The roots these tools may reach, mirroring what the host grants its own.
|
|
|
|
The host computes ``allowed_dirs = (workspace,) if restrict_to_workspace``
|
|
(raven/agent/loop/wiring.py) and an empty tuple means the fence is OFF --
|
|
which is what these replacements used to pass, whatever the product asked
|
|
for. The section carries the answer because a plugin factory cannot read
|
|
the host field; the launcher renders it in.
|
|
"""
|
|
return (Path(ctx.services.workspace),) if cfg.restrict_to_workspace else ()
|
|
|
|
|
|
def make_read_file(ctx: "PluginContext") -> ReadFileTool | None:
|
|
cfg = _face(ctx, "read_file")
|
|
if not cfg:
|
|
return None
|
|
return ReadFileTool(workspace=ctx.services.workspace, allowed_dirs=_fence(ctx, cfg), read_owner=owner_for(ctx))
|
|
|
|
|
|
def make_write_file(ctx: "PluginContext") -> WriteFileTool | None:
|
|
cfg = _face(ctx, "write_file")
|
|
if not cfg:
|
|
return None
|
|
return WriteFileTool(
|
|
workspace=ctx.services.workspace,
|
|
allowed_dirs=_fence(ctx, cfg),
|
|
syntax_note=cfg.python_syntax_note,
|
|
read_owner=owner_for(ctx),
|
|
)
|
|
|
|
|
|
def make_edit_file(ctx: "PluginContext") -> EditFileTool | None:
|
|
cfg = _face(ctx, "edit_file")
|
|
if not cfg:
|
|
return None
|
|
return EditFileTool(
|
|
workspace=ctx.services.workspace,
|
|
allowed_dirs=_fence(ctx, cfg),
|
|
syntax_note=cfg.python_syntax_note,
|
|
read_owner=owner_for(ctx),
|
|
require_read=cfg.require_read_before_edit,
|
|
)
|
|
|
|
|
|
def make_list_dir(ctx: "PluginContext") -> ListDirTool | None:
|
|
cfg = _face(ctx, "list_dir")
|
|
if not cfg:
|
|
return None
|
|
return ListDirTool(workspace=ctx.services.workspace, allowed_dirs=_fence(ctx, cfg))
|
|
|
|
|
|
def make_glob(ctx: "PluginContext") -> GlobTool | None:
|
|
cfg = _face(ctx, "glob")
|
|
if not cfg:
|
|
return None
|
|
return GlobTool(workspace=ctx.services.workspace, allowed_dirs=_fence(ctx, cfg))
|
|
|
|
|
|
def make_exec(ctx: "PluginContext") -> CodeExecTool | None:
|
|
"""The shell, with the clamped ceiling, partial output on timeout and the
|
|
30,000-character budget with spill. Served only where the host's own exec
|
|
would run on the host too (``tools.sandbox.backend == "none"``): the
|
|
replacement runs on the host, and a configured sandbox must not be
|
|
bypassed by a same-name tool -- so under any other backend this declines
|
|
and the host's exec keeps the shell."""
|
|
cfg = _face(ctx, "exec")
|
|
if not cfg:
|
|
return None
|
|
if cfg.exec.sandbox_backend != "none":
|
|
logger.info(
|
|
"code-flow: tools.sandbox.backend is {!r}; the host's exec keeps the shell", cfg.exec.sandbox_backend
|
|
)
|
|
return None
|
|
home = Path(ctx.services.workspace)
|
|
executor = CodeExecutor(max_timeout=cfg.exec.max_timeout, spill_dir=home / SPILL_SUBDIR)
|
|
return CodeExecTool(
|
|
timeout=cfg.exec.timeout,
|
|
working_dir=str(home),
|
|
restrict_to_workspace=cfg.restrict_to_workspace,
|
|
path_append=cfg.exec.path_append,
|
|
executor=executor,
|
|
extra_allowed_dirs=(home,),
|
|
max_timeout=cfg.exec.max_timeout,
|
|
)
|
|
|
|
|
|
def make_todo(ctx: "PluginContext") -> TodoTool | None:
|
|
"""The checklist, on the store the flow hook binds per session: one store
|
|
per Agent home, so the hook factory and this one meet on the same object."""
|
|
return TodoTool(STORES.for_home(ctx.services.workspace)) if _face(ctx, "todo") else None
|
|
|
|
|
|
__all__ = [
|
|
"make_edit_file",
|
|
"make_exec",
|
|
"make_glob",
|
|
"make_list_dir",
|
|
"make_read_file",
|
|
"make_todo",
|
|
"make_write_file",
|
|
]
|