## Summary
These are aggregate ceilings on how far import cycles reach, not a proof that no
cycle was deepened: an edge added between two members of the existing component
leaves every total unmoved, and that case is left to the contracts and to review.
The module docstring says so too.
`acyclic_siblings` is the import-linter contract that would forbid import cycles
among raven's top-level subpackages outright. It is not in `pyproject.toml`
because it is BROKEN: **18 of the 40 top-level subpackages sit in a single
strongly connected component**. Added as a gate it would paint CI red on arrival
and be switched off within the week.
This states the same rule as a budget instead of an absolute. Three ceilings, set
to what the tree measures today, and they may only go down:
```
PACKAGES_IN_CYCLES_CEILING = 18
MUTUAL_PAIRS_CEILING = 13
MODULES_IN_CYCLES_CEILING = 42
```
This branch carries the vocabulary refactor (MR 610) underneath it, because the
ceilings are the numbers that hold once that lands. If 610 merges first this
becomes a single-commit change; either way the ceilings match the tree the guard
runs against.
A change that draws a package or a module into a cycle for the first time, or
makes a new pair import each other, fails here. An edge added between two
members of the existing component does not: every total stays put, and that
case is left to the contracts and to review. Unpicking one lowers a ceiling,
which is a reviewed edit to the test file rather than a drive-by -- the same
shape `tests/test_kernel_budget.py` already uses, and for the same reason its
docstring gives.
Three numbers, because each is blind where another sees. Mutual pairs (a imports
b and b imports a) are the edges people actually add, and the failure message
names them. A cycle three packages long shows up in no pair at all, so a
component measure carries the general case.
The third exists because the package measure is an artifact of granularity as
much as of design. Collapsing a package to one node turns "config's writer
reaches agent, which reaches config's loader" into a cycle even where no module
imports itself back; measured per module, 42 of 635 modules sit in a cycle
rather than 18 of 40 packages. The two answer different questions -- whether a
package can be lifted out on its own, and whether a reader has a real knot to
walk around -- and they move independently: the refactor underneath took the
package count from 22 to 18 while moving the module count by three.
The numbers were still moving while this was written. `agent <-> permissions`
became the fourteenth mutual pair during the drafting, on a `permissions`
package that had just arrived. Nothing reported it, because nothing was
watching -- which is the case for pinning them.
`grimp` becomes an explicit dev dependency rather than staying a transitive one
through import-linter, since a test now imports it directly.
This changes no production code and unpicks no cycle. It fixes the number in
place so that the unpicking, when it happens, is not undone by the next branch.
### Both graph options are chosen, not defaulted
`exclude_type_checking_imports` is read out of `[tool.importlinter]` rather than
hardcoded, so the guard measures the same graph the contracts are checked
against. Without it, `gateway` counts as cyclic on a type-checking-only import
and the module count moves by three -- the guard would have been ratcheting a
graph no contract enforces.
`cache_dir=None` because grimp's default is a shared `.grimp_cache` that
outlives a branch switch. A guard whose job is to report the graph of the
checked-out tree must not serve one an earlier revision left behind: a stale hit
turns it red or green for reasons absent from the diff. Building fresh costs
about a second.
## Type
- [ ] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [x] Other
Other: an architecture guard, in the shape of a budget. Closest to `test`, which
is the commit type used.
## Verification
```
$ uv run --frozen --python 3.12 pytest tests/test_import_cycle_budget.py -q
4 passed in 1.06s
$ uv run --frozen --python 3.12 pytest tests/test_import_cycle_budget.py \
tests/test_kernel_closure.py tests/test_kernel_budget.py -q
10 passed in 1.51s
$ uv run --frozen --python 3.12 lint-imports
Contracts: 8 kept, 0 broken.
$ uv run --frozen --python 3.12 --extra dev ruff check tests/test_import_cycle_budget.py
All checks passed!
$ uv run --frozen --python 3.12 --extra dev ruff format --check tests/test_import_cycle_budget.py
1 file already formatted
$ make check-commits COMMIT_RANGE=origin/main..HEAD
exit 0
```
Checked in the failing direction once per ceiling, since a gate that has never
been seen red is not known to work.
Making `utils` import the subagent presets trips the two package ceilings and
leaves the module count untouched -- which is the granularity point above, seen
from the failing side:
```
AssertionError: 23 subpackages are inside an import cycle, over the ceiling of 18
AssertionError: 15 pairs of subpackages import each other, over the ceiling of 13
```
Making `utils.text` and `importer.skills.hermes` import each other is a real
module-level cycle, and trips the third:
```
AssertionError: 45 modules are inside an import cycle, over the ceiling of 42
```
Both probes were reverted; the diff carries only the guard, the ceilings and the
dependency line.
- [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 runtime behaviour change. The guard reads the import graph and asserts three
counts; it adds about a second to the suite. All three ceilings are met on
arrival,
so nothing that exists today is blocked. Rollback is reverting the one commit.
The known limit of a count-based ratchet is the one the coverage ratchet already
carries: a change that closes one cycle and opens another leaves the totals
unmoved and passes. Naming the pairs in the failure message is what makes that
visible in review when it matters.
## 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",
|
|
]
|