## 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).
318 lines
12 KiB
Python
318 lines
12 KiB
Python
"""Raven-Code file observations belong to the acting runtime and session."""
|
|
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from raven.agent.loop import AgentLoop
|
|
from raven.agent.loop.bundles import HostWiring, ToolWiring, TurnPolicy
|
|
from raven.contracts.llm_provider import LLMResponse, ToolCallRequest
|
|
from raven.contracts.loop_hooks import AgentHookContext
|
|
from raven.contracts.tool import ToolResult
|
|
from raven.plugins.context import PluginContext, ServiceLocator
|
|
from raven.spine import ChatType, Origin, Source, TurnRequest
|
|
|
|
PLUGIN_DIR = Path(__file__).resolve().parent.parent / "agents/raven-code/plugins/code-flow"
|
|
sys.path.insert(0, str(PLUGIN_DIR))
|
|
|
|
from code_flow.flow import make_flow_hook, make_session_observer # noqa: E402
|
|
from code_flow.tools import plugin as factories # noqa: E402
|
|
|
|
|
|
def _ctx(home, flow_enabled=True):
|
|
return PluginContext(
|
|
config={"enabled": flow_enabled, "tools": {"enabled": True}, "projectFiles": []},
|
|
services=ServiceLocator(workspace=home, user_id="u", agent_id="a"),
|
|
)
|
|
|
|
|
|
def _text(result):
|
|
return result.model_text if isinstance(result, ToolResult) else str(result)
|
|
|
|
|
|
async def _bind(hook, key):
|
|
await hook.before_iteration(AgentHookContext(session_key=key, messages=[]))
|
|
|
|
|
|
async def _edit(ctx, target, old="original", new="changed"):
|
|
return _text(await factories.make_edit_file(ctx).execute(file_path=str(target), old_string=old, new_string=new))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("previous", ["unread", "stale", "read", "written", "new"])
|
|
async def test_append_only_preserves_knowledge_of_previously_seen_content(tmp_path, previous):
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
await _bind(hook, "cli:a")
|
|
target = tmp_path / "target.txt"
|
|
if previous != "new":
|
|
target.write_text("original\n")
|
|
if previous in {"read", "stale"}:
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
if previous == "stale":
|
|
target.write_text("original with external changes\n")
|
|
if previous == "written":
|
|
await factories.make_write_file(ctx).execute(file_path=str(target), content="original\n")
|
|
appended = await factories.make_write_file(ctx).execute(file_path=str(target), content="tail\n", mode="append")
|
|
assert "Successfully" in _text(appended)
|
|
result = await _edit(ctx, target, old="tail" if previous == "new" else "original")
|
|
if previous in {"unread", "stale"}:
|
|
assert result.startswith("Error:"), result
|
|
assert "original" in target.read_text()
|
|
else:
|
|
assert "Successfully edited" in result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("same_home", [False, True])
|
|
async def test_runtime_instances_do_not_share_observations_even_for_the_same_session(tmp_path, same_home):
|
|
first = _ctx(tmp_path / "first")
|
|
second = _ctx(tmp_path / ("first" if same_home else "second"))
|
|
hook_a, hook_b = make_flow_hook(first), make_flow_hook(second)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
await _bind(hook_a, "cli:same")
|
|
await factories.make_read_file(first).execute(file_path=str(target))
|
|
await _bind(hook_b, "cli:same")
|
|
result = await _edit(second, target)
|
|
assert result.startswith("Error:"), result
|
|
await _bind(hook_a, "cli:same")
|
|
assert "Successfully edited" in await _edit(first, target)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_parallel_sessions_do_not_borrow_each_others_read_binding(tmp_path):
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
read_done, other_done = asyncio.Event(), asyncio.Event()
|
|
|
|
async def reader():
|
|
await _bind(hook, "cli:a")
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
read_done.set()
|
|
await other_done.wait()
|
|
assert "Successfully edited" in await _edit(ctx, target)
|
|
|
|
async def stranger():
|
|
await read_done.wait()
|
|
await _bind(hook, "cli:b")
|
|
try:
|
|
result = await _edit(ctx, target)
|
|
assert result.startswith("Error:"), result
|
|
finally:
|
|
other_done.set()
|
|
|
|
await asyncio.gather(reader(), stranger())
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_deletion_clears_only_the_deleted_conversations_observations(tmp_path):
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
targets = {key: tmp_path / f"{key}.txt" for key in ("a", "b")}
|
|
for key, target in targets.items():
|
|
target.write_text("original\n")
|
|
await _bind(hook, f"cli:{key}")
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
# Observers and hooks are constructed with separate locators by the host.
|
|
make_session_observer(_ctx(tmp_path)).on_session_deleted("cli:a", True)
|
|
await _bind(hook, "cli:a")
|
|
assert (await _edit(ctx, targets["a"])).startswith("Error:")
|
|
await _bind(hook, "cli:b")
|
|
assert "Successfully edited" in await _edit(ctx, targets["b"])
|
|
|
|
|
|
class _Provider:
|
|
def __init__(self):
|
|
self.responses = []
|
|
self.results = []
|
|
|
|
async def chat_with_retry(self, **kwargs):
|
|
self.results.extend(m for m in kwargs["messages"] if m.get("role") == "tool")
|
|
return self.responses.pop(0)
|
|
|
|
def get_default_model(self):
|
|
return "fake/model"
|
|
|
|
|
|
def _loop(home, provider, flow_enabled=True):
|
|
# Separate locators match real plugin-stack construction.
|
|
hook = make_flow_hook(_ctx(home, flow_enabled))
|
|
tools = [
|
|
make(_ctx(home, flow_enabled))
|
|
for make in (
|
|
factories.make_read_file,
|
|
factories.make_write_file,
|
|
factories.make_edit_file,
|
|
)
|
|
]
|
|
loop = AgentLoop(
|
|
provider=provider,
|
|
workspace=home,
|
|
model="fake/model",
|
|
policy=TurnPolicy(max_iterations=4),
|
|
host=HostWiring(hooks=[hook]),
|
|
tools=ToolWiring(plugin_tools=tools),
|
|
)
|
|
|
|
async def noop(**kwargs):
|
|
return None
|
|
|
|
loop._start_executor = noop
|
|
loop._connect_mcp = noop
|
|
return loop
|
|
|
|
|
|
def _req(text):
|
|
return TurnRequest(
|
|
origin=Origin.USER,
|
|
source=Source(channel="cli", chat_id="a", sender_id="u", chat_type=ChatType.DM),
|
|
text=text,
|
|
)
|
|
|
|
|
|
async def _turn(loop, provider, key, name, args, origin=Origin.USER):
|
|
provider.responses = [
|
|
LLMResponse(content="", tool_calls=[ToolCallRequest(id="call", name=name, arguments=args)]),
|
|
LLMResponse(content="done", finish_reason="stop"),
|
|
]
|
|
provider.results = []
|
|
await loop._process_message(_req("continue"), session_key=key, origin=origin)
|
|
return provider.results[-1]["content"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("flow_enabled", [False, True])
|
|
@pytest.mark.parametrize("origin", [Origin.USER, Origin.SUBAGENT])
|
|
async def test_real_loop_binds_the_actual_session_for_file_tools(tmp_path, flow_enabled, origin):
|
|
provider = _Provider()
|
|
loop = _loop(tmp_path, provider, flow_enabled)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
assert "original" in await _turn(loop, provider, "cli:a", "read_file", {"file_path": str(target)}, origin)
|
|
args = {"file_path": str(target), "old_string": "original", "new_string": "changed"}
|
|
result = await _turn(loop, provider, "cli:b", "edit_file", args, origin)
|
|
assert "Error:" in result, result
|
|
assert "Successfully edited" in await _turn(loop, provider, "cli:a", "edit_file", args, origin)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("command", ["/new", " /NEW ", "/help"])
|
|
@pytest.mark.parametrize("flow_enabled", [False, True])
|
|
async def test_host_commands_keep_file_observations_scoped_to_the_unchanged_session_key(
|
|
tmp_path, command, flow_enabled, monkeypatch
|
|
):
|
|
provider = _Provider()
|
|
loop = _loop(tmp_path, provider, flow_enabled)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
await _turn(loop, provider, "cli:a", "read_file", {"file_path": str(target)})
|
|
attempts = []
|
|
|
|
async def consolidate(session):
|
|
attempts.append(session.key)
|
|
return True
|
|
|
|
monkeypatch.setattr(loop.memory_consolidator, "consolidate_unconsolidated", consolidate)
|
|
reply = await loop._process_message(_req(command), session_key="cli:a")
|
|
if command.strip().lower() == "/new":
|
|
assert attempts == ["cli:a"]
|
|
assert reply[0] == "New session started."
|
|
else:
|
|
assert not attempts
|
|
result = await _turn(
|
|
loop,
|
|
provider,
|
|
"cli:a",
|
|
"edit_file",
|
|
{"file_path": str(target), "old_string": "original", "new_string": "changed"},
|
|
)
|
|
assert "Successfully edited" in result, result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("previous", ["unread", "read"])
|
|
async def test_failed_append_does_not_create_or_discard_a_read_record(tmp_path, previous):
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
await _bind(hook, "cli:a")
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
if previous == "read":
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
result = await factories.make_write_file(ctx).execute(file_path=str(target), content="", mode="append")
|
|
assert _text(result).startswith("Error:")
|
|
edited = await _edit(ctx, target)
|
|
assert ("Successfully edited" in edited) == (previous == "read")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_ambiguous_edit_does_not_count_as_observing_the_file(tmp_path):
|
|
from code_flow.tools.filesystem import EditFileTool
|
|
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
await _bind(hook, "cli:a")
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original original\n")
|
|
unchecked = EditFileTool(workspace=tmp_path, require_read=False)
|
|
result = await unchecked.execute(file_path=str(target), old_string="original", new_string="changed")
|
|
assert _text(result).startswith("Warning:")
|
|
assert (await _edit(ctx, target, old="original original")).startswith("Error:")
|
|
assert target.read_text() == "original original\n"
|
|
assert "Unread or externally changed files are rejected" not in unchecked.description
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_append_in_one_session_leaves_another_sessions_record_stale(tmp_path):
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
for key in ("cli:a", "cli:b"):
|
|
await _bind(hook, key)
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
await factories.make_write_file(ctx).execute(file_path=str(target), content="tail\n", mode="append")
|
|
await _bind(hook, "cli:a")
|
|
assert "changed since" in await _edit(ctx, target)
|
|
await _bind(hook, "cli:b")
|
|
assert "Successfully edited" in await _edit(ctx, target)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("flow_enabled", [False, True])
|
|
async def test_unbound_and_wrong_owner_calls_cannot_borrow_observations(tmp_path, flow_enabled):
|
|
ctx = _ctx(tmp_path, flow_enabled)
|
|
hook = make_flow_hook(ctx)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
await _bind(hook, "cli:a")
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
assert "no active Raven-Code session" in await _edit(_ctx(tmp_path / "other"), target)
|
|
await hook.after_send(AgentHookContext(session_key="cli:a"))
|
|
assert "no active Raven-Code session" in await _edit(ctx, target)
|
|
await _bind(hook, "cli:a")
|
|
assert "Successfully edited" in await _edit(ctx, target)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_replacing_a_file_with_the_same_mtime_still_requires_another_read(tmp_path):
|
|
import os
|
|
|
|
ctx = _ctx(tmp_path)
|
|
hook = make_flow_hook(ctx)
|
|
target = tmp_path / "target.txt"
|
|
target.write_text("original\n")
|
|
await _bind(hook, "cli:a")
|
|
await factories.make_read_file(ctx).execute(file_path=str(target))
|
|
stat = target.stat()
|
|
replacement = tmp_path / "replacement.txt"
|
|
replacement.write_text("external\n")
|
|
os.utime(replacement, ns=(stat.st_atime_ns, stat.st_mtime_ns))
|
|
replacement.replace(target)
|
|
assert "changed since" in await _edit(ctx, target, old="external")
|