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
|
|
|
"""``glob``: the fork's spelling of trunk's pathname-pattern tool.
|
|
|
|
|
|
|
|
|
|
Same engine, one name and one description: the fork measured that models
|
|
|
|
|
trained on the common convention reach for ``glob`` and read its output as a
|
|
|
|
|
listing, not as a command to run. The product config withholds trunk's
|
|
|
|
|
``find`` so the face carries one spelling.
|
|
|
|
|
|
|
|
|
|
Brace alternation (``*.{ts,tsx}``) is part of that convention and trunk's
|
|
|
|
|
engine takes one pattern, so it is expanded here and the listings are merged.
|
|
|
|
|
The engine returns paths together with status text. The merge preserves
|
|
|
|
|
errors, carries any child truncation into the final notice, deduplicates the
|
|
|
|
|
paths and sorts them by recency before applying the caller's total limit.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import re
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
from raven.agent.tools import file_search as trunk
|
|
|
|
|
|
|
|
|
|
#: How many patterns one brace expression may expand to. Past it the call is
|
|
|
|
|
#: refused rather than silently searching a subset -- a listing that quietly
|
|
|
|
|
#: omits half the alternatives reads exactly like a directory that lacks them.
|
|
|
|
|
BRACE_CAP = 20
|
|
|
|
|
|
|
|
|
|
#: The engine's own lines, which are not paths. Matched, not guessed: each is
|
|
|
|
|
#: a literal the engine writes (``file_search.FindTool``).
|
|
|
|
|
_NOTICE_RE = re.compile(
|
|
|
|
|
r"^\(showing first \d+(?: of \d+ results| results across \d+ patterns)(?:; PARTIAL.*)?\)$"
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
r"|^\(PARTIAL result: .*\)$"
|
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
|
|
|
r"|^No files found matching pattern(?:\.|: .*)$"
|
|
|
|
|
r"|^Error: |^Error running find: ",
|
|
|
|
|
)
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
#: The engine's one trailing notice, which carries a clause per condition: the
|
|
|
|
|
#: listing was cut at the limit, the walk hit its traversal budget, or both.
|
|
|
|
|
_CHILD_CUT_RE = re.compile(r"^\(showing first \d+ of \d+ results(?:; PARTIAL result: .*)?\)$")
|
|
|
|
|
_CHILD_INCOMPLETE_RE = re.compile(r"^\((?:showing first \d+ of \d+ results; )?PARTIAL result: .*\)$")
|
|
|
|
|
_NO_FILES = "No files found matching pattern."
|
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 is_notice(line: str) -> bool:
|
|
|
|
|
"""Whether this output line is the engine talking, not a path."""
|
|
|
|
|
return bool(_NOTICE_RE.match(line.strip()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def expand_braces(pattern: str) -> list[str]:
|
|
|
|
|
"""Every ``{a,b}`` group expanded, innermost-first, in listed order.
|
|
|
|
|
|
|
|
|
|
Returns the pattern unchanged when it carries no group, and raises
|
|
|
|
|
``ValueError`` when the expansion would exceed :data:`BRACE_CAP` or the
|
|
|
|
|
braces do not pair -- the caller turns either into a refusal the model can
|
|
|
|
|
act on.
|
|
|
|
|
"""
|
|
|
|
|
if "{" not in pattern:
|
|
|
|
|
return [pattern]
|
|
|
|
|
start = pattern.find("{")
|
|
|
|
|
depth = 0
|
|
|
|
|
end = -1
|
|
|
|
|
for index in range(start, len(pattern)):
|
|
|
|
|
if pattern[index] == "{":
|
|
|
|
|
depth += 1
|
|
|
|
|
elif pattern[index] == "}":
|
|
|
|
|
depth -= 1
|
|
|
|
|
if depth == 0:
|
|
|
|
|
end = index
|
|
|
|
|
break
|
|
|
|
|
if end < 0:
|
|
|
|
|
raise ValueError(f"unbalanced braces in pattern {pattern!r}")
|
|
|
|
|
alternatives = _split_top_level(pattern[start + 1 : end])
|
|
|
|
|
out: list[str] = []
|
|
|
|
|
for alt in alternatives:
|
|
|
|
|
for rest in expand_braces(pattern[:start] + alt + pattern[end + 1 :]):
|
|
|
|
|
if rest not in out:
|
|
|
|
|
out.append(rest)
|
|
|
|
|
if len(out) > BRACE_CAP:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"pattern {pattern!r} expands to more than {BRACE_CAP} patterns; "
|
|
|
|
|
"search the alternatives in separate calls"
|
|
|
|
|
)
|
|
|
|
|
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _split_top_level(body: str) -> list[str]:
|
|
|
|
|
"""Split on commas that are not inside a nested group."""
|
|
|
|
|
parts: list[str] = []
|
|
|
|
|
depth = 0
|
|
|
|
|
current: list[str] = []
|
|
|
|
|
for char in body:
|
|
|
|
|
if char == "{":
|
|
|
|
|
depth += 1
|
|
|
|
|
elif char == "}":
|
|
|
|
|
depth -= 1
|
|
|
|
|
if char == "," and depth == 0:
|
|
|
|
|
parts.append("".join(current))
|
|
|
|
|
current = []
|
|
|
|
|
continue
|
|
|
|
|
current.append(char)
|
|
|
|
|
parts.append("".join(current))
|
|
|
|
|
return parts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class GlobTool(trunk.FindTool):
|
|
|
|
|
@property
|
|
|
|
|
def name(self) -> str:
|
|
|
|
|
return "glob"
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def description(self) -> str:
|
|
|
|
|
return (
|
|
|
|
|
"Find files by glob pattern (e.g. '*.py', 'src/**/*.ts' or '*.{ts,tsx}'). Prefer this over "
|
|
|
|
|
"running find/ls through exec. Returns paths relative to the search root, "
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
"most-recently-modified first. Noise directories (.git, node_modules, etc.) are "
|
|
|
|
|
"skipped below the pattern's literal path prefix; one named inside that prefix, as in "
|
|
|
|
|
"'src/node_modules/*.js', is entered. "
|
|
|
|
|
"Use it to locate a file before reading or editing it instead of "
|
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
|
|
|
"guessing at the path. Brace alternatives share one limit after deduplication and sorting. "
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
"A notice naming the limit means the result was cut there: raise limit or narrow the pattern. "
|
|
|
|
|
"A notice naming the traversal budget means the walk ran out of time: absence of a match is not "
|
|
|
|
|
"conclusive there, and only a narrower path or pattern helps."
|
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
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def parameters(self) -> dict[str, Any]:
|
|
|
|
|
base = super().parameters
|
|
|
|
|
props = dict(base["properties"])
|
|
|
|
|
if "pattern" in props:
|
|
|
|
|
props["pattern"] = {
|
|
|
|
|
**props["pattern"],
|
|
|
|
|
"description": "Glob pattern, e.g. '*.py', 'src/**/*.ts' or '*.{ts,tsx}'",
|
|
|
|
|
}
|
|
|
|
|
if "path" in props:
|
|
|
|
|
props["path"] = {**props["path"], "description": "Directory to search in (default: workspace root)"}
|
|
|
|
|
props["limit"] = {
|
|
|
|
|
**props["limit"],
|
|
|
|
|
"description": "Maximum unique entries across all patterns (default 1000). "
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
"Raise it when a notice says the result was cut at the limit; a traversal-budget notice "
|
|
|
|
|
"needs a narrower path or pattern instead.",
|
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
|
|
|
}
|
|
|
|
|
return {**base, "properties": props}
|
|
|
|
|
|
|
|
|
|
async def execute(self, pattern: str = "", limit: int | None = None, **kwargs: Any): # type: ignore[override]
|
|
|
|
|
if not pattern:
|
|
|
|
|
return "Error: missing required parameter 'pattern'."
|
|
|
|
|
try:
|
|
|
|
|
alternatives = expand_braces(pattern)
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
return f"Error: {exc}"
|
|
|
|
|
if len(alternatives) == 1:
|
|
|
|
|
return await super().execute(pattern=alternatives[0], limit=limit, **kwargs)
|
|
|
|
|
try:
|
|
|
|
|
base = self._resolve(kwargs.get("path", "."))
|
|
|
|
|
except PermissionError as exc:
|
|
|
|
|
return f"Error: {exc}"
|
|
|
|
|
ceiling = limit if limit is not None else self._DEFAULT_LIMIT
|
|
|
|
|
paths: list[str] = []
|
|
|
|
|
seen: set[str] = set()
|
|
|
|
|
cut = False
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
incomplete = False
|
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
|
|
|
for one in alternatives:
|
|
|
|
|
result = await super().execute(pattern=one, limit=limit, **kwargs)
|
|
|
|
|
text = result.model_text if hasattr(result, "model_text") else str(result)
|
|
|
|
|
if text.startswith(("Error: ", "Error running find: ")):
|
|
|
|
|
return result
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
if text == _NO_FILES:
|
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
|
|
|
continue
|
|
|
|
|
lines = text.splitlines()
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
# FindTool puts its notice after a blank line. A filename that
|
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
|
|
|
# merely starts with a notice's words is still a path.
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
if (
|
|
|
|
|
len(lines) >= 2
|
|
|
|
|
and not lines[-2]
|
|
|
|
|
and (_CHILD_CUT_RE.fullmatch(lines[-1]) or _CHILD_INCOMPLETE_RE.fullmatch(lines[-1]))
|
|
|
|
|
):
|
|
|
|
|
cut = cut or bool(_CHILD_CUT_RE.fullmatch(lines[-1]))
|
|
|
|
|
incomplete = incomplete or bool(_CHILD_INCOMPLETE_RE.fullmatch(lines[-1]))
|
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
|
|
|
lines = lines[:-2]
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
# A walk that hit its budget before any match still carries
|
|
|
|
|
# the engine's no-files line above the notice.
|
|
|
|
|
if lines == [_NO_FILES]:
|
|
|
|
|
lines = []
|
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
|
|
|
for line in lines:
|
|
|
|
|
if line and line not in seen:
|
|
|
|
|
seen.add(line)
|
|
|
|
|
paths.append(line)
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
budget_clause = (
|
|
|
|
|
"PARTIAL result: a pattern hit the search's traversal budget before finishing, "
|
|
|
|
|
"so absence of a match is not conclusive -- narrow the path or pattern"
|
|
|
|
|
)
|
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
|
|
|
if not paths:
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
missing = f"No files found matching pattern: {pattern}"
|
|
|
|
|
return f"{missing}\n\n({budget_clause})" if incomplete else missing
|
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
|
|
|
paths.sort(key=lambda path: self._mtime(base / path), reverse=True)
|
|
|
|
|
cut = cut or len(paths) > ceiling
|
|
|
|
|
shown = paths[:ceiling]
|
|
|
|
|
listing = "\n".join(shown)
|
fix(agent): bound every tree walk and take it off the event loop (#566)
## Summary
On 2026-09-20 one `find` call froze the whole gateway for 2h21m. The
model asked for `find(pattern="**/gps_trilateration/index.html",
path="/Users/admin")`, and `FindTool` ran `Path.glob` synchronously on
the event loop, filtered the noise directories only after walking them,
and had no deadline. The registry's 300s ceiling is an
`asyncio.wait_for`, which cannot preempt synchronous code, so every
session and every subagent on the gateway stopped until the walk came
back (`gateway.log`: `Tool result: find duration=8476519ms`). `list_dir`
with `recursive=true` had the same shape through `rglob`.
The fix gives the three tree-walking tools one walk,
`raven.agent.tools.tree_walk`, with these bounds:
- noise directories (`node_modules`, `.git`, ...) are pruned before they
are entered, not filtered afterwards -- the pruning tests spy on
`os.scandir` and assert the noise directory is never opened;
- the walk yields one entry at a time and checks a 20s wall-clock budget
(the value grep's fallback already used) before every entry, so whatever
the caller does with one entry -- the `stat` per `find` match, the read
per grep file -- is covered by the check on the next. The budget cannot
be overrun by one large or slow directory: the probe with eight matches,
a 30ms stat each and a 50ms budget returns 2 matches and the notice.
When the budget is hit, `find` and `list_dir` append a `PARTIAL result:
... traversal budget ...` clause to their trailer, and a deadline that
fires before any match is not reported as a clean `No files found` /
`Directory is empty`;
- every caller runs the walk in `asyncio.to_thread`, so the loop keeps
serving other sessions while the walk runs. Cancelling the thread does
not stop the worker, which is why the deadline lives inside the walk.
The pure-Python `grep` fallback already had the prune and the deadline;
it moves onto the shared walk and off the loop with the others.
`find` matches each path component with `fnmatch.translate`, with a
component that is exactly `**` spanning any number of components; the
matcher is a position-set simulation (`_advance`), linear in components
times segments, so a pattern carrying many `**` cannot make one match
call slow. A pattern's leading literal components decide where the walk
starts: `src/**/*.py` begins inside `src` and never lists a sibling of
it, a pattern that is all literal (`src/lib/c.py`, `src/lib`) names
exactly one path and answers without a walk, and the prefix itself is a
match when the rest of the pattern can match nothing (`src/**` still
lists `src/`). It answers exactly what `Path.glob` answered for the same
pattern: pinned by a parametrized oracle test over twenty-seven patterns
on a fixture and nineteen on a fixture with links (a directory link out
of the tree, a link cycle, a file link, a noise directory beneath a
link), and checked by hand against `Path.glob` over `raven/` for 27
patterns including bracket edge cases and trailing slashes, 0
mismatches. Two deliberate differences: a trailing `**` also lists files
beneath its prefix (3.12's `Path.glob` listed only directories there),
and a pattern with `..` or a leading `/` is refused instead of followed,
since a pattern must not reach outside the directory the fence resolved.
A trailing slash keeps `Path.glob`'s directory-only meaning (`*/`,
`src/**/`). A symbolic link to a directory is entered where a single
component names or matches it and never under `**`, which is how
`Path.glob` read a pattern: `*/util/helper.py` reaches through a linked
`vendor`, `**/helper.py` does not, and a link cycle is entered once per
component the pattern spends on it, so `*/*/*/b.py` enters `src/loop ->
src` twice and stops. The walker asks its caller per link (`follow`),
`find` answers from the pattern and hands the link positions of a path
to the matcher so `**` cannot claim them, and `list_dir` and the grep
fallback never ask, staying as `rglob` and `os.walk` left them. A third
deliberate difference from the merge base: a noise directory inside a
pattern's literal prefix (`node_modules/*.js`, `src/node_modules/*.js`)
is walked, since the pattern asked for it, where `Path.glob`'s filter
dropped it; one met below the prefix is pruned as before
(`*/node_modules/*.js` answers nothing), `list_dir` on such a path lists
it, and the `find`, `list_dir` and code-flow `glob` descriptions state
that rule instead of an unconditional "skipped". Review found an earlier
wording of the two `find` descriptions one component short ("except one
the pattern starts with"), while the oracle helper already pruned below
the prefix; the sentences now say what the helper checks, and the oracle
has the `src/node_modules` shape on both sides.
The raven-code `glob` tool (`agents/raven-code/.../tools/search.py`)
parses trunk `find` output line by line and strips the trailer before
merging brace alternatives. It learns the new clause, so a cut-short
child is reported as cut short rather than as a tree that lacks the
files; its `is_notice` grammar covers the new line so it is never pasted
into a listing as a path. The code-flow tool guide
(`prompts/TOOLS_CODE.md`), the wrapper's description and its `limit`
parameter told the model that a PARTIAL `glob` result means "raise
`limit` or narrow the pattern"; a traversal-budget PARTIAL is now a
result `glob` can return and a higher limit does nothing for it, so all
three now tell the two notices apart. The seeded copy of the guide
refreshes through the receipt `seed_guide` keeps beside it, so no legacy
digest is added.
Fixed in passing, and now pinned: recursive `list_dir` filtered `rglob`
results on the components of the absolute path, so a workspace beneath a
directory named `build`, `dist`, `venv` or another noise name listed as
"Directory ... is empty" (reproduced at the merge base under
`<tmp>/build/proj`; this head lists it). The shared walk prunes below
the listed path only; `find` and the grep fallback already did.
Not changed: the 20s value. It is the budget grep's fallback already ran
under; this PR does not re-measure it, it makes it hold for every entry
of every walk.
## Type
- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
At head 8dade176, on origin/main at d50a13c1 (nine commits: the walk,
the grep pin, the changelog, the per-entry budget with the prefix start,
the literal-directory case, the symbolic-link reading with the
noise-prefix wording, the noise-name-above-the-path pin, the guide
wording, and the prefix-rule wording; `git range-diff` against bb836988:
all nine replayed `=` onto the moved main, which conflicted only at the
changelog anchor and touches no file this PR touches):
```
uv run pytest tests/test_file_search_traversal_guard.py tests/test_agents_code_tools_plugin.py \
tests/test_search_tools.py tests/test_tools_workdir.py tests/test_tool_registry_execute.py tests/test_filesystem_tools.py -q
# 203 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q --ignore=tests/integration # in a throwaway worktree
# 24652 passed, 110 skipped in 382.30s (0:06:22) at head 8dade176, in a throwaway worktree with COLORTERM=truecolor
uv run pytest tests/test_agents_code_launcher.py tests/test_agents_code_tools_plugin.py -q # the guide's seeding and wording tests, the glob wrapper
# 119 passed
make lint-python lint-imports lint-types lint-deps # all pass
git diff --check origin/main...HEAD # clean
scripts/check_source_language.py origin/main...HEAD # exit 0
scripts/check_large_files.py origin/main...HEAD # exit 0
git merge-tree --write-tree HEAD origin/main # clean
```
Revert-to-red, with the tests kept (101 tests in
`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`):
```
the three production files reverted to the previously reviewed head (fd5663ee) 19 failed
file_search.py + filesystem.py reverted to origin/main, tree_walk.py removed collection error
```
Mutation, each mutant applied alone, control restored between runs:
```
deadline checked once per directory (the reviewed placement) 10 failed
walk starts at the root instead of the pattern's prefix 2 failed
trailing slash matches files too 4 failed
a pattern naming one file still walks 1 failed
the prefix itself is never a match 7 failed
a pattern naming one directory walks beneath it 1 failed
control (nothing mutated) 101 passed
```
From the first review round (still holding at this head): find without
`to_thread` 1 failed; list_dir without `to_thread` 1 failed; grep
fallback without `to_thread` 1 failed; pruning removed 6 failed; fork
drops the PARTIAL clause 1 failed.
Fourth round, the symbolic-link reading
(`test_file_search_traversal_guard.py` +
`test_agents_code_tools_plugin.py`, 128 tests, `-n 0`; a mutant that
lets `**` sweep a link, or forgets the link positions, re-enters the
cycle until the OS refuses the path and answers paths `Path.glob` never
did):
```
baseline 128 passed
MUTANT ** may sweep a link 8 failed (7 oracle cases, and the link the pattern ends at is opened)
MUTANT find never asks to enter a link 6 failed (the six oracle patterns that pass through a link)
MUTANT a link is entered even when the pattern ends at it 1 failed (scandir spy on **/vendor)
MUTANT ancestor links forgotten (links_of empty) 1 failed (a cycle case answers a path Path.glob never did)
MUTANT the walker consults follow but never enters 7 failed
MUTANT each followed root gets a fresh deadline 9 failed (every deadline test, and the walker's one-budget test)
REVERT production files to reviewed head d67184c8 7 failed
CONTROL restored 128 passed
```
Revert-to-red for the noise-name pin: with
`raven/agent/tools/filesystem.py` at the merge base and the test kept,
`test_a_noise_name_above_the_searched_path_hides_nothing` fails on the
`Directory ... is empty` answer (1 failed); at this head it passes. The
`agents/**` change is two prose strings and a guide line, outside the
coverage gate's `raven/**` and `plugins-dist/**` pathspecs; the guide's
name-list test and its seeding tests (`test_agents_code_launcher.py`)
cover the file.
The prefix rule is pinned by mutation, the other policy (prune a noise
directory inside the prefix) against the two guard files (131 tests, `-n
0`):
```
baseline 131 passed
MUTANT a noise directory inside the prefix is pruned 5 failed
test_find_matches_what_path_glob_matched[node_modules/**/*.py], test_find_matches_what_path_glob_matched[node_modules/*/], test_find_matches_what_path_glob_matched[node_modules/*/d.py], test_find_matches_what_path_glob_matched[node_modules/x/d.py], test_find_matches_what_path_glob_matched[src/node_modules/*.py]
CONTROL restored 131 passed
```
The symlink oracle is the reviewer's own test shape over a fixture with
links: `vendor -> outside/real`, `src/loop -> src`, `alias.py -> a.py`,
a `node_modules` beneath the link; 19 patterns, 0 mismatches against
`Path.glob` on 3.12, plus a scandir spy pinning that `**/vendor` never
opens the link, a walker test pinning that the default walk yields a
link and does not enter it while a `follow`ed link is walked after the
tree under one deadline, and a `list_dir` and grep test pinning
`rglob`/`os.walk` parity through a link.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG
`Unreleased / Fixed` entry)
## Risk
User-visible behaviour changes, all in tool output the model reads:
- `find` and `list_dir` (recursive) can now return a partial listing
with a `PARTIAL result` clause in the trailer where they previously
either returned everything or hung. The clause tells the model the
absence of a match is not conclusive and to narrow the search.
- A path-prefixed `find` pattern spends its budget only inside its
prefix, so on a large tree it finds what a root-anchored walk used to
miss.
- `find` refuses patterns containing `..` or starting with `/` with an
`Error running find:` line; `Path.glob` used to raise on the second and
could climb on the first.
- `find` with a trailing `**` lists files as well as directories beneath
the prefix; a trailing `/` lists directories only, as before.
- `find` reaches through a symbolic link to a directory where a literal
or single-wildcard component names or matches it, as it did at the merge
base; the earlier revisions of this PR had lost that and returned a
clean miss with no notice. `**` never enters a link, as before.
- A noise directory inside a `find` pattern's literal prefix, or named
as the `list_dir` path, is walked: `find('node_modules/*.js')` and
`find('src/node_modules/*.js')` answer its files and
`list_dir('node_modules', recursive=true)` lists it, where the merge
base answered nothing and "empty". One met below the prefix is pruned as
before. Both descriptions state the rule.
- Recursive `list_dir` on a workspace beneath a directory named like a
noise directory (`/tmp/build/proj`) lists it instead of answering "is
empty".
- The code-flow `glob` description, its `limit` parameter and the tool
guide tell a limit cut from a traversal-budget PARTIAL; the notices
themselves are unchanged.
- `list_dir` flat listings are unchanged; the empty-directory message is
unchanged.
Rollback: revert the squash commit. The new module has no other
consumers, and no state or schema is involved.
- [x] Security impact considered (a pattern can no longer climb out of
the fenced directory via `..`; a directory link is entered exactly where
`Path.glob` entered it at the merge base, one non-`**` component, and
never under `**`, so the fence's reach is what it was and not wider;
`list_dir` and grep never enter one)
- [x] Backward compatibility considered (the fork's trailer grammar is
extended, not changed; existing fork tests pass unchanged)
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 10:59:01 +08:00
|
|
|
if incomplete:
|
|
|
|
|
listing += (
|
|
|
|
|
f"\n(showing first {len(shown)} results across {len(alternatives)} patterns; "
|
|
|
|
|
f"{budget_clause}{', or raise limit' if cut else ''})"
|
|
|
|
|
)
|
|
|
|
|
elif cut:
|
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
|
|
|
listing += (
|
|
|
|
|
f"\n(showing first {len(shown)} results across {len(alternatives)} patterns; "
|
|
|
|
|
"PARTIAL result, raise limit or narrow the pattern)"
|
|
|
|
|
)
|
|
|
|
|
return listing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
__all__ = ["BRACE_CAP", "GlobTool", "expand_braces", "is_notice"]
|