147 lines
5.2 KiB
Python
Raw Permalink Normal View History

feat(acp): a prompt is held open while the agent sleeps on an armed wake, and takes a steer ## Summary An on-call agent submits a job, arms a wake and ends its turn saying so; the wake runs a later turn on the session on its own clock. Over ACP that turn's `end_turn` read as "finished" to the caller: a DAG judging its node spent every continuation on "still watching, wake at 13:13" while the job ran fine (ar-r4, 2026-09-08), and the main agent re-dispatched the work by hand. ACP has no stop reason for "waiting". Replaces the closed !573: **no DAG code changes**, no new node status. The node is `running` because a turn is genuinely in flight. - **The signal.** The loop-hooks paper gains one key the ACP layer reads for itself: `acp_meta["raven.holdTurn"]` (`{"untilMs", "why"}`). oncall-flow files it at the send fire when the window's campaign is claimed, not concluded, and has one pending wake -- read the same way the owner's answer pulls that wake forward. No campaign, a wake that stood down, or a concluded campaign files nothing and the turn ends as before. - **The hold** (`raven/acp/methods.py`). A turn that ended `end_turn` with the key filed is not answered. One `tool_call` stands for the wait (its title names the campaign and the next look), with a `tool_call_update` heartbeat every `HOLD_HEARTBEAT_S` (60 s) so a client that clocks liveness by frames sees the agent alive while its model sleeps. The turn slot is reopened with no id to correlate on, so whichever turn ends next on the session -- the wake's, a steer's -- settles it, and the handler decides again from that turn's stash. A wake that arms again keeps the hold; a turn ending with nothing pending answers `end_turn`; a cancel answers `cancelled` as before. The key itself is not passed to the client. - **Steer.** `_raven/session/steer` is served and advertised under `agentCapabilities._meta` as `raven.steer` (the names raven's own client already uses). Accepted while a prompt is open on the session, held or running: the text is shown on the wire as the person's own line, then sent with `turn.send`'s new `busy: "inject"`. Answers `injected` / `no_turn`. - **Wire.** `turn.send` gains the optional `busy` param (`const "inject"`): an ordinary send on an idle lane, `BusyPolicy.INJECT` into the running turn otherwise -- the merge a channel's mid-turn message already gets (`gateway_commands.py`). No slot is bound for an injected message; the running turn keeps the lane's. `openrpc.json` and both generated clients moved together. What raven's client side already does, unchanged: the DAG stall watcher resets on any frame (the heartbeat keeps it quiet, and a stopped heartbeat raises the existing stall notice after ten minutes); a sub-agent process that dies fails the request and the node takes its ordinary path; the pool's `_responsive` treats a prompt in flight as busy. ## Review round 1 (2026-09-09, on !600, superseded by this MR) - **`busy: inject` reads the scheduler's lane state too.** `is_turn_active` knows only the turns `turn.send` started; an armed wake is submitted to the scheduler directly (`make_on_session_wake`) and never binds that map, so a steer during a running wake queued a second turn and answered `injected`. `turn.send` now asks `Scheduler.has_inflight(lane)` as well, and merges (`BusyPolicy.INJECT`) when either record says the lane is running. Pinned: `test_busy_inject_merges_into_a_wake_the_real_scheduler_is_running` -- the reviewer's reproduction on the real `Scheduler`, a turn submitted the way `make_on_session_wake` submits one; with the lane check bypassed it reads `pending=1, inject_mailbox=0`, with it `(1, 0)` in the mailbox and the running turn drains the text. - Branch renamed to snake_case and both commits carry the `Co-authored-by: Claude (<model-id>)` trailer, per AGENTS.md §2–3; that is why this MR replaces !600 rather than continuing it. ## Review round 2 (2026-09-10) - **A wake re-armed during its own run survives the writeback.** `CronService._writeback_locked` reloaded the store after the run and, for a one-shot with `delete_after_run`, overwrote the id with the finished run's state and removed it -- but the turn the wake ran had just called `schedule_wake` under the same key, so the id now named the *next* look. It vanished, and the held prompt had nothing left to settle it. A stored job under the fired id whose `at` schedule the run never had is treated as the new wake it is: claim cleared, run recorded, schedule kept, not deleted. Pinned on the real service: `test_a_wake_re_armed_during_its_own_run_survives_the_writeback` (reads `[]` without the fix, the reviewer's state) and the unchanged one-shot deletion beside it. Cron, proactive, sentinel and on-call suites: 968 passed. ## Review round 3 (2026-09-10) - **An undrained inject stays visible and cancellable.** `busy: inject` dropped the scheduler's handle; when the host turn ended past its last drain, the spine's fallback ran the text as a turn nothing owned -- `turn.cancel` a no-op, no `message.start`. The handle is now kept per lane under an id minted for the text; `turn.cancel` / `session.interrupt` reach it when the active slot is empty (mailbox, queued fallback, or running); and when the fallback turn starts, the RPC sink (`on_turn_start`, wired from bootstrap) binds the lane to it and opens it on the wire with the person's words. `turn.send` answers the inject's own id. Pinned through `build_rpc_spine` with the reviewer's shape (a loop that drains once, an inject after it): `test_an_undrained_inject_runs_as_a_turn_the_surface_can_see_and_cancel` and `test_a_pending_inject_can_be_cancelled_before_it_merges_or_falls_back`; both read the reviewer's state (`turn_ids` empty, cancel finding nothing) with the fix bypassed. - **Line ceiling.** The contract comment is five lines; `raven/contracts` is 2,519 against 2,520, one line of headroom on the current `main` (2,514). - Non-blocking items taken: `SchedulerDrainingError` on the inject path exits as `turn_failed`; the title is announced before the hold; the steer constants sit below the cancel constant's docstring; three edges pinned (a held prompt settled by a wake turn's uncorrelated ending through `send_frame`, the hold key never in the client's `_meta`, `raven.toolName` on the wait row). - Focused suite (reviewer's list plus the touched files): 948 passed on Python 3.12. ## Review round 4 (2026-09-10) - **Every pending inject is kept, per lane and per id.** One replaceable record per lane kept only the newest steer; two steers after the host's last drain fall back in turn, and the first started unowned while a cancel took out the second. The record is now `lane -> {inject id: (handle, text)}` in arrival order: each fallback promotes its own handle, and a cancel with no active turn reaches the oldest pending one -- the one the spine runs next. Pinned: `test_two_undrained_injects_each_get_their_own_turn_promoted_and_cancelled` (both promoted with their own ids and `message.start`, cancelled one after the other; runner saw all three turns). Focused suite: 949 passed. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification ``` uv run pytest tests/test_acp_methods.py tests/test_acp_protocol.py tests/test_rpc_turn_send.py \ tests/test_rpc_schema_match.py tests/test_acp_updates.py tests/test_acp_server.py -q # 766 passed uv run pytest tests/test_agents_oncall_flow_hooks.py tests/test_agents_oncall_flow_actions.py \ tests/test_agents_oncall_flow_budget.py tests/test_agents_oncall_flow_readings.py \ tests/test_agents_oncall_flow_escalation_tools.py -q # 99 passed uv run ruff check raven tests agents && uv run ruff format --check raven tests agents # clean uv run lint-imports # 9 kept, 0 broken cd ui-tui && npm run lint:rpc && npx tsc --noEmit; cd ui-web && npm run gen:check && npx tsc --noEmit # in sync, clean ``` New tests: `TestHeldTurn` (held across an armed wake, held again on a re-arm, heartbeat on the wait call, cancel while held, a non-`end_turn` stop is not held; every frame validated against the ACP schema), `TestSteer` (advertised, `no_turn` when idle, a held prompt takes the words as a turn with `busy: inject`, refusals), `busy: inject` on a busy and an idle lane in `test_rpc_turn_send.py`, and the plugin's hold stamping through the real `CronService` grant (filed with a pending wake; not filed without one, after the wake stands down, or once the campaign concluded). Not done: no end-to-end run of a real on-call wake through a held prompt yet -- unit tests only. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed (the hold is invisible to a person except as a "waiting for ..." tool row) ## Risk - [x] Backward compatibility considered: a turn that files no `raven.holdTurn` is answered exactly as before; `busy` is optional and absent from every existing caller; the steer method and capability are additive. - [x] Rollback path is clear: revert the two commits. A held prompt holds one `max_concurrent_subagents` slot (default 8) for the wait's duration on the caller's side; raised in config if it bites. ## Related Replaces !573 (closed). Follows !518 (stall notice) and !520 (unprompted-turn route; a wake that runs under a held prompt no longer takes it for DAG nodes).
2026-09-11 02:37:55 +00:00
"""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,
feat(*): add bounded Python diagnostics after code edits (#967) ## Summary Raven-Code reports Python syntax errors after file edits but misses unresolved names and equivalent feedback after shell edits. Add advisory Pyflakes F821/F822/F823 checks to the existing tool result; optional F401 notices remain off by default. No additional model call or code execution is involved. ```text write_file / edit_file -> inspect final source, compare with a baseline that can be read and analyzed -> retain syntax warnings; suppress existing name findings exec -> require checkpoint visibility for the working directory -> read the changed files from the host's write record for the command -> ask visibility in batches of 256, select at most 8, check up to 4 concurrently -> append ordered diagnostics, preserving exit status and file metadata ``` Existing syntax failures remain visible after unrelated edits and identical rewrites. A baseline that cannot be read, parsed or analyzed is marked unknown; overwriting non-UTF-8 source still checks the known replacement. Source nested too deeply for the parser or checker, and a changed file that cannot be read, report diagnostics unavailable for that file rather than passing as clean. Every check reads a file as the bytes Python runs: text a write or edit stores is checked as its UTF-8 bytes, the content it replaced included, and a file from disk as its bytes, each decoded as Python decodes source, by its coding declaration or as UTF-8. Bytes that do not decode are reported as a syntax error at the line where decoding stops, so a declaration the written text cannot satisfy is reported however the file was changed. Noqa comments are read as Ruff reads them, including after other comment directives and never inside string literals: a file-level `ruff: noqa` / `flake8: noqa` counts only on a line of its own, and a marker counts only when codes follow its colon or, with no colon, whitespace, another comment or the end of the comment follows it. Unlike Ruff, which takes the first directive in a comment, every directive in it counts. The seeded tool guide gives the syntax note's own advice. With no checkpoint or no visibility verdict, exec diagnostics do not inspect changed file contents; direct file checks remain available. Pyflakes is imported when the tool face loads, not by whichever check first needs it: imported lazily, its cold import fell inside that check's one-second wait, and on a slow Windows runner the one test that paid it reported diagnostics unavailable for a plain syntax error. Private workers bound reads and checks to four active jobs per process. Saturated capacity rejects new work without queuing, and timeout/cancellation retains each slot until the actual work finishes. Name checks are capped at 256 KiB of source and the syntax check at 2 MiB, and a check skipped for size says so in one line. Findings are capped at eight per file, and exec diagnostic text at 6,000 characters plus omission notices. Runtime changes stay inside the Raven-Code code-flow plugin, except for one fix to `CheckpointService.trackable`, the visibility verdict that exec diagnostics and the host's exec write record both rely on. On macOS, git precomposes a file name it reads off the disk before matching an ignore rule, but takes the paths `trackable` sends to `git check-ignore --stdin` as written. A file stored with a decomposed (NFD) name under a `.gitignore` rule written precomposed (NFC) is therefore left out of the checkpoint, yet main vouches for it, so the write record's diff carries its text, and exec diagnostics would quote its source lines to the model. Nor is git's precomposition NFC: it composes only neighbouring characters, by Unicode 3.2's table, and reorders nothing, so a name whose combining marks are out of canonical order comes out as neither the name as given nor its NFC. `trackable` now asks about each name as given, as NFC and in git's macOS spelling, and withholds it when any spelling is ignored. Other shared file/shell/snapshot implementations are unchanged. Raven-Code has no separate dependency manifest, so Pyflakes uses the existing root dependencies. It is the only added package; uv normalized existing lockfile markers without changing other package versions. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification - **Before:** on main, Raven-Code's file tools report Python syntax errors only, and its exec reports nothing about the Python files a command changed. On macOS, main's `CheckpointService.trackable` vouches for a file stored as `secret_cafe` + U+0301 + `.py` under the rule `secret_caf` + U+00E9 + `.py`: the user's own git ignores it and the checkpoint's staged tree leaves it out, yet its text reaches the exec write record's stored diff. - **After:** on macOS 26.6.2 / arm64 with Apple Git 2.54.0, the command below passes 364 tests on Python 3.12.13 and on 3.14.6. The full default suite on 3.12.13 has 32283 passed, 169 skipped, 20 failed and 3 errors over 22 test ids: 21 of them also fail on the exact base in the same environment, and the other, a remote process-tree cancel test that missed its deadline under the suite's load, passes when run alone. Tests cover actual worker overlap, retained capacity after timeout/cancellation, host-tool isolation, hidden-file quotas, visibility batching through the host's write-record wiring, baseline handling, parser-limit failures, the size bounds and their skip notes, undecodable bytes placed where decoding stops, coding declarations in written and edited text, the baseline read staying on a worker, the checker loaded with its module, the file each unavailable note names, comment directives and their marker boundary, the tool guide's agreement with the syntax note, portable commands in paths with spaces/non-ASCII characters, and the checkpoint's verdict on decomposed names and on names git spells as neither given nor NFC, held against its own staged tree. Removing any of the three spellings from the query fails the cases that pin it, as does removing the marker boundary, the parser-limit report, the unknown-baseline handling, the syntax check past the name-check bound and the decoding report, checking written text as its stored bytes, the worker around the baseline read, loading the checker with its module, or the file name in an unavailable note; restoring the guide's earlier advice fails its agreement test. git's macOS spelling is what libiconv's UTF-8-MAC conversion returns, which git precomposes with: composing neighbours by Unicode 3.2's table reproduced it for all 281,928 names built from every decomposable character's decomposition (reordered, partly composed, or with a mark added), and across 784,220 further mixed names and pairs no name was spelled outside the three asked; the same held under Python 3.13 and 3.14. The decomposed-name check asserts the macOS outcome only where git precomposes names, so it also passes with `core.precomposeunicode = false` set through `GIT_CONFIG_GLOBAL`. Across 102 noqa comment variants the reported lines match Ruff 0.15.12, except the three that hold several directives in one comment. Through the real `AgentLoop`, code-flow tool face, `CodeExecutor` and checkpoint, with the working directory under `/tmp`, under `$TMPDIR` and in a path with spaces and CJK characters, exec diagnostics report created, modified and decomposed-name files, follow `working_dir`, report an undecodable file at the line where decoding stops, a syntax error past 256 KiB and a skip past 2 MiB, and withhold `.gitignore`d files, including decomposed names and names git spells as neither given nor NFC; across repeated runs on both interpreters, a file near the 256 KiB cap is checked in 52-135 ms (117-128 ms against a baseline), the syntax of a file near 2 MiB in 318-371 ms, and 600 ignored files plus one visible file take 73-90 ms with the event loop held at most 20 ms. At this head CI passes the unit suite on Linux/Python 3.12 (32619 tests over four shards), and its two Windows steps pass the diagnostic files on native Windows/Python 3.13: 122 file/worker tests, and 27 exec diagnostic tests with 17 pre-existing executor tests deselected; the symlink fixture skips only where the host cannot create links. ```sh env -u SERPER_API_KEY -u RAVEN_MIRRORED_SERPER_API_KEY uv run --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_flow_exec.py tests/test_agents_code_flow_plugin.py tests/test_agents_code_flow_read_state.py tests/test_agents_code_launcher.py tests/test_workdir_snapshot.py tests/test_shell_command_writes.py tests/test_runtime_checkpoint.py tests/test_trajectory_upload.py::test_blocked_upload_hits_the_deadline -o addopts= -q --tb=short --maxfail=3 uv run --no-sync ruff check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_diagnostic_workers.py uv run --no-sync ty check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py uv run --no-sync lint-imports uv run --no-sync ruff format --check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py ``` Native Windows CI commands: ```sh uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py -q -n 0 --tb=short uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_flow_exec.py -k test_exec_ -q -n 0 --tb=short ``` Ruff, format and type checks passed; all 10 import contracts kept; the commit-message, large-file and source-language checks pass over the branch. The launcher tests unset inherited search API keys to keep the expected tool list deterministic. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk Scope: Raven-Code's enabled code-flow tool face; installing Pyflakes does not activate checks in other agents. The change is reversible and never fixes/removes code or rolls back edits. Static diagnostics can need judgment for dynamic names, target Python versions, and project lint configuration; only explicit noqa directives are honored. Passing diagnostics do not replace tests. The `trackable` fix reaches every exec write record, not only Raven-Code: a file whose name, as given, as NFC or in git's macOS spelling, matches an ignore rule keeps its counts and loses its diff and removal body. Where git matches another of those spellings, as off macOS for a decomposed name under a precomposed rule, the checkpoint stores the file but it is still withheld; its counts remain. Exec diagnostics now require an active checkpoint. Noninteractive runs using the default interactive checkpoint policy must explicitly enable checkpoints to receive this feedback. Visibility is checked in batches of up to 256 files and stops once eight visible files are found; each batch holds the event loop while the host resolves its paths, about 130 ms for a full batch on native Windows. Each file-check wait is one second, and post-command diagnostics have a three-second wait budget; past it, or when they fail as a whole, they are dropped and the command's result is kept. These are caller budgets, not hard I/O deadlines: running OS reads and inherited synchronous host callbacks cannot be forcibly interrupted. Private worker capacity remains bounded. Between 256 KiB and 2 MiB only syntax is checked: near 2 MiB that took 0.3-0.4 s and about 190 MiB here, up to four checks run at once, and on slower hardware such a check can outlast the one-second wait and report diagnostics unavailable. Python's GIL means concurrency does not promise a CPU speedup. Windows CI exercises the diagnostics layer with the real native DirectExecutor. The existing CodeExecutor environment probe uses POSIX quoting and already fails on Windows at the base; this PR neither changes that probe nor claims end-to-end compatibility for it. Symlink setup is skipped only if the host cannot create the fixture. Disable `pythonLint` for syntax-only feedback, `execPythonDiagnostics` for no post-command checks, or `pythonSyntaxNote` for no diagnostics, under `plugins.config["code-flow"].tools`. The PR can also be reverted as a unit. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: Codex <noreply@openai.com> Co-authored-by: Dizhan Xue <xuedizhan17@mails.ucas.ac.cn> Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-10-18 20:21:04 +08:00
lint=cfg.python_lint,
unused_imports=cfg.python_unused_imports,
feat(acp): a prompt is held open while the agent sleeps on an armed wake, and takes a steer ## Summary An on-call agent submits a job, arms a wake and ends its turn saying so; the wake runs a later turn on the session on its own clock. Over ACP that turn's `end_turn` read as "finished" to the caller: a DAG judging its node spent every continuation on "still watching, wake at 13:13" while the job ran fine (ar-r4, 2026-09-08), and the main agent re-dispatched the work by hand. ACP has no stop reason for "waiting". Replaces the closed !573: **no DAG code changes**, no new node status. The node is `running` because a turn is genuinely in flight. - **The signal.** The loop-hooks paper gains one key the ACP layer reads for itself: `acp_meta["raven.holdTurn"]` (`{"untilMs", "why"}`). oncall-flow files it at the send fire when the window's campaign is claimed, not concluded, and has one pending wake -- read the same way the owner's answer pulls that wake forward. No campaign, a wake that stood down, or a concluded campaign files nothing and the turn ends as before. - **The hold** (`raven/acp/methods.py`). A turn that ended `end_turn` with the key filed is not answered. One `tool_call` stands for the wait (its title names the campaign and the next look), with a `tool_call_update` heartbeat every `HOLD_HEARTBEAT_S` (60 s) so a client that clocks liveness by frames sees the agent alive while its model sleeps. The turn slot is reopened with no id to correlate on, so whichever turn ends next on the session -- the wake's, a steer's -- settles it, and the handler decides again from that turn's stash. A wake that arms again keeps the hold; a turn ending with nothing pending answers `end_turn`; a cancel answers `cancelled` as before. The key itself is not passed to the client. - **Steer.** `_raven/session/steer` is served and advertised under `agentCapabilities._meta` as `raven.steer` (the names raven's own client already uses). Accepted while a prompt is open on the session, held or running: the text is shown on the wire as the person's own line, then sent with `turn.send`'s new `busy: "inject"`. Answers `injected` / `no_turn`. - **Wire.** `turn.send` gains the optional `busy` param (`const "inject"`): an ordinary send on an idle lane, `BusyPolicy.INJECT` into the running turn otherwise -- the merge a channel's mid-turn message already gets (`gateway_commands.py`). No slot is bound for an injected message; the running turn keeps the lane's. `openrpc.json` and both generated clients moved together. What raven's client side already does, unchanged: the DAG stall watcher resets on any frame (the heartbeat keeps it quiet, and a stopped heartbeat raises the existing stall notice after ten minutes); a sub-agent process that dies fails the request and the node takes its ordinary path; the pool's `_responsive` treats a prompt in flight as busy. ## Review round 1 (2026-09-09, on !600, superseded by this MR) - **`busy: inject` reads the scheduler's lane state too.** `is_turn_active` knows only the turns `turn.send` started; an armed wake is submitted to the scheduler directly (`make_on_session_wake`) and never binds that map, so a steer during a running wake queued a second turn and answered `injected`. `turn.send` now asks `Scheduler.has_inflight(lane)` as well, and merges (`BusyPolicy.INJECT`) when either record says the lane is running. Pinned: `test_busy_inject_merges_into_a_wake_the_real_scheduler_is_running` -- the reviewer's reproduction on the real `Scheduler`, a turn submitted the way `make_on_session_wake` submits one; with the lane check bypassed it reads `pending=1, inject_mailbox=0`, with it `(1, 0)` in the mailbox and the running turn drains the text. - Branch renamed to snake_case and both commits carry the `Co-authored-by: Claude (<model-id>)` trailer, per AGENTS.md §2–3; that is why this MR replaces !600 rather than continuing it. ## Review round 2 (2026-09-10) - **A wake re-armed during its own run survives the writeback.** `CronService._writeback_locked` reloaded the store after the run and, for a one-shot with `delete_after_run`, overwrote the id with the finished run's state and removed it -- but the turn the wake ran had just called `schedule_wake` under the same key, so the id now named the *next* look. It vanished, and the held prompt had nothing left to settle it. A stored job under the fired id whose `at` schedule the run never had is treated as the new wake it is: claim cleared, run recorded, schedule kept, not deleted. Pinned on the real service: `test_a_wake_re_armed_during_its_own_run_survives_the_writeback` (reads `[]` without the fix, the reviewer's state) and the unchanged one-shot deletion beside it. Cron, proactive, sentinel and on-call suites: 968 passed. ## Review round 3 (2026-09-10) - **An undrained inject stays visible and cancellable.** `busy: inject` dropped the scheduler's handle; when the host turn ended past its last drain, the spine's fallback ran the text as a turn nothing owned -- `turn.cancel` a no-op, no `message.start`. The handle is now kept per lane under an id minted for the text; `turn.cancel` / `session.interrupt` reach it when the active slot is empty (mailbox, queued fallback, or running); and when the fallback turn starts, the RPC sink (`on_turn_start`, wired from bootstrap) binds the lane to it and opens it on the wire with the person's words. `turn.send` answers the inject's own id. Pinned through `build_rpc_spine` with the reviewer's shape (a loop that drains once, an inject after it): `test_an_undrained_inject_runs_as_a_turn_the_surface_can_see_and_cancel` and `test_a_pending_inject_can_be_cancelled_before_it_merges_or_falls_back`; both read the reviewer's state (`turn_ids` empty, cancel finding nothing) with the fix bypassed. - **Line ceiling.** The contract comment is five lines; `raven/contracts` is 2,519 against 2,520, one line of headroom on the current `main` (2,514). - Non-blocking items taken: `SchedulerDrainingError` on the inject path exits as `turn_failed`; the title is announced before the hold; the steer constants sit below the cancel constant's docstring; three edges pinned (a held prompt settled by a wake turn's uncorrelated ending through `send_frame`, the hold key never in the client's `_meta`, `raven.toolName` on the wait row). - Focused suite (reviewer's list plus the touched files): 948 passed on Python 3.12. ## Review round 4 (2026-09-10) - **Every pending inject is kept, per lane and per id.** One replaceable record per lane kept only the newest steer; two steers after the host's last drain fall back in turn, and the first started unowned while a cancel took out the second. The record is now `lane -> {inject id: (handle, text)}` in arrival order: each fallback promotes its own handle, and a cancel with no active turn reaches the oldest pending one -- the one the spine runs next. Pinned: `test_two_undrained_injects_each_get_their_own_turn_promoted_and_cancelled` (both promoted with their own ids and `message.start`, cancelled one after the other; runner saw all three turns). Focused suite: 949 passed. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification ``` uv run pytest tests/test_acp_methods.py tests/test_acp_protocol.py tests/test_rpc_turn_send.py \ tests/test_rpc_schema_match.py tests/test_acp_updates.py tests/test_acp_server.py -q # 766 passed uv run pytest tests/test_agents_oncall_flow_hooks.py tests/test_agents_oncall_flow_actions.py \ tests/test_agents_oncall_flow_budget.py tests/test_agents_oncall_flow_readings.py \ tests/test_agents_oncall_flow_escalation_tools.py -q # 99 passed uv run ruff check raven tests agents && uv run ruff format --check raven tests agents # clean uv run lint-imports # 9 kept, 0 broken cd ui-tui && npm run lint:rpc && npx tsc --noEmit; cd ui-web && npm run gen:check && npx tsc --noEmit # in sync, clean ``` New tests: `TestHeldTurn` (held across an armed wake, held again on a re-arm, heartbeat on the wait call, cancel while held, a non-`end_turn` stop is not held; every frame validated against the ACP schema), `TestSteer` (advertised, `no_turn` when idle, a held prompt takes the words as a turn with `busy: inject`, refusals), `busy: inject` on a busy and an idle lane in `test_rpc_turn_send.py`, and the plugin's hold stamping through the real `CronService` grant (filed with a pending wake; not filed without one, after the wake stands down, or once the campaign concluded). Not done: no end-to-end run of a real on-call wake through a held prompt yet -- unit tests only. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed (the hold is invisible to a person except as a "waiting for ..." tool row) ## Risk - [x] Backward compatibility considered: a turn that files no `raven.holdTurn` is answered exactly as before; `busy` is optional and absent from every existing caller; the steer method and capability are additive. - [x] Rollback path is clear: revert the two commits. A held prompt holds one `max_concurrent_subagents` slot (default 8) for the wait's duration on the caller's side; raised in config if it bites. ## Related Replaces !573 (closed). Follows !518 (stall notice) and !520 (unprompted-turn route; a wake that runs under a held prompt no longer takes it for DAG nodes).
2026-09-11 02:37:55 +00:00
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,
feat(*): add bounded Python diagnostics after code edits (#967) ## Summary Raven-Code reports Python syntax errors after file edits but misses unresolved names and equivalent feedback after shell edits. Add advisory Pyflakes F821/F822/F823 checks to the existing tool result; optional F401 notices remain off by default. No additional model call or code execution is involved. ```text write_file / edit_file -> inspect final source, compare with a baseline that can be read and analyzed -> retain syntax warnings; suppress existing name findings exec -> require checkpoint visibility for the working directory -> read the changed files from the host's write record for the command -> ask visibility in batches of 256, select at most 8, check up to 4 concurrently -> append ordered diagnostics, preserving exit status and file metadata ``` Existing syntax failures remain visible after unrelated edits and identical rewrites. A baseline that cannot be read, parsed or analyzed is marked unknown; overwriting non-UTF-8 source still checks the known replacement. Source nested too deeply for the parser or checker, and a changed file that cannot be read, report diagnostics unavailable for that file rather than passing as clean. Every check reads a file as the bytes Python runs: text a write or edit stores is checked as its UTF-8 bytes, the content it replaced included, and a file from disk as its bytes, each decoded as Python decodes source, by its coding declaration or as UTF-8. Bytes that do not decode are reported as a syntax error at the line where decoding stops, so a declaration the written text cannot satisfy is reported however the file was changed. Noqa comments are read as Ruff reads them, including after other comment directives and never inside string literals: a file-level `ruff: noqa` / `flake8: noqa` counts only on a line of its own, and a marker counts only when codes follow its colon or, with no colon, whitespace, another comment or the end of the comment follows it. Unlike Ruff, which takes the first directive in a comment, every directive in it counts. The seeded tool guide gives the syntax note's own advice. With no checkpoint or no visibility verdict, exec diagnostics do not inspect changed file contents; direct file checks remain available. Pyflakes is imported when the tool face loads, not by whichever check first needs it: imported lazily, its cold import fell inside that check's one-second wait, and on a slow Windows runner the one test that paid it reported diagnostics unavailable for a plain syntax error. Private workers bound reads and checks to four active jobs per process. Saturated capacity rejects new work without queuing, and timeout/cancellation retains each slot until the actual work finishes. Name checks are capped at 256 KiB of source and the syntax check at 2 MiB, and a check skipped for size says so in one line. Findings are capped at eight per file, and exec diagnostic text at 6,000 characters plus omission notices. Runtime changes stay inside the Raven-Code code-flow plugin, except for one fix to `CheckpointService.trackable`, the visibility verdict that exec diagnostics and the host's exec write record both rely on. On macOS, git precomposes a file name it reads off the disk before matching an ignore rule, but takes the paths `trackable` sends to `git check-ignore --stdin` as written. A file stored with a decomposed (NFD) name under a `.gitignore` rule written precomposed (NFC) is therefore left out of the checkpoint, yet main vouches for it, so the write record's diff carries its text, and exec diagnostics would quote its source lines to the model. Nor is git's precomposition NFC: it composes only neighbouring characters, by Unicode 3.2's table, and reorders nothing, so a name whose combining marks are out of canonical order comes out as neither the name as given nor its NFC. `trackable` now asks about each name as given, as NFC and in git's macOS spelling, and withholds it when any spelling is ignored. Other shared file/shell/snapshot implementations are unchanged. Raven-Code has no separate dependency manifest, so Pyflakes uses the existing root dependencies. It is the only added package; uv normalized existing lockfile markers without changing other package versions. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification - **Before:** on main, Raven-Code's file tools report Python syntax errors only, and its exec reports nothing about the Python files a command changed. On macOS, main's `CheckpointService.trackable` vouches for a file stored as `secret_cafe` + U+0301 + `.py` under the rule `secret_caf` + U+00E9 + `.py`: the user's own git ignores it and the checkpoint's staged tree leaves it out, yet its text reaches the exec write record's stored diff. - **After:** on macOS 26.6.2 / arm64 with Apple Git 2.54.0, the command below passes 364 tests on Python 3.12.13 and on 3.14.6. The full default suite on 3.12.13 has 32283 passed, 169 skipped, 20 failed and 3 errors over 22 test ids: 21 of them also fail on the exact base in the same environment, and the other, a remote process-tree cancel test that missed its deadline under the suite's load, passes when run alone. Tests cover actual worker overlap, retained capacity after timeout/cancellation, host-tool isolation, hidden-file quotas, visibility batching through the host's write-record wiring, baseline handling, parser-limit failures, the size bounds and their skip notes, undecodable bytes placed where decoding stops, coding declarations in written and edited text, the baseline read staying on a worker, the checker loaded with its module, the file each unavailable note names, comment directives and their marker boundary, the tool guide's agreement with the syntax note, portable commands in paths with spaces/non-ASCII characters, and the checkpoint's verdict on decomposed names and on names git spells as neither given nor NFC, held against its own staged tree. Removing any of the three spellings from the query fails the cases that pin it, as does removing the marker boundary, the parser-limit report, the unknown-baseline handling, the syntax check past the name-check bound and the decoding report, checking written text as its stored bytes, the worker around the baseline read, loading the checker with its module, or the file name in an unavailable note; restoring the guide's earlier advice fails its agreement test. git's macOS spelling is what libiconv's UTF-8-MAC conversion returns, which git precomposes with: composing neighbours by Unicode 3.2's table reproduced it for all 281,928 names built from every decomposable character's decomposition (reordered, partly composed, or with a mark added), and across 784,220 further mixed names and pairs no name was spelled outside the three asked; the same held under Python 3.13 and 3.14. The decomposed-name check asserts the macOS outcome only where git precomposes names, so it also passes with `core.precomposeunicode = false` set through `GIT_CONFIG_GLOBAL`. Across 102 noqa comment variants the reported lines match Ruff 0.15.12, except the three that hold several directives in one comment. Through the real `AgentLoop`, code-flow tool face, `CodeExecutor` and checkpoint, with the working directory under `/tmp`, under `$TMPDIR` and in a path with spaces and CJK characters, exec diagnostics report created, modified and decomposed-name files, follow `working_dir`, report an undecodable file at the line where decoding stops, a syntax error past 256 KiB and a skip past 2 MiB, and withhold `.gitignore`d files, including decomposed names and names git spells as neither given nor NFC; across repeated runs on both interpreters, a file near the 256 KiB cap is checked in 52-135 ms (117-128 ms against a baseline), the syntax of a file near 2 MiB in 318-371 ms, and 600 ignored files plus one visible file take 73-90 ms with the event loop held at most 20 ms. At this head CI passes the unit suite on Linux/Python 3.12 (32619 tests over four shards), and its two Windows steps pass the diagnostic files on native Windows/Python 3.13: 122 file/worker tests, and 27 exec diagnostic tests with 17 pre-existing executor tests deselected; the symlink fixture skips only where the host cannot create links. ```sh env -u SERPER_API_KEY -u RAVEN_MIRRORED_SERPER_API_KEY uv run --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_flow_exec.py tests/test_agents_code_flow_plugin.py tests/test_agents_code_flow_read_state.py tests/test_agents_code_launcher.py tests/test_workdir_snapshot.py tests/test_shell_command_writes.py tests/test_runtime_checkpoint.py tests/test_trajectory_upload.py::test_blocked_upload_hits_the_deadline -o addopts= -q --tb=short --maxfail=3 uv run --no-sync ruff check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_diagnostic_workers.py uv run --no-sync ty check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py uv run --no-sync lint-imports uv run --no-sync ruff format --check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py ``` Native Windows CI commands: ```sh uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py -q -n 0 --tb=short uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_flow_exec.py -k test_exec_ -q -n 0 --tb=short ``` Ruff, format and type checks passed; all 10 import contracts kept; the commit-message, large-file and source-language checks pass over the branch. The launcher tests unset inherited search API keys to keep the expected tool list deterministic. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk Scope: Raven-Code's enabled code-flow tool face; installing Pyflakes does not activate checks in other agents. The change is reversible and never fixes/removes code or rolls back edits. Static diagnostics can need judgment for dynamic names, target Python versions, and project lint configuration; only explicit noqa directives are honored. Passing diagnostics do not replace tests. The `trackable` fix reaches every exec write record, not only Raven-Code: a file whose name, as given, as NFC or in git's macOS spelling, matches an ignore rule keeps its counts and loses its diff and removal body. Where git matches another of those spellings, as off macOS for a decomposed name under a precomposed rule, the checkpoint stores the file but it is still withheld; its counts remain. Exec diagnostics now require an active checkpoint. Noninteractive runs using the default interactive checkpoint policy must explicitly enable checkpoints to receive this feedback. Visibility is checked in batches of up to 256 files and stops once eight visible files are found; each batch holds the event loop while the host resolves its paths, about 130 ms for a full batch on native Windows. Each file-check wait is one second, and post-command diagnostics have a three-second wait budget; past it, or when they fail as a whole, they are dropped and the command's result is kept. These are caller budgets, not hard I/O deadlines: running OS reads and inherited synchronous host callbacks cannot be forcibly interrupted. Private worker capacity remains bounded. Between 256 KiB and 2 MiB only syntax is checked: near 2 MiB that took 0.3-0.4 s and about 190 MiB here, up to four checks run at once, and on slower hardware such a check can outlast the one-second wait and report diagnostics unavailable. Python's GIL means concurrency does not promise a CPU speedup. Windows CI exercises the diagnostics layer with the real native DirectExecutor. The existing CodeExecutor environment probe uses POSIX quoting and already fails on Windows at the base; this PR neither changes that probe nor claims end-to-end compatibility for it. Symlink setup is skipped only if the host cannot create the fixture. Disable `pythonLint` for syntax-only feedback, `execPythonDiagnostics` for no post-command checks, or `pythonSyntaxNote` for no diagnostics, under `plugins.config["code-flow"].tools`. The PR can also be reverted as a unit. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: Codex <noreply@openai.com> Co-authored-by: Dizhan Xue <xuedizhan17@mails.ucas.ac.cn> Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-10-18 20:21:04 +08:00
lint=cfg.python_lint,
unused_imports=cfg.python_unused_imports,
feat(acp): a prompt is held open while the agent sleeps on an armed wake, and takes a steer ## Summary An on-call agent submits a job, arms a wake and ends its turn saying so; the wake runs a later turn on the session on its own clock. Over ACP that turn's `end_turn` read as "finished" to the caller: a DAG judging its node spent every continuation on "still watching, wake at 13:13" while the job ran fine (ar-r4, 2026-09-08), and the main agent re-dispatched the work by hand. ACP has no stop reason for "waiting". Replaces the closed !573: **no DAG code changes**, no new node status. The node is `running` because a turn is genuinely in flight. - **The signal.** The loop-hooks paper gains one key the ACP layer reads for itself: `acp_meta["raven.holdTurn"]` (`{"untilMs", "why"}`). oncall-flow files it at the send fire when the window's campaign is claimed, not concluded, and has one pending wake -- read the same way the owner's answer pulls that wake forward. No campaign, a wake that stood down, or a concluded campaign files nothing and the turn ends as before. - **The hold** (`raven/acp/methods.py`). A turn that ended `end_turn` with the key filed is not answered. One `tool_call` stands for the wait (its title names the campaign and the next look), with a `tool_call_update` heartbeat every `HOLD_HEARTBEAT_S` (60 s) so a client that clocks liveness by frames sees the agent alive while its model sleeps. The turn slot is reopened with no id to correlate on, so whichever turn ends next on the session -- the wake's, a steer's -- settles it, and the handler decides again from that turn's stash. A wake that arms again keeps the hold; a turn ending with nothing pending answers `end_turn`; a cancel answers `cancelled` as before. The key itself is not passed to the client. - **Steer.** `_raven/session/steer` is served and advertised under `agentCapabilities._meta` as `raven.steer` (the names raven's own client already uses). Accepted while a prompt is open on the session, held or running: the text is shown on the wire as the person's own line, then sent with `turn.send`'s new `busy: "inject"`. Answers `injected` / `no_turn`. - **Wire.** `turn.send` gains the optional `busy` param (`const "inject"`): an ordinary send on an idle lane, `BusyPolicy.INJECT` into the running turn otherwise -- the merge a channel's mid-turn message already gets (`gateway_commands.py`). No slot is bound for an injected message; the running turn keeps the lane's. `openrpc.json` and both generated clients moved together. What raven's client side already does, unchanged: the DAG stall watcher resets on any frame (the heartbeat keeps it quiet, and a stopped heartbeat raises the existing stall notice after ten minutes); a sub-agent process that dies fails the request and the node takes its ordinary path; the pool's `_responsive` treats a prompt in flight as busy. ## Review round 1 (2026-09-09, on !600, superseded by this MR) - **`busy: inject` reads the scheduler's lane state too.** `is_turn_active` knows only the turns `turn.send` started; an armed wake is submitted to the scheduler directly (`make_on_session_wake`) and never binds that map, so a steer during a running wake queued a second turn and answered `injected`. `turn.send` now asks `Scheduler.has_inflight(lane)` as well, and merges (`BusyPolicy.INJECT`) when either record says the lane is running. Pinned: `test_busy_inject_merges_into_a_wake_the_real_scheduler_is_running` -- the reviewer's reproduction on the real `Scheduler`, a turn submitted the way `make_on_session_wake` submits one; with the lane check bypassed it reads `pending=1, inject_mailbox=0`, with it `(1, 0)` in the mailbox and the running turn drains the text. - Branch renamed to snake_case and both commits carry the `Co-authored-by: Claude (<model-id>)` trailer, per AGENTS.md §2–3; that is why this MR replaces !600 rather than continuing it. ## Review round 2 (2026-09-10) - **A wake re-armed during its own run survives the writeback.** `CronService._writeback_locked` reloaded the store after the run and, for a one-shot with `delete_after_run`, overwrote the id with the finished run's state and removed it -- but the turn the wake ran had just called `schedule_wake` under the same key, so the id now named the *next* look. It vanished, and the held prompt had nothing left to settle it. A stored job under the fired id whose `at` schedule the run never had is treated as the new wake it is: claim cleared, run recorded, schedule kept, not deleted. Pinned on the real service: `test_a_wake_re_armed_during_its_own_run_survives_the_writeback` (reads `[]` without the fix, the reviewer's state) and the unchanged one-shot deletion beside it. Cron, proactive, sentinel and on-call suites: 968 passed. ## Review round 3 (2026-09-10) - **An undrained inject stays visible and cancellable.** `busy: inject` dropped the scheduler's handle; when the host turn ended past its last drain, the spine's fallback ran the text as a turn nothing owned -- `turn.cancel` a no-op, no `message.start`. The handle is now kept per lane under an id minted for the text; `turn.cancel` / `session.interrupt` reach it when the active slot is empty (mailbox, queued fallback, or running); and when the fallback turn starts, the RPC sink (`on_turn_start`, wired from bootstrap) binds the lane to it and opens it on the wire with the person's words. `turn.send` answers the inject's own id. Pinned through `build_rpc_spine` with the reviewer's shape (a loop that drains once, an inject after it): `test_an_undrained_inject_runs_as_a_turn_the_surface_can_see_and_cancel` and `test_a_pending_inject_can_be_cancelled_before_it_merges_or_falls_back`; both read the reviewer's state (`turn_ids` empty, cancel finding nothing) with the fix bypassed. - **Line ceiling.** The contract comment is five lines; `raven/contracts` is 2,519 against 2,520, one line of headroom on the current `main` (2,514). - Non-blocking items taken: `SchedulerDrainingError` on the inject path exits as `turn_failed`; the title is announced before the hold; the steer constants sit below the cancel constant's docstring; three edges pinned (a held prompt settled by a wake turn's uncorrelated ending through `send_frame`, the hold key never in the client's `_meta`, `raven.toolName` on the wait row). - Focused suite (reviewer's list plus the touched files): 948 passed on Python 3.12. ## Review round 4 (2026-09-10) - **Every pending inject is kept, per lane and per id.** One replaceable record per lane kept only the newest steer; two steers after the host's last drain fall back in turn, and the first started unowned while a cancel took out the second. The record is now `lane -> {inject id: (handle, text)}` in arrival order: each fallback promotes its own handle, and a cancel with no active turn reaches the oldest pending one -- the one the spine runs next. Pinned: `test_two_undrained_injects_each_get_their_own_turn_promoted_and_cancelled` (both promoted with their own ids and `message.start`, cancelled one after the other; runner saw all three turns). Focused suite: 949 passed. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification ``` uv run pytest tests/test_acp_methods.py tests/test_acp_protocol.py tests/test_rpc_turn_send.py \ tests/test_rpc_schema_match.py tests/test_acp_updates.py tests/test_acp_server.py -q # 766 passed uv run pytest tests/test_agents_oncall_flow_hooks.py tests/test_agents_oncall_flow_actions.py \ tests/test_agents_oncall_flow_budget.py tests/test_agents_oncall_flow_readings.py \ tests/test_agents_oncall_flow_escalation_tools.py -q # 99 passed uv run ruff check raven tests agents && uv run ruff format --check raven tests agents # clean uv run lint-imports # 9 kept, 0 broken cd ui-tui && npm run lint:rpc && npx tsc --noEmit; cd ui-web && npm run gen:check && npx tsc --noEmit # in sync, clean ``` New tests: `TestHeldTurn` (held across an armed wake, held again on a re-arm, heartbeat on the wait call, cancel while held, a non-`end_turn` stop is not held; every frame validated against the ACP schema), `TestSteer` (advertised, `no_turn` when idle, a held prompt takes the words as a turn with `busy: inject`, refusals), `busy: inject` on a busy and an idle lane in `test_rpc_turn_send.py`, and the plugin's hold stamping through the real `CronService` grant (filed with a pending wake; not filed without one, after the wake stands down, or once the campaign concluded). Not done: no end-to-end run of a real on-call wake through a held prompt yet -- unit tests only. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed (the hold is invisible to a person except as a "waiting for ..." tool row) ## Risk - [x] Backward compatibility considered: a turn that files no `raven.holdTurn` is answered exactly as before; `busy` is optional and absent from every existing caller; the steer method and capability are additive. - [x] Rollback path is clear: revert the two commits. A held prompt holds one `max_concurrent_subagents` slot (default 8) for the wait's duration on the caller's side; raised in config if it bites. ## Related Replaces !573 (closed). Follows !518 (stall notice) and !520 (unprompted-turn route; a wake that runs under a held prompt no longer takes it for DAG nodes).
2026-09-11 02:37:55 +00:00
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:
feat(docker): run raven in a docker container and make a first run configurable from the page ## Summary Two things arrive together because the second is what made the first usable. **Run raven from a container.** A Dockerfile builds the page, the Python environment and the engine into one image; `cd docker && docker compose up` serves it. nginx serves the built page and proxies the RPC socket to the engine over the loopback they share -- the engine binds 127.0.0.1 only, so a proxy in a second container would have no address to dial. Compose publishes on 127.0.0.1, and the entrypoint prints a one-time sign-in link on boot. **A first run is no longer a dead end.** The gateway used to refuse to start until a provider was configured, while being the thing that serves the page where a provider gets configured. It now starts, says what is missing, and picks up a key saved in Settings on the next turn without a restart. The onboarding overlay no longer takes the page either: New chat, the model chip and Send send the reader to Settings > Models instead, and an empty model list is marked on the control that fills it. Also carried: the provider catalogue registry (capabilities, modalities and context windows per model), the reworked Settings > Models pane, and four fixes found in review of that work -- a sibling catalogue answering 200 with a non-catalogue body no longer crashes the whole fetch; adding a tag no longer erases the label and description already stored for that model; `authenticated` no longer demands a bearer token from a local provider reached by address; and registry rows are keyed by the spelling every lookup produces, which recovers 593 rows that no reader could reach. ## Type - [ ] Fix - [x] Feature - [x] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification Commands run on the branch head, with their results: - `uv run pytest tests -q -k "provider or registry or catalog or model or rpc or gateway or docker or i18n"` -- 4389 passed, 46 skipped - `npx vitest run` in `ui-web` -- 1573 passed (101 files) - `npx vitest run` in `ui-tui` -- 2037 passed (142 files) - `uv run ruff check raven scripts tests` and `ruff format --check` -- clean - `npx tsc --noEmit` in `ui-web` and `npm run type-check` in `ui-tui` -- clean - `npm run lint:rpc` in `ui-tui` -- generated.ts in sync - `make check-source-language`, `make check-large-files` -- clean Each of the four review fixes was checked by reverting it and watching a named test go red, then restoring it. The container image itself has not been built by CI or by me -- no Docker daemon was available on the machine this was written on. It has been built and run by the author of the branch. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk Two deliberate security trade-offs in the container deployment, both documented in `docker/README.md`: - nginx rewrites the `Origin` header, because the engine accepts only an Origin naming its own loopback port and no browser reaching a published port can send one. This drops a defence-in-depth layer. The session cookie is SameSite=Strict, so an unauthenticated socket is still refused -- but SameSite ignores ports, so another page on localhost counts as same-site. - `RAVEN_AUTO_LOGIN=1` is the default: nginx attaches the session cookie to every page load, so anyone who can reach the published port is signed in. It is contained by Compose publishing on 127.0.0.1 only. Set it to 0 for any deployment reachable from elsewhere. These are two settings that must agree, and nothing warns when they do not. Behaviour changes outside the container: the gateway now starts without a configured provider rather than exiting 1, and the first-run onboarding overlay no longer opens by default (`?onboard=1` still forces it). Rollback is by revert; nothing here migrates state or changes an on-disk format. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A
2026-09-11 03:27:52 +00:00
"""The shell, with the clamped ceiling, the partial-output marker and the
feat(acp): a prompt is held open while the agent sleeps on an armed wake, and takes a steer ## Summary An on-call agent submits a job, arms a wake and ends its turn saying so; the wake runs a later turn on the session on its own clock. Over ACP that turn's `end_turn` read as "finished" to the caller: a DAG judging its node spent every continuation on "still watching, wake at 13:13" while the job ran fine (ar-r4, 2026-09-08), and the main agent re-dispatched the work by hand. ACP has no stop reason for "waiting". Replaces the closed !573: **no DAG code changes**, no new node status. The node is `running` because a turn is genuinely in flight. - **The signal.** The loop-hooks paper gains one key the ACP layer reads for itself: `acp_meta["raven.holdTurn"]` (`{"untilMs", "why"}`). oncall-flow files it at the send fire when the window's campaign is claimed, not concluded, and has one pending wake -- read the same way the owner's answer pulls that wake forward. No campaign, a wake that stood down, or a concluded campaign files nothing and the turn ends as before. - **The hold** (`raven/acp/methods.py`). A turn that ended `end_turn` with the key filed is not answered. One `tool_call` stands for the wait (its title names the campaign and the next look), with a `tool_call_update` heartbeat every `HOLD_HEARTBEAT_S` (60 s) so a client that clocks liveness by frames sees the agent alive while its model sleeps. The turn slot is reopened with no id to correlate on, so whichever turn ends next on the session -- the wake's, a steer's -- settles it, and the handler decides again from that turn's stash. A wake that arms again keeps the hold; a turn ending with nothing pending answers `end_turn`; a cancel answers `cancelled` as before. The key itself is not passed to the client. - **Steer.** `_raven/session/steer` is served and advertised under `agentCapabilities._meta` as `raven.steer` (the names raven's own client already uses). Accepted while a prompt is open on the session, held or running: the text is shown on the wire as the person's own line, then sent with `turn.send`'s new `busy: "inject"`. Answers `injected` / `no_turn`. - **Wire.** `turn.send` gains the optional `busy` param (`const "inject"`): an ordinary send on an idle lane, `BusyPolicy.INJECT` into the running turn otherwise -- the merge a channel's mid-turn message already gets (`gateway_commands.py`). No slot is bound for an injected message; the running turn keeps the lane's. `openrpc.json` and both generated clients moved together. What raven's client side already does, unchanged: the DAG stall watcher resets on any frame (the heartbeat keeps it quiet, and a stopped heartbeat raises the existing stall notice after ten minutes); a sub-agent process that dies fails the request and the node takes its ordinary path; the pool's `_responsive` treats a prompt in flight as busy. ## Review round 1 (2026-09-09, on !600, superseded by this MR) - **`busy: inject` reads the scheduler's lane state too.** `is_turn_active` knows only the turns `turn.send` started; an armed wake is submitted to the scheduler directly (`make_on_session_wake`) and never binds that map, so a steer during a running wake queued a second turn and answered `injected`. `turn.send` now asks `Scheduler.has_inflight(lane)` as well, and merges (`BusyPolicy.INJECT`) when either record says the lane is running. Pinned: `test_busy_inject_merges_into_a_wake_the_real_scheduler_is_running` -- the reviewer's reproduction on the real `Scheduler`, a turn submitted the way `make_on_session_wake` submits one; with the lane check bypassed it reads `pending=1, inject_mailbox=0`, with it `(1, 0)` in the mailbox and the running turn drains the text. - Branch renamed to snake_case and both commits carry the `Co-authored-by: Claude (<model-id>)` trailer, per AGENTS.md §2–3; that is why this MR replaces !600 rather than continuing it. ## Review round 2 (2026-09-10) - **A wake re-armed during its own run survives the writeback.** `CronService._writeback_locked` reloaded the store after the run and, for a one-shot with `delete_after_run`, overwrote the id with the finished run's state and removed it -- but the turn the wake ran had just called `schedule_wake` under the same key, so the id now named the *next* look. It vanished, and the held prompt had nothing left to settle it. A stored job under the fired id whose `at` schedule the run never had is treated as the new wake it is: claim cleared, run recorded, schedule kept, not deleted. Pinned on the real service: `test_a_wake_re_armed_during_its_own_run_survives_the_writeback` (reads `[]` without the fix, the reviewer's state) and the unchanged one-shot deletion beside it. Cron, proactive, sentinel and on-call suites: 968 passed. ## Review round 3 (2026-09-10) - **An undrained inject stays visible and cancellable.** `busy: inject` dropped the scheduler's handle; when the host turn ended past its last drain, the spine's fallback ran the text as a turn nothing owned -- `turn.cancel` a no-op, no `message.start`. The handle is now kept per lane under an id minted for the text; `turn.cancel` / `session.interrupt` reach it when the active slot is empty (mailbox, queued fallback, or running); and when the fallback turn starts, the RPC sink (`on_turn_start`, wired from bootstrap) binds the lane to it and opens it on the wire with the person's words. `turn.send` answers the inject's own id. Pinned through `build_rpc_spine` with the reviewer's shape (a loop that drains once, an inject after it): `test_an_undrained_inject_runs_as_a_turn_the_surface_can_see_and_cancel` and `test_a_pending_inject_can_be_cancelled_before_it_merges_or_falls_back`; both read the reviewer's state (`turn_ids` empty, cancel finding nothing) with the fix bypassed. - **Line ceiling.** The contract comment is five lines; `raven/contracts` is 2,519 against 2,520, one line of headroom on the current `main` (2,514). - Non-blocking items taken: `SchedulerDrainingError` on the inject path exits as `turn_failed`; the title is announced before the hold; the steer constants sit below the cancel constant's docstring; three edges pinned (a held prompt settled by a wake turn's uncorrelated ending through `send_frame`, the hold key never in the client's `_meta`, `raven.toolName` on the wait row). - Focused suite (reviewer's list plus the touched files): 948 passed on Python 3.12. ## Review round 4 (2026-09-10) - **Every pending inject is kept, per lane and per id.** One replaceable record per lane kept only the newest steer; two steers after the host's last drain fall back in turn, and the first started unowned while a cancel took out the second. The record is now `lane -> {inject id: (handle, text)}` in arrival order: each fallback promotes its own handle, and a cancel with no active turn reaches the oldest pending one -- the one the spine runs next. Pinned: `test_two_undrained_injects_each_get_their_own_turn_promoted_and_cancelled` (both promoted with their own ids and `message.start`, cancelled one after the other; runner saw all three turns). Focused suite: 949 passed. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification ``` uv run pytest tests/test_acp_methods.py tests/test_acp_protocol.py tests/test_rpc_turn_send.py \ tests/test_rpc_schema_match.py tests/test_acp_updates.py tests/test_acp_server.py -q # 766 passed uv run pytest tests/test_agents_oncall_flow_hooks.py tests/test_agents_oncall_flow_actions.py \ tests/test_agents_oncall_flow_budget.py tests/test_agents_oncall_flow_readings.py \ tests/test_agents_oncall_flow_escalation_tools.py -q # 99 passed uv run ruff check raven tests agents && uv run ruff format --check raven tests agents # clean uv run lint-imports # 9 kept, 0 broken cd ui-tui && npm run lint:rpc && npx tsc --noEmit; cd ui-web && npm run gen:check && npx tsc --noEmit # in sync, clean ``` New tests: `TestHeldTurn` (held across an armed wake, held again on a re-arm, heartbeat on the wait call, cancel while held, a non-`end_turn` stop is not held; every frame validated against the ACP schema), `TestSteer` (advertised, `no_turn` when idle, a held prompt takes the words as a turn with `busy: inject`, refusals), `busy: inject` on a busy and an idle lane in `test_rpc_turn_send.py`, and the plugin's hold stamping through the real `CronService` grant (filed with a pending wake; not filed without one, after the wake stands down, or once the campaign concluded). Not done: no end-to-end run of a real on-call wake through a held prompt yet -- unit tests only. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed (the hold is invisible to a person except as a "waiting for ..." tool row) ## Risk - [x] Backward compatibility considered: a turn that files no `raven.holdTurn` is answered exactly as before; `busy` is optional and absent from every existing caller; the steer method and capability are additive. - [x] Rollback path is clear: revert the two commits. A held prompt holds one `max_concurrent_subagents` slot (default 8) for the wait's duration on the caller's side; raised in config if it bites. ## Related Replaces !573 (closed). Follows !518 (stall notice) and !520 (unprompted-turn route; a wake that runs under a held prompt no longer takes it for DAG nodes).
2026-09-11 02:37:55 +00:00
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,
feat(*): add bounded Python diagnostics after code edits (#967) ## Summary Raven-Code reports Python syntax errors after file edits but misses unresolved names and equivalent feedback after shell edits. Add advisory Pyflakes F821/F822/F823 checks to the existing tool result; optional F401 notices remain off by default. No additional model call or code execution is involved. ```text write_file / edit_file -> inspect final source, compare with a baseline that can be read and analyzed -> retain syntax warnings; suppress existing name findings exec -> require checkpoint visibility for the working directory -> read the changed files from the host's write record for the command -> ask visibility in batches of 256, select at most 8, check up to 4 concurrently -> append ordered diagnostics, preserving exit status and file metadata ``` Existing syntax failures remain visible after unrelated edits and identical rewrites. A baseline that cannot be read, parsed or analyzed is marked unknown; overwriting non-UTF-8 source still checks the known replacement. Source nested too deeply for the parser or checker, and a changed file that cannot be read, report diagnostics unavailable for that file rather than passing as clean. Every check reads a file as the bytes Python runs: text a write or edit stores is checked as its UTF-8 bytes, the content it replaced included, and a file from disk as its bytes, each decoded as Python decodes source, by its coding declaration or as UTF-8. Bytes that do not decode are reported as a syntax error at the line where decoding stops, so a declaration the written text cannot satisfy is reported however the file was changed. Noqa comments are read as Ruff reads them, including after other comment directives and never inside string literals: a file-level `ruff: noqa` / `flake8: noqa` counts only on a line of its own, and a marker counts only when codes follow its colon or, with no colon, whitespace, another comment or the end of the comment follows it. Unlike Ruff, which takes the first directive in a comment, every directive in it counts. The seeded tool guide gives the syntax note's own advice. With no checkpoint or no visibility verdict, exec diagnostics do not inspect changed file contents; direct file checks remain available. Pyflakes is imported when the tool face loads, not by whichever check first needs it: imported lazily, its cold import fell inside that check's one-second wait, and on a slow Windows runner the one test that paid it reported diagnostics unavailable for a plain syntax error. Private workers bound reads and checks to four active jobs per process. Saturated capacity rejects new work without queuing, and timeout/cancellation retains each slot until the actual work finishes. Name checks are capped at 256 KiB of source and the syntax check at 2 MiB, and a check skipped for size says so in one line. Findings are capped at eight per file, and exec diagnostic text at 6,000 characters plus omission notices. Runtime changes stay inside the Raven-Code code-flow plugin, except for one fix to `CheckpointService.trackable`, the visibility verdict that exec diagnostics and the host's exec write record both rely on. On macOS, git precomposes a file name it reads off the disk before matching an ignore rule, but takes the paths `trackable` sends to `git check-ignore --stdin` as written. A file stored with a decomposed (NFD) name under a `.gitignore` rule written precomposed (NFC) is therefore left out of the checkpoint, yet main vouches for it, so the write record's diff carries its text, and exec diagnostics would quote its source lines to the model. Nor is git's precomposition NFC: it composes only neighbouring characters, by Unicode 3.2's table, and reorders nothing, so a name whose combining marks are out of canonical order comes out as neither the name as given nor its NFC. `trackable` now asks about each name as given, as NFC and in git's macOS spelling, and withholds it when any spelling is ignored. Other shared file/shell/snapshot implementations are unchanged. Raven-Code has no separate dependency manifest, so Pyflakes uses the existing root dependencies. It is the only added package; uv normalized existing lockfile markers without changing other package versions. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification - **Before:** on main, Raven-Code's file tools report Python syntax errors only, and its exec reports nothing about the Python files a command changed. On macOS, main's `CheckpointService.trackable` vouches for a file stored as `secret_cafe` + U+0301 + `.py` under the rule `secret_caf` + U+00E9 + `.py`: the user's own git ignores it and the checkpoint's staged tree leaves it out, yet its text reaches the exec write record's stored diff. - **After:** on macOS 26.6.2 / arm64 with Apple Git 2.54.0, the command below passes 364 tests on Python 3.12.13 and on 3.14.6. The full default suite on 3.12.13 has 32283 passed, 169 skipped, 20 failed and 3 errors over 22 test ids: 21 of them also fail on the exact base in the same environment, and the other, a remote process-tree cancel test that missed its deadline under the suite's load, passes when run alone. Tests cover actual worker overlap, retained capacity after timeout/cancellation, host-tool isolation, hidden-file quotas, visibility batching through the host's write-record wiring, baseline handling, parser-limit failures, the size bounds and their skip notes, undecodable bytes placed where decoding stops, coding declarations in written and edited text, the baseline read staying on a worker, the checker loaded with its module, the file each unavailable note names, comment directives and their marker boundary, the tool guide's agreement with the syntax note, portable commands in paths with spaces/non-ASCII characters, and the checkpoint's verdict on decomposed names and on names git spells as neither given nor NFC, held against its own staged tree. Removing any of the three spellings from the query fails the cases that pin it, as does removing the marker boundary, the parser-limit report, the unknown-baseline handling, the syntax check past the name-check bound and the decoding report, checking written text as its stored bytes, the worker around the baseline read, loading the checker with its module, or the file name in an unavailable note; restoring the guide's earlier advice fails its agreement test. git's macOS spelling is what libiconv's UTF-8-MAC conversion returns, which git precomposes with: composing neighbours by Unicode 3.2's table reproduced it for all 281,928 names built from every decomposable character's decomposition (reordered, partly composed, or with a mark added), and across 784,220 further mixed names and pairs no name was spelled outside the three asked; the same held under Python 3.13 and 3.14. The decomposed-name check asserts the macOS outcome only where git precomposes names, so it also passes with `core.precomposeunicode = false` set through `GIT_CONFIG_GLOBAL`. Across 102 noqa comment variants the reported lines match Ruff 0.15.12, except the three that hold several directives in one comment. Through the real `AgentLoop`, code-flow tool face, `CodeExecutor` and checkpoint, with the working directory under `/tmp`, under `$TMPDIR` and in a path with spaces and CJK characters, exec diagnostics report created, modified and decomposed-name files, follow `working_dir`, report an undecodable file at the line where decoding stops, a syntax error past 256 KiB and a skip past 2 MiB, and withhold `.gitignore`d files, including decomposed names and names git spells as neither given nor NFC; across repeated runs on both interpreters, a file near the 256 KiB cap is checked in 52-135 ms (117-128 ms against a baseline), the syntax of a file near 2 MiB in 318-371 ms, and 600 ignored files plus one visible file take 73-90 ms with the event loop held at most 20 ms. At this head CI passes the unit suite on Linux/Python 3.12 (32619 tests over four shards), and its two Windows steps pass the diagnostic files on native Windows/Python 3.13: 122 file/worker tests, and 27 exec diagnostic tests with 17 pre-existing executor tests deselected; the symlink fixture skips only where the host cannot create links. ```sh env -u SERPER_API_KEY -u RAVEN_MIRRORED_SERPER_API_KEY uv run --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_flow_exec.py tests/test_agents_code_flow_plugin.py tests/test_agents_code_flow_read_state.py tests/test_agents_code_launcher.py tests/test_workdir_snapshot.py tests/test_shell_command_writes.py tests/test_runtime_checkpoint.py tests/test_trajectory_upload.py::test_blocked_upload_hits_the_deadline -o addopts= -q --tb=short --maxfail=3 uv run --no-sync ruff check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_diagnostic_workers.py uv run --no-sync ty check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py uv run --no-sync lint-imports uv run --no-sync ruff format --check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py ``` Native Windows CI commands: ```sh uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py -q -n 0 --tb=short uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_flow_exec.py -k test_exec_ -q -n 0 --tb=short ``` Ruff, format and type checks passed; all 10 import contracts kept; the commit-message, large-file and source-language checks pass over the branch. The launcher tests unset inherited search API keys to keep the expected tool list deterministic. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk Scope: Raven-Code's enabled code-flow tool face; installing Pyflakes does not activate checks in other agents. The change is reversible and never fixes/removes code or rolls back edits. Static diagnostics can need judgment for dynamic names, target Python versions, and project lint configuration; only explicit noqa directives are honored. Passing diagnostics do not replace tests. The `trackable` fix reaches every exec write record, not only Raven-Code: a file whose name, as given, as NFC or in git's macOS spelling, matches an ignore rule keeps its counts and loses its diff and removal body. Where git matches another of those spellings, as off macOS for a decomposed name under a precomposed rule, the checkpoint stores the file but it is still withheld; its counts remain. Exec diagnostics now require an active checkpoint. Noninteractive runs using the default interactive checkpoint policy must explicitly enable checkpoints to receive this feedback. Visibility is checked in batches of up to 256 files and stops once eight visible files are found; each batch holds the event loop while the host resolves its paths, about 130 ms for a full batch on native Windows. Each file-check wait is one second, and post-command diagnostics have a three-second wait budget; past it, or when they fail as a whole, they are dropped and the command's result is kept. These are caller budgets, not hard I/O deadlines: running OS reads and inherited synchronous host callbacks cannot be forcibly interrupted. Private worker capacity remains bounded. Between 256 KiB and 2 MiB only syntax is checked: near 2 MiB that took 0.3-0.4 s and about 190 MiB here, up to four checks run at once, and on slower hardware such a check can outlast the one-second wait and report diagnostics unavailable. Python's GIL means concurrency does not promise a CPU speedup. Windows CI exercises the diagnostics layer with the real native DirectExecutor. The existing CodeExecutor environment probe uses POSIX quoting and already fails on Windows at the base; this PR neither changes that probe nor claims end-to-end compatibility for it. Symlink setup is skipped only if the host cannot create the fixture. Disable `pythonLint` for syntax-only feedback, `execPythonDiagnostics` for no post-command checks, or `pythonSyntaxNote` for no diagnostics, under `plugins.config["code-flow"].tools`. The PR can also be reverted as a unit. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: Codex <noreply@openai.com> Co-authored-by: Dizhan Xue <xuedizhan17@mails.ucas.ac.cn> Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-10-18 20:21:04 +08:00
python_diagnostics=cfg.python_syntax_note and cfg.exec_python_diagnostics,
python_lint=cfg.python_lint,
python_unused_imports=cfg.python_unused_imports,
feat(acp): a prompt is held open while the agent sleeps on an armed wake, and takes a steer ## Summary An on-call agent submits a job, arms a wake and ends its turn saying so; the wake runs a later turn on the session on its own clock. Over ACP that turn's `end_turn` read as "finished" to the caller: a DAG judging its node spent every continuation on "still watching, wake at 13:13" while the job ran fine (ar-r4, 2026-09-08), and the main agent re-dispatched the work by hand. ACP has no stop reason for "waiting". Replaces the closed !573: **no DAG code changes**, no new node status. The node is `running` because a turn is genuinely in flight. - **The signal.** The loop-hooks paper gains one key the ACP layer reads for itself: `acp_meta["raven.holdTurn"]` (`{"untilMs", "why"}`). oncall-flow files it at the send fire when the window's campaign is claimed, not concluded, and has one pending wake -- read the same way the owner's answer pulls that wake forward. No campaign, a wake that stood down, or a concluded campaign files nothing and the turn ends as before. - **The hold** (`raven/acp/methods.py`). A turn that ended `end_turn` with the key filed is not answered. One `tool_call` stands for the wait (its title names the campaign and the next look), with a `tool_call_update` heartbeat every `HOLD_HEARTBEAT_S` (60 s) so a client that clocks liveness by frames sees the agent alive while its model sleeps. The turn slot is reopened with no id to correlate on, so whichever turn ends next on the session -- the wake's, a steer's -- settles it, and the handler decides again from that turn's stash. A wake that arms again keeps the hold; a turn ending with nothing pending answers `end_turn`; a cancel answers `cancelled` as before. The key itself is not passed to the client. - **Steer.** `_raven/session/steer` is served and advertised under `agentCapabilities._meta` as `raven.steer` (the names raven's own client already uses). Accepted while a prompt is open on the session, held or running: the text is shown on the wire as the person's own line, then sent with `turn.send`'s new `busy: "inject"`. Answers `injected` / `no_turn`. - **Wire.** `turn.send` gains the optional `busy` param (`const "inject"`): an ordinary send on an idle lane, `BusyPolicy.INJECT` into the running turn otherwise -- the merge a channel's mid-turn message already gets (`gateway_commands.py`). No slot is bound for an injected message; the running turn keeps the lane's. `openrpc.json` and both generated clients moved together. What raven's client side already does, unchanged: the DAG stall watcher resets on any frame (the heartbeat keeps it quiet, and a stopped heartbeat raises the existing stall notice after ten minutes); a sub-agent process that dies fails the request and the node takes its ordinary path; the pool's `_responsive` treats a prompt in flight as busy. ## Review round 1 (2026-09-09, on !600, superseded by this MR) - **`busy: inject` reads the scheduler's lane state too.** `is_turn_active` knows only the turns `turn.send` started; an armed wake is submitted to the scheduler directly (`make_on_session_wake`) and never binds that map, so a steer during a running wake queued a second turn and answered `injected`. `turn.send` now asks `Scheduler.has_inflight(lane)` as well, and merges (`BusyPolicy.INJECT`) when either record says the lane is running. Pinned: `test_busy_inject_merges_into_a_wake_the_real_scheduler_is_running` -- the reviewer's reproduction on the real `Scheduler`, a turn submitted the way `make_on_session_wake` submits one; with the lane check bypassed it reads `pending=1, inject_mailbox=0`, with it `(1, 0)` in the mailbox and the running turn drains the text. - Branch renamed to snake_case and both commits carry the `Co-authored-by: Claude (<model-id>)` trailer, per AGENTS.md §2–3; that is why this MR replaces !600 rather than continuing it. ## Review round 2 (2026-09-10) - **A wake re-armed during its own run survives the writeback.** `CronService._writeback_locked` reloaded the store after the run and, for a one-shot with `delete_after_run`, overwrote the id with the finished run's state and removed it -- but the turn the wake ran had just called `schedule_wake` under the same key, so the id now named the *next* look. It vanished, and the held prompt had nothing left to settle it. A stored job under the fired id whose `at` schedule the run never had is treated as the new wake it is: claim cleared, run recorded, schedule kept, not deleted. Pinned on the real service: `test_a_wake_re_armed_during_its_own_run_survives_the_writeback` (reads `[]` without the fix, the reviewer's state) and the unchanged one-shot deletion beside it. Cron, proactive, sentinel and on-call suites: 968 passed. ## Review round 3 (2026-09-10) - **An undrained inject stays visible and cancellable.** `busy: inject` dropped the scheduler's handle; when the host turn ended past its last drain, the spine's fallback ran the text as a turn nothing owned -- `turn.cancel` a no-op, no `message.start`. The handle is now kept per lane under an id minted for the text; `turn.cancel` / `session.interrupt` reach it when the active slot is empty (mailbox, queued fallback, or running); and when the fallback turn starts, the RPC sink (`on_turn_start`, wired from bootstrap) binds the lane to it and opens it on the wire with the person's words. `turn.send` answers the inject's own id. Pinned through `build_rpc_spine` with the reviewer's shape (a loop that drains once, an inject after it): `test_an_undrained_inject_runs_as_a_turn_the_surface_can_see_and_cancel` and `test_a_pending_inject_can_be_cancelled_before_it_merges_or_falls_back`; both read the reviewer's state (`turn_ids` empty, cancel finding nothing) with the fix bypassed. - **Line ceiling.** The contract comment is five lines; `raven/contracts` is 2,519 against 2,520, one line of headroom on the current `main` (2,514). - Non-blocking items taken: `SchedulerDrainingError` on the inject path exits as `turn_failed`; the title is announced before the hold; the steer constants sit below the cancel constant's docstring; three edges pinned (a held prompt settled by a wake turn's uncorrelated ending through `send_frame`, the hold key never in the client's `_meta`, `raven.toolName` on the wait row). - Focused suite (reviewer's list plus the touched files): 948 passed on Python 3.12. ## Review round 4 (2026-09-10) - **Every pending inject is kept, per lane and per id.** One replaceable record per lane kept only the newest steer; two steers after the host's last drain fall back in turn, and the first started unowned while a cancel took out the second. The record is now `lane -> {inject id: (handle, text)}` in arrival order: each fallback promotes its own handle, and a cancel with no active turn reaches the oldest pending one -- the one the spine runs next. Pinned: `test_two_undrained_injects_each_get_their_own_turn_promoted_and_cancelled` (both promoted with their own ids and `message.start`, cancelled one after the other; runner saw all three turns). Focused suite: 949 passed. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification ``` uv run pytest tests/test_acp_methods.py tests/test_acp_protocol.py tests/test_rpc_turn_send.py \ tests/test_rpc_schema_match.py tests/test_acp_updates.py tests/test_acp_server.py -q # 766 passed uv run pytest tests/test_agents_oncall_flow_hooks.py tests/test_agents_oncall_flow_actions.py \ tests/test_agents_oncall_flow_budget.py tests/test_agents_oncall_flow_readings.py \ tests/test_agents_oncall_flow_escalation_tools.py -q # 99 passed uv run ruff check raven tests agents && uv run ruff format --check raven tests agents # clean uv run lint-imports # 9 kept, 0 broken cd ui-tui && npm run lint:rpc && npx tsc --noEmit; cd ui-web && npm run gen:check && npx tsc --noEmit # in sync, clean ``` New tests: `TestHeldTurn` (held across an armed wake, held again on a re-arm, heartbeat on the wait call, cancel while held, a non-`end_turn` stop is not held; every frame validated against the ACP schema), `TestSteer` (advertised, `no_turn` when idle, a held prompt takes the words as a turn with `busy: inject`, refusals), `busy: inject` on a busy and an idle lane in `test_rpc_turn_send.py`, and the plugin's hold stamping through the real `CronService` grant (filed with a pending wake; not filed without one, after the wake stands down, or once the campaign concluded). Not done: no end-to-end run of a real on-call wake through a held prompt yet -- unit tests only. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed (the hold is invisible to a person except as a "waiting for ..." tool row) ## Risk - [x] Backward compatibility considered: a turn that files no `raven.holdTurn` is answered exactly as before; `busy` is optional and absent from every existing caller; the steer method and capability are additive. - [x] Rollback path is clear: revert the two commits. A held prompt holds one `max_concurrent_subagents` slot (default 8) for the wait's duration on the caller's side; raised in config if it bites. ## Related Replaces !573 (closed). Follows !518 (stall notice) and !520 (unprompted-turn route; a wake that runs under a held prompt no longer takes it for DAG nodes).
2026-09-11 02:37:55 +00:00
)
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",
]