## Summary A conversation reached disk only when its turn finished, and the session store knows a session only by its file. So a conversation whose first turn was still running was in no listing: the rail kept it as an unsaved row only while it stayed the open one, a refresh of the list (an approval or a question arriving does that) dropped it once the reader had switched away, and a reload lost it outright while the turn kept running with nobody watching. Six commits (plus a merge of `main`, whose #617 moved the generated RPC clients): 1. `fix(agent)`: the question is written as soon as the prompt is assembled and before the first model call, through the same `_save_turn` that wrote it at turn end, so it is filed exactly once with its arrival timestamp. The three closing writes (healthy, cancelled, failed) start after it. `prev_len` is read before the opening write so the memory-backend slice and the output-limit marker still count from this turn's start, and the history handed to hooks is sliced there so it still ends with the previous turn, as documented. The session namer now runs before the `message.start` emit, otherwise the filed question made it decline to name a new session. 2. `feat(rpc)`: `running` on `SessionListItem` and `SessionInitInfo`, read from the active-turn table, so a page that has just loaded can tell. Both generated clients regenerated. 3. `feat(ui-web)`: the rail badges a running row from the list answer and lets that answer clear a stale badge; opening a conversation whose resume bundle says it is running puts the composer back into the streaming, cancellable state, so the stop button works, a send queues instead of being refused, and the deltas still to come land in a fresh step. What already streamed before the reload is not recoverable and is not pretended at. 4. `fix(*)`: the reload race the review found. `turn.subscribe` now answers `running`, read on the far side of the emitter's replay publish, so a completion that would make it stale is one the new subscription itself receives; the page keeps the resume hint (it pre-arms the machine so the replayed `message.start` does not draw the question twice) and, once subscribed, re-opens the conversation from disk when the hint said running but the subscription says otherwise while the machine is still busy. The offline fixtures answer the new `running` fields, which the fixture-shape gate had been failing on. 5. `fix(ui-web)`: found in the owner's acceptance pass -- after a reload the live row's clock restarted from zero. The resume path now anchors the live clock and the runtime's start stamp to the last user message's timestamp (the question is on disk from turn start, so it carries the turn's arrival), through the transcript's own stamp parser exposed via its seam. 6. `fix(*)`: from the reviewer's timezone finding and an adversarial pass over the served page. The resumed clock had been anchored to the question's stored stamp parsed in the browser; the loop writes that stamp off the gateway's wall clock with no offset, so a browser in another timezone read the offset back as the turn's age. `session.resume` now answers `running_ms`, measured on the server against its own clock (naive against `datetime.now()`, aware against `datetime.now(tz)`), and the page anchors at `Date.now()` minus that. The re-open of the fourth commit had landed on the kept-turn branch: `park()` keeps a busy machine and leaves `rt.events` set, so the second pass restored the streaming phase instead of reading the conversation off disk, and the stop button stood over a finished answer for the life of the tab -- reachable on every Stop that overlaps a reload, because `turn.cancel` emits its error frame before the active slot clears. The re-open now disarms the machine and the anchor first and tells the second pass the turn is over. A `run` badge that came from `session.list` never came off: the on-screen turn end now clears the current row's badge, and while any listed row says somebody else is answering, the page asks for the list again every five seconds, stopping when none is left. `running` was false for every turn `turn.send` did not start, so a cron or channel conversation answering for a minute listed as idle; `session.list` and `session.resume` now ask the scheduler as well (`is_session_answering`). Known limits after this PR, to follow up separately: a cron or channel turn is listed and badged while it runs, but opening it shows no stop button or live clock, because the spine emits no opening frame for a scheduler-origin turn, so `turn.subscribe` cannot say it is running (making it read the scheduler would re-open the Stop-overlaps-reload window). A message queued while a turn runs is still page-local and lost by a reload (rarely reached once #622 injects instead of queueing). A reload within about two seconds of a send boots a rail without the conversation until the next list. A gateway that dies mid-turn leaves the filed question with no answer and nothing on screen saying so: the wire has no `interrupted` flag on a transcript row and the page no renderer for one. Behaviour visible elsewhere: every consumer of the session list (TUI picker, `raven sessions list`, `session.most_recent`, the heartbeat's delivery target) now sees a conversation from the moment its turn starts rather than when it ends, and a row moves to the top of the list on send rather than on answer. Every turn costs one more locked append. ## Type - [x] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification - `uv run pytest tests/test_agent_loop_turn_open_persist.py tests/test_agent_loop_broken_turn.py tests/test_agent_loop_iteration_hooks.py tests/test_session_manager.py tests/test_rpc_session.py tests/test_rpc_session_init_bundle.py tests/test_rpc_turn_session_naming_wiring.py tests/test_rpc_turn_send.py tests/test_rpc_session_naming.py tests/test_rpc_schema_match.py -q` -- 299 passed, and the same again with an empty `HOME`. New cases: the session is on disk and listed from inside the first provider call; the question is filed once and the answer follows it; a cancelled and a failed turn each leave the question once with what had streamed and the end marker; the slice handed to the memory backend still opens on the question; a hook's `session_history` stops before this turn's question; a session holding only its open question lists as a complete row with an auto title; naming still starts when the question is already filed; `session.list`, `session.resume` and `session.create` report `running`. The on-disk and naming cases fail against the previous `turn_path.py` / `turn.py`; the once-only and history cases fail under the single mutation each guards. - `uv run pytest tests/ -q` -- 24334 passed, 119 skipped. - `npm test --prefix ui-web -- src/features/rail src/state/session` -- 234 passed (new: a listed `running` row carries the badge; the server's answer clears a stale run badge while the reader's own marks stay; a resumed running conversation puts the turn machine into streaming/cancellable and repaints; a resumed idle one stays idle). - `uv run pytest tests/test_rpc_turn_subscribe.py tests/test_rpc_schema_match.py tests/test_rpc_registration.py -q` -- 413 passed (new: `turn.subscribe` says running while a turn is buffered, not running on a quiet session, not running once the turn completed; red against the previous `turn.py`). `npm test --prefix ui-web -- src/state/session/registry.test.ts` -- 24 passed (new: resume running + subscribe running stays streaming; resume running + subscribe not running re-opens and ends idle, red against the previous `registry.ts`; resume not running + subscribe running is left to the replayed `message.start`). - `uv run pytest tests/test_rpc_session.py tests/test_rpc_turn_send.py tests/test_rpc_turn_cancel.py tests/test_rpc_turn_subscribe.py tests/test_rpc_schema_match.py -q` -- passes (new: resume of a busy session carries `running_ms` measured against a monkeypatched clock, the same for a naive and an offset-bearing stamp; idle answers no elapsed and an unparsable stamp null; `session.list` and `session.resume` say running for a lane the scheduler holds that `turn.send` never saw, and not for a different lane). Red against the previous `session.py`. - `npm test --prefix ui-web -- src/state/session` -- passes (new: the re-open reads the conversation back off disk with the REAL residency module in the harness -- second `session.resume` issued, transcript re-read, machine idle; the badge poll asks again after 5 s, clears when the answer says not running and stops; the visible turn end takes a listed `run` badge off the row; a resumed turn anchors to `Date.now() - running_ms`, and a bundle without it leaves the clock alone). Each red against the previous `registry.ts` / `pipeline.ts`. - `npm test --prefix ui-web` -- whole suite green, the contract gates included; `npm run type-check --prefix ui-web`, `npm run lint --prefix ui-web`, `npm run gen:check --prefix ui-web`, `npm run lint:rpc --prefix ui-tui`, `uv run ruff check raven tests` -- clean. - `npm run type-check --prefix ui-web`, `npm run lint --prefix ui-web`, `npm run gen:check --prefix ui-web`, `npm run lint:rpc --prefix ui-tui`, `uv run ruff check raven tests` -- clean. - Served page, second pass: a Stop fired from another connection while the page reloads, detected by the page's own second `session.resume` -- 2 of 14 attempts landed in the band and both ended idle with the question, the partial answer and the stop note (before: stuck with the stop button up); a background conversation's badge clears within the same sample the server turns idle (before: still on after 140 s); the badge on the conversation being watched clears at the turn's end; browsers in America/New_York and Asia/Tokyo read 11 s and 16 s of elapsed at 12 s and 17 s of wall time (before: 0 s and 60m17s); a cron turn lists and badges as running while it runs and clears at its end. - Served page, isolated agent home, a turn that sleeps in a shell tool: before the fix nothing is on disk or listed until the turn ends, and a reload lands on the new-task screen with no row; after the fix the file exists within a second of the send (metadata plus the question), `session.list` carries the key with one message and `running: true`, a reload lists the conversation with its badge, opening it shows the question and the stop button, the answer lands when the turn ends, and the JSONL holds the question exactly once; a cancelled turn also leaves the question once, followed by its end marker. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes The turn path gains one write per turn on every surface, channels and cron included; a gateway that dies mid-turn now leaves a one-message conversation instead of nothing. The `running` field has a default, so older clients ignore it. `running_ms` is optional and defaults to null, so older clients ignore it. The listed-badge poll costs one `session.list` every five seconds only while a row shows another client answering. Rollback: revert the commits in reverse order. ## Related Issues N/A --------- Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
556 lines
22 KiB
Python
556 lines
22 KiB
Python
"""The iteration phases fire inside the loop and their grants take effect.
|
|
|
|
A product that steers the loop -- budget notes, forced finalization, spin
|
|
breaking -- lives entirely on these seams, so what is pinned here is the
|
|
loop's side of the contract: where each phase fires, what a rollback does
|
|
to history and to the iteration budget, that injected messages reach the
|
|
re-sample and persist, that generation overrides reach the provider only
|
|
when allowlisted, that a withheld tool is withheld for one iteration only,
|
|
and that the terminal seam sees an answerless exit.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
|
|
from raven.agent.hook import AgentHook, HookDecision
|
|
from raven.agent.loop import AgentLoop
|
|
from raven.agent.loop.bundles import HostWiring, ToolWiring, TurnPolicy
|
|
from raven.agent.loop.turn_path import _stamp_turn_observers
|
|
from raven.contracts.llm_provider import LLMResponse, ToolCallRequest
|
|
from raven.spine import ChatType, Origin, Source, TurnRequest
|
|
|
|
|
|
class _ScriptedProvider:
|
|
"""chat_with_retry answers from a script and records every call's kwargs."""
|
|
|
|
def __init__(self, responses: list[LLMResponse]) -> None:
|
|
self._responses = list(responses)
|
|
self.calls: list[dict] = []
|
|
|
|
async def chat_with_retry(self, **kwargs) -> LLMResponse:
|
|
# Snapshot: the loop mutates-and-returns the same message list, so a
|
|
# stored reference would show the turn's end state, not this call's.
|
|
snapshot = dict(kwargs)
|
|
snapshot["messages"] = [dict(m) for m in kwargs.get("messages") or []]
|
|
snapshot["tools"] = list(kwargs.get("tools") or [])
|
|
self.calls.append(snapshot)
|
|
index = min(len(self.calls) - 1, len(self._responses) - 1)
|
|
return self._responses[index]
|
|
|
|
def get_default_model(self) -> str:
|
|
return "fake/model"
|
|
|
|
|
|
def _text(content: str, **extra) -> LLMResponse:
|
|
return LLMResponse(content=content, finish_reason="stop", **extra)
|
|
|
|
|
|
def _tool_call(name: str, arguments: dict) -> LLMResponse:
|
|
return LLMResponse(content="", tool_calls=[ToolCallRequest(id="c1", name=name, arguments=arguments)])
|
|
|
|
|
|
def _req(text: str = "hi") -> TurnRequest:
|
|
return TurnRequest(
|
|
origin=Origin.USER,
|
|
source=Source(channel="cli", chat_id="c", sender_id="u", chat_type=ChatType.DM),
|
|
text=text,
|
|
)
|
|
|
|
|
|
def _loop(tmp_path, provider, hooks, max_iterations: int = 6) -> AgentLoop:
|
|
loop = AgentLoop(
|
|
provider=provider,
|
|
workspace=tmp_path,
|
|
model="fake/model",
|
|
policy=TurnPolicy(max_iterations=max_iterations),
|
|
host=HostWiring(hooks=hooks),
|
|
tools=ToolWiring(restrict_to_workspace=True),
|
|
)
|
|
|
|
async def _noop(**_kw) -> None:
|
|
return None
|
|
|
|
loop._start_executor = _noop
|
|
loop._connect_mcp = _noop
|
|
return loop
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_before_iteration_sees_the_turn_and_can_withhold_a_tool_for_one_iteration(tmp_path):
|
|
seen: list[tuple[int, str, int]] = []
|
|
|
|
class WithholdFirst(AgentHook):
|
|
async def before_iteration(self, ctx):
|
|
seen.append((ctx.iteration, ctx.turn_question, ctx.turn_base))
|
|
if ctx.iteration == 1:
|
|
return HookDecision(modified_tools=[t for t in ctx.tools if t["function"]["name"] != "list_dir"])
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."}), _text("done")])
|
|
loop = _loop(tmp_path, provider, [WithholdFirst()])
|
|
|
|
out = await loop._process_message(_req("what is here"))
|
|
|
|
assert out is not None
|
|
assert seen[0][1] == "what is here"
|
|
first_call_tools = {t["function"]["name"] for t in provider.calls[0]["tools"]}
|
|
second_call_tools = {t["function"]["name"] for t in provider.calls[1]["tools"]}
|
|
assert "list_dir" not in first_call_tools, "withheld for the first iteration"
|
|
assert "list_dir" in second_call_tools, "and offered again on the next -- the registry was untouched"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_before_execute_tools_rollback_discards_the_proposal_and_does_not_consume_an_iteration(tmp_path):
|
|
class BounceOnce(AgentHook):
|
|
def __init__(self) -> None:
|
|
self.bounced = False
|
|
|
|
async def before_execute_tools(self, ctx):
|
|
if not self.bounced:
|
|
self.bounced = True
|
|
return HookDecision(
|
|
rollback=True,
|
|
rollback_inject=[{"role": "user", "content": "[gate] do not call tools; answer directly"}],
|
|
rollback_overrides={"temperature": 0.0, "bogus": 1},
|
|
)
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."}), _text("answered directly")])
|
|
loop = _loop(tmp_path, provider, [BounceOnce()], max_iterations=1)
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
# Budget of one iteration, two provider calls: the rollback did not spend it.
|
|
assert out is not None and "answered directly" in str(out)
|
|
assert len(provider.calls) == 2
|
|
resample = provider.calls[1]
|
|
assert resample["temperature"] == 0.0, "allowlisted override reached the re-sample"
|
|
assert "bogus" not in resample, "unknown override was dropped, not forwarded"
|
|
assert resample["messages"][-1]["content"] == "[gate] do not call tools; answer directly"
|
|
assert not any(m.get("tool_calls") for m in resample["messages"]), "the discarded proposal is gone"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_after_iteration_short_circuit_replaces_the_draft_without_persisting_it(tmp_path):
|
|
class Replace(AgentHook):
|
|
async def after_iteration(self, ctx):
|
|
if ctx.response is not None and not ctx.response.has_tool_calls:
|
|
return HookDecision(short_circuit_result="reviewed answer")
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_text("first draft")])
|
|
loop = _loop(tmp_path, provider, [Replace()])
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert "reviewed answer" in str(out)
|
|
session = loop.sessions.get_or_create("cli:c")
|
|
texts = [m.get("content") for m in session.messages if m.get("role") == "assistant"]
|
|
assert "first draft" not in texts
|
|
assert "reviewed answer" in texts
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_honoured_rollback_is_counted_where_the_next_iteration_can_read_it(tmp_path):
|
|
"""The re-sample carries the same iteration number, so a hook scoped to the
|
|
turn boundary cannot tell it from the first sampling by ``ctx.iteration``
|
|
alone. The loop records the honoured count beside the refused one."""
|
|
|
|
class BounceOnce(AgentHook):
|
|
def __init__(self) -> None:
|
|
self.seen: list[tuple[int | None, int]] = []
|
|
|
|
async def before_iteration(self, ctx):
|
|
self.seen.append((ctx.iteration, ctx.metadata.get("hook_rollbacks", 0)))
|
|
return HookDecision()
|
|
|
|
async def after_iteration(self, ctx):
|
|
if ctx.metadata.get("bounced"):
|
|
return HookDecision()
|
|
ctx.metadata["bounced"] = True
|
|
return HookDecision(rollback=True)
|
|
|
|
hook = BounceOnce()
|
|
provider = _ScriptedProvider([_text("draft"), _text("final")])
|
|
loop = _loop(tmp_path, provider, [hook], max_iterations=3)
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert out is not None
|
|
# Iteration 1 twice: the first sampling with no rollback on record, the
|
|
# re-sample with exactly one.
|
|
assert hook.seen == [(1, 0), (1, 1)]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_the_rollback_cap_degrades_to_pass_through_and_is_counted(tmp_path):
|
|
class AlwaysBounce(AgentHook):
|
|
def __init__(self) -> None:
|
|
self.refusals_seen = 0
|
|
|
|
async def after_iteration(self, ctx):
|
|
self.refusals_seen = ctx.metadata.get("rollbacks_refused", 0)
|
|
return HookDecision(rollback=True)
|
|
|
|
hook = AlwaysBounce()
|
|
provider = _ScriptedProvider([_text("draft")])
|
|
loop = _loop(tmp_path, provider, [hook], max_iterations=2)
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert out is not None
|
|
assert len(provider.calls) == AgentLoop._MAX_HOOK_ROLLBACKS + 1, "the cap bounds the re-samples"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_terminal_answerless_can_commit_an_answer_after_a_provider_error(tmp_path):
|
|
class Salvage(AgentHook):
|
|
async def terminal_answerless(self, ctx):
|
|
assert ctx.metadata["turn_end"]["status"] == "error"
|
|
return HookDecision(short_circuit_result="salvaged answer")
|
|
|
|
provider = _ScriptedProvider([LLMResponse(content="upstream failed", finish_reason="error")])
|
|
loop = _loop(tmp_path, provider, [Salvage()])
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert "salvaged answer" in str(out)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_hooks_means_no_phase_work(tmp_path):
|
|
provider = _ScriptedProvider([_text("plain")])
|
|
loop = _loop(tmp_path, provider, None)
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert "plain" in str(out)
|
|
assert len(provider.calls) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_session_policy_caps_iterations_and_reaches_the_hooks(tmp_path):
|
|
seen: list[dict] = []
|
|
|
|
class Observe(AgentHook):
|
|
async def before_iteration(self, ctx):
|
|
seen.append(dict(ctx.metadata))
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."})] * 5 + [_text("done")])
|
|
loop = _loop(tmp_path, provider, [Observe()], max_iterations=6)
|
|
loop.set_session_policy("cli:c", max_iterations=2, mode="deep", mode_overlay={"k": 10})
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert out is not None
|
|
assert len(provider.calls) <= 3, "the session cap of 2 held (plus the exhaustion wrap-up call)"
|
|
assert seen[0]["mode"] == "deep" and seen[0]["mode_overlay"] == {"k": 10}
|
|
assert loop.session_policy("cli:other").mode == "", "another session runs on the defaults"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_session_policy_pins_the_reasoning_effort_of_its_calls(tmp_path):
|
|
"""A mode that asks for more thinking sets the effort of every provider call
|
|
the session's turn makes; a session without one leaves the provider's own."""
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."}), _text("done")])
|
|
loop = _loop(tmp_path, provider, [])
|
|
loop.set_session_policy("cli:c", mode="max", reasoning_effort="max")
|
|
|
|
await loop._process_message(_req())
|
|
|
|
assert len(provider.calls) == 2
|
|
assert all(call.get("reasoning_effort") == "max" for call in provider.calls)
|
|
|
|
other = _ScriptedProvider([_text("plain")])
|
|
quiet = _loop(tmp_path, other, [])
|
|
await quiet._process_message(_req())
|
|
assert "reasoning_effort" not in other.calls[0]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_after_iteration_note_lands_on_the_last_message_before_the_next_call(tmp_path):
|
|
class Nudge(AgentHook):
|
|
async def after_iteration(self, ctx):
|
|
if getattr(ctx.response, "has_tool_calls", False):
|
|
return HookDecision(append_note="[budget warning: most of the budget is spent]")
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."}), _text("done")])
|
|
loop = _loop(tmp_path, provider, [Nudge()])
|
|
|
|
out = await loop._process_message(_req("what is here"))
|
|
|
|
assert out is not None
|
|
last_seen = provider.calls[1]["messages"][-1]
|
|
assert last_seen["role"] == "tool"
|
|
assert str(last_seen["content"]).endswith("\n\n[budget warning: most of the budget is spent]")
|
|
assert "[budget warning" not in str(provider.calls[0]["messages"][-1]["content"]), "landed after, not before"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_before_user_inbound_can_rewrite_the_inbound_text(tmp_path):
|
|
seeded: list[str | None] = []
|
|
|
|
class Memo(AgentHook):
|
|
async def before_user_inbound(self, ctx):
|
|
seeded.append(ctx.inbound_content)
|
|
return HookDecision(modified_content=f"[research memo]\n\n{ctx.inbound_content}")
|
|
|
|
provider = _ScriptedProvider([_text("done")])
|
|
loop = _loop(tmp_path, provider, [Memo()])
|
|
|
|
out = await loop._process_message(_req("what changed since last time?"))
|
|
|
|
assert out is not None
|
|
assert seeded == ["what changed since last time?"]
|
|
dispatched = str(provider.calls[0]["messages"][-1]["content"])
|
|
assert "[research memo]" in dispatched and "what changed since last time?" in dispatched
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_metadata_is_one_dict_across_all_three_phase_groups(tmp_path):
|
|
seen: dict[str, object] = {}
|
|
|
|
class Stash(AgentHook):
|
|
async def before_user_inbound(self, ctx):
|
|
ctx.metadata["stash"] = "from-the-door"
|
|
seen["inbound_history"] = list(ctx.session_history or [])
|
|
return HookDecision()
|
|
|
|
async def before_iteration(self, ctx):
|
|
seen["at_iteration"] = ctx.metadata.get("stash")
|
|
return HookDecision()
|
|
|
|
async def after_send(self, ctx):
|
|
seen["at_send"] = ctx.metadata.get("stash")
|
|
seen["send_history"] = len(ctx.session_history or [])
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_text("done"), _text("again")])
|
|
loop = _loop(tmp_path, provider, [Stash()])
|
|
|
|
out = await loop._process_message(_req("hello"))
|
|
|
|
assert out is not None
|
|
assert seen["at_iteration"] == "from-the-door"
|
|
assert seen["at_send"] == "from-the-door"
|
|
assert seen["inbound_history"] == [], "a fresh session has no record yet"
|
|
assert seen["send_history"] == 0, "the send fires before this turn is filed"
|
|
|
|
out2 = await loop._process_message(_req("and now?"))
|
|
|
|
assert out2 is not None
|
|
assert len(seen["inbound_history"]) >= 2, "the second turn's inbound sees the first turn's record"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_history_keeps_the_users_words_not_the_hooks_rewrite(tmp_path):
|
|
class Memo(AgentHook):
|
|
async def before_user_inbound(self, ctx):
|
|
return HookDecision(modified_content=f"[research memo]\n\n{ctx.inbound_content}\n\n[reminder]")
|
|
|
|
provider = _ScriptedProvider([_text("done")])
|
|
loop = _loop(tmp_path, provider, [Memo()])
|
|
|
|
out = await loop._process_message(_req("what changed?"))
|
|
|
|
assert out is not None
|
|
dispatched = str(provider.calls[0]["messages"][-1]["content"])
|
|
assert "[research memo]" in dispatched, "the model saw the rewrite"
|
|
session = loop.sessions.get_or_create("cli:c")
|
|
users = [m for m in session.messages if m.get("role") == "user"]
|
|
assert users and users[-1]["content"] == "what changed?", "history kept the user's own words"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_hooks_observers_dict_lands_on_the_turns_last_assistant_message(tmp_path):
|
|
class Counter(AgentHook):
|
|
async def after_iteration(self, ctx):
|
|
ctx.metadata.setdefault("observers", {})["gate"] = {"fired": 1}
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."}), _text("done")])
|
|
loop = _loop(tmp_path, provider, [Counter()])
|
|
|
|
out = await loop._process_message(_req("look around"))
|
|
|
|
assert out is not None
|
|
session = loop.sessions.get_or_create("cli:c")
|
|
stamped = [m for m in session.messages if m.get("observers")]
|
|
assert len(stamped) == 1 and stamped[0]["role"] == "assistant"
|
|
assert stamped[0]["observers"] == {"gate": {"fired": 1}}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iteration_phases_read_the_filed_record_which_still_ends_with_the_previous_turn(tmp_path):
|
|
histories: list[list] = []
|
|
|
|
class Reader(AgentHook):
|
|
async def before_iteration(self, ctx):
|
|
if ctx.iteration == 1:
|
|
histories.append(list(ctx.session_history or []))
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_text("first answer"), _text("second answer")])
|
|
loop = _loop(tmp_path, provider, [Reader()])
|
|
|
|
await loop._process_message(_req("first"))
|
|
await loop._process_message(_req("second"))
|
|
|
|
assert histories[0] == [], "a fresh session has no filed record yet"
|
|
assert histories[1], "the second turn's iterations see the first turn's record"
|
|
assert any("first answer" in str(m.get("content")) for m in histories[1])
|
|
assert all("second" != str(m.get("content")) for m in histories[1]), "the running turn is not filed yet"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_the_filed_record_a_phase_reads_stops_before_this_turns_question(tmp_path):
|
|
"""``session_history`` is the record as it stood BEFORE this turn, and the
|
|
question now reaches disk before the first model call -- so the slice the
|
|
phases are handed has to end where the previous turn ended, or a hook that
|
|
counts turns sees the one it is inside of."""
|
|
at_iteration: list[list] = []
|
|
at_send: list[list] = []
|
|
|
|
class Reader(AgentHook):
|
|
async def before_iteration(self, ctx):
|
|
if ctx.iteration == 1:
|
|
at_iteration.append(list(ctx.session_history or []))
|
|
return HookDecision()
|
|
|
|
async def after_send(self, ctx):
|
|
at_send.append(list(ctx.session_history or []))
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_text("first answer"), _text("second answer")])
|
|
loop = _loop(tmp_path, provider, [Reader()])
|
|
|
|
await loop._process_message(_req("first"))
|
|
await loop._process_message(_req("second"))
|
|
|
|
assert at_iteration[0] == [] and at_send[0] == [], "a fresh session has no filed record yet"
|
|
for history in (at_iteration[1], at_send[1]):
|
|
contents = [str(m.get("content")) for m in history]
|
|
assert "first" in contents, "the previous turn's question is part of the record"
|
|
assert "second" not in contents, f"the running turn's question leaked into the history: {contents}"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iteration_phases_carry_the_cap_the_loop_enforces_and_the_bindings_window(tmp_path):
|
|
seen: dict[str, object] = {}
|
|
|
|
class Reader(AgentHook):
|
|
async def before_iteration(self, ctx):
|
|
seen.setdefault("cap", ctx.max_iterations)
|
|
seen.setdefault("window", ctx.context_window_tokens)
|
|
return HookDecision()
|
|
|
|
async def before_user_inbound(self, ctx):
|
|
seen["inbound_cap"] = ctx.max_iterations
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_text("done")])
|
|
loop = _loop(tmp_path, provider, [Reader()], max_iterations=6)
|
|
loop.set_session_policy("cli:c", max_iterations=2)
|
|
|
|
out = await loop._process_message(_req())
|
|
|
|
assert out is not None
|
|
assert seen["cap"] == 2, "the stamped cap is the session policy's -- the one the loop enforces"
|
|
assert isinstance(seen["window"], int) and seen["window"] > 0
|
|
assert seen["inbound_cap"] is None, "the inbound fire predates the loop's one policy read"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_observers_stash_written_at_after_send_reaches_the_persisted_message(tmp_path):
|
|
class SendCounter(AgentHook):
|
|
async def after_send(self, ctx):
|
|
ctx.metadata.setdefault("observers", {})["send_gate"] = {"fired": 1}
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_text("done")])
|
|
loop = _loop(tmp_path, provider, [SendCounter()])
|
|
|
|
out = await loop._process_message(_req("hello"))
|
|
|
|
assert out is not None
|
|
session = loop.sessions.get_or_create("cli:c")
|
|
stamped = [m for m in session.messages if m.get("observers")]
|
|
assert len(stamped) == 1 and stamped[0]["role"] == "assistant"
|
|
assert stamped[0]["observers"] == {"send_gate": {"fired": 1}}
|
|
|
|
|
|
def test_the_persist_stamp_never_crosses_the_turn_base_into_filed_history():
|
|
"""The stamp's bound: the paper files observers on THE TURN'S message.
|
|
|
|
An answerless turn has no seat, and the assembled window can share dict
|
|
objects with the session record (the curator candidate view), so an
|
|
unbounded search would rewrite a previous turn's filed message in
|
|
place -- this turn's measurements stamped onto last turn's answer."""
|
|
|
|
prior_assistant = {"role": "assistant", "content": "earlier answer"}
|
|
messages = [
|
|
{"role": "user", "content": "earlier question"},
|
|
prior_assistant,
|
|
{"role": "user", "content": "now this"},
|
|
]
|
|
|
|
_stamp_turn_observers(messages, {"observers": {"gate": {"fired": 1}}}, turn_base=2)
|
|
|
|
assert "observers" not in prior_assistant, "filed history must not be rewritten in place"
|
|
assert not any("observers" in m for m in messages), "an answerless turn stamps nothing"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_the_turns_subagent_tier_is_frozen_at_its_start(tmp_path):
|
|
"""A tier switched between two iterations lands on the next turn.
|
|
|
|
The sibling of the iteration cap above: both are read from the policy the
|
|
turn snapshotted, so a `session/set_mode` arriving while the turn runs cannot
|
|
make two sub-agent dispatches in one turn run at different efforts.
|
|
"""
|
|
from raven.agent.subagent.mode_tiers import turn_tier_in_force
|
|
|
|
seen: list[str | None] = []
|
|
held: dict = {}
|
|
|
|
class SwitchMidTurn(AgentHook):
|
|
async def before_iteration(self, ctx):
|
|
seen.append(turn_tier_in_force())
|
|
held["loop"].set_session_policy("cli:c", mode="max")
|
|
return HookDecision()
|
|
|
|
provider = _ScriptedProvider([_tool_call("list_dir", {"path": "."}), _text("done")])
|
|
loop = _loop(tmp_path, provider, [SwitchMidTurn()])
|
|
held["loop"] = loop
|
|
loop.set_session_policy("cli:c", mode="medium")
|
|
|
|
await loop._process_message(_req())
|
|
|
|
assert seen and set(seen) == {"medium"}, f"the turn kept the tier it started on, saw {seen}"
|
|
assert loop.session_policy("cli:c").mode == "max", "the switch did land, for the next turn"
|
|
|
|
|
|
def test_the_loop_wires_this_sessions_tier_into_the_subagent_manager(tmp_path):
|
|
"""The half a later refactor can silently drop.
|
|
|
|
`SubagentManager` reads a session's tier through a callable the loop hands it at
|
|
construction, and nothing asserted the loop hands the right one: both loop-side
|
|
writes survived mutation (`session_tier=lambda key: ""` and a wrong
|
|
`_default_tier`) while the tier ladder's own tests stayed green. Reported by 0xKT
|
|
with a control proving the selection did exercise the ladder.
|
|
|
|
Asserted against literal values rather than against `loop._default_tier`, or a
|
|
wrong default would compare equal to itself and pass.
|
|
"""
|
|
loop = _loop(tmp_path, _ScriptedProvider([_text("plain")]), None)
|
|
|
|
assert loop._default_tier == "high", "the loop resolves the catalogue default once, at construction"
|
|
assert loop.subagents._session_tier("cli:c") == "high", "and a session with no policy inherits it"
|
|
|
|
loop.set_session_policy("cli:c", mode="max")
|
|
assert loop.subagents._session_tier("cli:c") == "max", "a session's own tier reaches the manager"
|
|
assert loop.subagents._session_tier("cli:other") == "high", "and only that session's"
|