337 lines
14 KiB
Python
Raw Permalink Normal View History

refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
"""The code flow's turn participant.
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
Repository instructions and workspace concurrency notices join the system
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
message through the ``system_addendum`` verb. They never rewrite the inbound
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
query. The participant tracks the turn in the session ledger,
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
binds and restores its checklist, and files the workspace report at send.
Session deletion discards product state; new session IDs isolate new tasks.
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
One participant per turn: the checklist binding and the per-directory instruction
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
cache are attributes that die with the turn.
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
"""
from __future__ import annotations
from pathlib import Path
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
from typing import TYPE_CHECKING, Any
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
from loguru import logger
from pydantic import ValidationError
from code_flow.config import FlowConfig
from code_flow.manifest import build_manifest
from code_flow.sessions import LEDGER, SessionLedger
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
from code_flow.system_context import sized_addendum
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
from code_flow.tools.read_state import Owner, ReadSessions, forget_session, owner_for
from code_flow.tools.todo import STORES, TodoStore
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
from raven.agent import workdir
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
from raven.agent.hook.participant import ParticipantHook
from raven.contracts.participant import AgentParticipant, Answer, StepView
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
if TYPE_CHECKING:
from raven.plugins.context import PluginContext
#: The observer entry the ACP layer relays as the prompt response's ``_meta``.
ACP_META_OBSERVER = "acp_meta"
#: The ``_meta`` namespace this product's workspace report travels under.
MANIFEST_META_KEY = "raven.harnessManifest"
CONCURRENCY_NOTICE = (
"# Workspace concurrency\n"
"{count} other Raven-Code session{plural} {verb} working in this same directory right "
"now, and nothing locks the tree. Re-read a file immediately before every write; modify "
"only the files this task explicitly covers; never overwrite unrelated or unexplained "
"existing changes. If a target file changes unexpectedly or appears concurrently modified "
"by another task, stop writing and report it."
)
def concurrency_notice(peers: int) -> str:
plural = "" if peers == 1 else "s"
verb = "is" if peers == 1 else "are"
return CONCURRENCY_NOTICE.format(count=peers, plural=plural, verb=verb)
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
#: The coding set of a checkout's own instruction files, read from the bound
#: working directory. The launcher renders these names into the slice; the
#: slice decides, so an eval that must judge the model alone empties it.
PROJECT_FILES = ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]
#: Per-file ceiling. A repository can carry an arbitrarily large markdown at
#: these names, and a turn's prompt must not inherit that size.
PROJECT_FILE_MAX_CHARS = 24_000
PROJECT_INSTRUCTIONS_HEAD = (
"# Repository instructions\n"
"The working directory carries its own instruction files. They describe how this "
"repository is built, tested and contributed to; follow them for this task unless the "
"task itself says otherwise."
)
def project_instructions(root: Path | None, names: list[str]) -> str:
"""The bound checkout's instruction files, as one block, or empty.
Nothing bound reads nothing: unbound, these names would resolve against the
agent's own home, whose files are the agent's and not a project's. A name
that is missing, is not a regular file, or cannot be read is skipped
rather than raised -- context assembly runs on every turn, and one bad
symlink in someone's checkout must not end the conversation. Not fenced as
untrusted: these are the project's standing instructions to whoever works
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
in it, the same footing the participant stands on, and a data fence would tell
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
the model to ignore exactly what it is being handed to follow.
"""
if root is None or not names:
return ""
try:
root = Path(root).resolve(strict=True)
except (OSError, RuntimeError):
return ""
parts: list[str] = []
seen: set[Path] = set()
for name in names:
path = Path(root) / name
try:
resolved = path.resolve(strict=True)
if not resolved.is_relative_to(root):
logger.warning("code-flow: skipping an instruction file outside the working directory: {}", path)
continue
if resolved in seen or not resolved.is_file():
continue
with resolved.open(encoding="utf-8", errors="replace") as source:
text = source.read(PROJECT_FILE_MAX_CHARS + 1)
seen.add(resolved)
except (OSError, RuntimeError) as exc:
logger.warning("code-flow: could not read the project file {}: {}", path, exc)
continue
if len(text) > PROJECT_FILE_MAX_CHARS:
text = text[:PROJECT_FILE_MAX_CHARS] + "\n\n... (truncated to fit the context window)"
parts.append(f"## {path.name}\n\n{text.rstrip()}")
if not parts:
return ""
return PROJECT_INSTRUCTIONS_HEAD + "\n\n" + "\n\n".join(parts)
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
class CodeParticipant(AgentParticipant):
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
"""The code flow's judgements and bookkeeping, one instance per turn.
Process-level dependencies (the ledger, the checklist store, the slice's
file names) arrive through ``__init__``; what used to ride the hook
context's metadata dict -- the turn's checklist binding, the per-directory
instruction cache, the pending restore note the sizing must count -- is an
attribute here and dies with the turn.
"""
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
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 __init__(
self,
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
ledger: SessionLedger,
project_files: list[str],
todos: TodoStore | None,
flow_enabled: bool,
reads: ReadSessions | None,
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
) -> None:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._ledger = ledger
self._project_files = project_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
# The checklist store this product's ``todo`` tool writes through, or
# None when the tool face is not served (nothing to bind or restore).
self._todos = todos
self._flow_enabled = flow_enabled
self._reads = reads
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._todo_binding: tuple[str, str | None] | None = None
self._instructions: tuple[Any, str] | None = None
self._pending_note: str | None = None
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
async def intake(self, text: str, step: StepView) -> Answer | None:
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
# Commands return before iteration or after_send, so they must not
# create an in-flight mark for a turn that will never report back.
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
if (text or "").strip().lower() in {"/new", "/help"}:
return None
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
cwd = workdir.current()
if self._flow_enabled:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._ledger.begin_turn(step.session_key, cwd)
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 self._todos is not None:
try:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._todos.bind(step.session_key, cwd)
self._todo_binding = (step.session_key, str(cwd) if cwd is not None else None)
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
except Exception: # noqa: BLE001 - a record problem must not cost the turn
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
logger.exception("code-flow: could not bind the checklist for {}", step.session_key)
return None
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
async def advise(self, step: StepView) -> str | None:
"""The checklist, restored into context when the window elided it."""
if step.response is not None:
# Asked before the call and after it; everything here belongs before.
return None
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 self._reads is not None:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._reads.bind(step.session_key)
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 self._flow_enabled:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._ledger.touch(step.session_key)
note: str | None = None
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 self._todos is not None:
# System turns skip inbound, and the loop can select another
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
# session after inbound. The turn's binding survives rollbacks
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
# because the participant does.
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
cwd = workdir.current()
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
binding = (step.session_key, str(cwd) if cwd is not None else None)
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
try:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
if self._todo_binding != binding or not self._todos.is_bound:
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
self._todos.bind(*binding)
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._todo_binding = binding
snapshot = self._todos.snapshot_if_hidden(list(step.transcript))
if snapshot is not None:
logger.info("code-flow: restoring the checklist into context for {}", step.session_key)
note = snapshot
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
except Exception: # noqa: BLE001 - a checklist failure must not discard repository instructions
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
logger.exception("code-flow: could not restore the checklist for {}", step.session_key)
# What the sizing below must count: the note lands on the prompt in
# the same call the addendum does.
self._pending_note = note
return note
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
async def system_addendum(self, step: StepView) -> Answer | None:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
if not self._flow_enabled:
return None
cwd = workdir.current()
if self._instructions is None or self._instructions[0] != cwd:
self._instructions = (cwd, project_instructions(cwd, self._project_files))
peers = self._ledger.peers_in_flight(step.session_key)
return sized_addendum(
step.transcript,
step.tools,
self._instructions[1],
concurrency_notice(peers) if peers else "",
window=step.window,
pending_note=self._pending_note,
)
async def archive(self, step: StepView, reply: str | None) -> dict[str, dict[str, Any]] | None:
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 self._reads is not None:
self._reads.unbind()
if not self._flow_enabled:
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
return None
record = self._ledger.record(step.session_key)
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
cwd = workdir.current()
if cwd is None and record is not None and record.cwd:
cwd = Path(record.cwd)
report = build_manifest(
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
step.session_key,
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
cwd,
record.base_commit if record is not None else None,
shared_with=len(record.peers) if record is not None else 0,
)
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
self._ledger.end_turn(step.session_key)
return {ACP_META_OBSERVER: {MANIFEST_META_KEY: report}}
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
class CodeFlowHook(ParticipantHook):
"""The code flow's seat in the hook chain: one participant per turn.
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
Kept as a named class rather than a bare ``ParticipantHook`` because the
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
constructor is the product's assembly surface -- the factory below and a
ledger's worth of tests wire sessions through it -- and because
``isinstance`` is how the factory's admission is asserted.
"""
def __init__(
self,
ledger: SessionLedger | None = None,
project_files: list[str] | None = None,
todos: TodoStore | None = None,
*,
flow_enabled: bool = True,
reads: ReadSessions | None = None,
) -> None:
seated_ledger = ledger if ledger is not None else LEDGER
names = list(project_files or [])
super().__init__(
"code_flow",
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
lambda: CodeParticipant(seated_ledger, names, todos, flow_enabled, reads),
# This participant does not review, so no verdict of its can send a turn
refactor(*): let a sub-agent write a conduct instead of six hook phases (#469) ## Summary Follows #468 (merged as `869ad78a`), which moved the charter reads and the window's mid-turn shrinking onto the harness roles. This branch is rebased onto `main` and carries only its own three commits. A sub-agent's product logic was an `AgentHook` subclass: six phase methods over a fourteen-field context it could write, with the turn's own state kept in the context's free-form `metadata` dict. Surveyed before this change, the five bundled plugins had 71 phase methods, 42 of them doing real work, reading fourteen context fields and using six decision fields. Every one of them fits a small set of verbs. This PR makes those verbs the contract, in three commits. **1. A sub-agent writes a conduct instead of six hook phases.** New factory-loop-tier paper `contracts/agent_conduct.py`: `AgentConduct` with nine optional verbs (`intake`, `select_tools`, `advise`, `system_addendum`, `review`, `salvage`, `outbound`, `archive`, `observe`), answered against a read-only `StepView` of fourteen fields, with `Intake` and `Verdict` (Accept / Resample / End) as the answers and a `ConductFactory` because the host builds one conduct per turn. It sits beside `loop_hooks` rather than replacing it. The six phases remain the loop's *timing* contract: when the loop asks, in what order, what a refusal does. This is the *judgement* contract: given one step, what does this agent say about it. `ConductHook` seats one in the other, so a plugin that still ships a plain `AgentHook` keeps working and the composite's ordering, merging and rollback are untouched. All five bundled plugins are ported: design-engine, ppt-engine, code-flow, oncall-flow and research-flow. Research keeps its six-phase gate chain: the gates now subclass a plugin-private `Gate` and read a `GateCtx` the conduct builds from its `StepView` and its own turn-private facts, so six thousand lines of gate bodies did not move and its wrappers still see the cross-gate state they read. The turn's conduct and the system-message addendum it splices live in the turn's own `metadata` dict, not on the hook: one hook instance serves every turn a process runs, and a system turn can overlap a user one on the same chain. **2. The conducts seat on the roles.** `MemoryModule.intake`, `PlanningModule.advise`, `ActionModule.review` and `ActionModule.salvage` each take this turn's conducts, so a replaced role decides what a plugin's judgement does rather than the seat deciding it. The composition rules live in `raven/agent/harness/conducts.py`: the first non-Accept verdict wins, advice joins in order, the first salvage wins, an intake threads the text through each conduct. `run_turn` binds the harness for the turn the way it binds the model, and the seat falls back to the same rules when nothing is bound, which is how a plugin test drives a hook directly. Contract papers: the conduct paper is factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move with it. `CONTRACTS_LINE_CEILING` 3,200 to 3,420, each bump with its own review paragraph in `tests/test_kernel_budget.py`. **3. What the review found.** Eleven threads, all resolved in the third commit. The ones that changed behaviour rather than prose: `CodeFlowHook` kept its `rolls_back_iterations = False` (inheriting `True` from the new base had it hold every reply behind the draft gate instead of streaming); `StepView` now publishes deep-frozen nested values, since freezing only the outer tuple left a conduct able to write through to `ctx.messages`; a turn's conducts are collected at the role boundary, so a replaced role sees one batch of the turn's judgements rather than one call per seat; an addendum is located by its own text rather than a saved offset, which two conducts appending system text used to shift out from under each other; `Planning` and `Action` gained binders, so a replacement role missing a new member is named at assembly rather than swallowed by the composite's `except Exception`. `CONTEXT.md` carries the Agent Conduct term and the Agent Hook entry no longer describes what this PR replaces. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates. CI runs these at the branch tip (17 pass, 1 skipped -- the skipped row is the disabled Claude Mention workflow). Locally, at each of the three commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken at each of the three commits. The suite is green at each, and no commit adds a failure that `main` does not already show on this machine (this checkout has the heavy extras uninstalled, so the local run carries failures `main` carries too -- CI is the authority, and it is green). The loop's own e2e files, which the default selection leaves out, were run too (charter, playbook, truncation, direct chat, fallback chain, ACP stdio): no new failure. Behaviour preservation. The oracle for this change is the hook seam itself: all five plugins driven through every phase of a multi-iteration turn under the same scripted provider, recording each phase's decision and the observers it files. Outputs normalised for nonces and temp paths, then byte-compared. Re-run after the review fixes at the branch tip `81e6f423` (all three commits), against `main` at `c65c2059`: | scenario | bytes | | --- | --- | | five-plugin hook seam | 23,840 == 23,840 | | a whole turn with no playbook (host turn, spawned sub-agent, tool calls and refusals) | 12,821 == 12,821 | | six window-shrink scenarios | 133,371 == 133,371 | These cover the tip, not each commit separately. The seam comparison is the one that matters most for the third commit: its first fix changed `rolls_back_iterations` for code-flow, which decides whether replies stream or are held, and the seam oracle records the decision at every phase, so an unintended change there shows as a diff rather than as silence. A unit test proves the seat is a real decision point rather than a pass-through: with a lenient Action role bound, a conduct's Resample is not applied, and Planning's advice and Memory's intake are what the loop receives. Real model, Sonnet 4.5 through OpenRouter, at the branch tip: - playbook on, in-process lane: two workers, each receives the charter (3 checks), writes its file, finishes; 26 recorded model calls - playbook on, ACP fork lane: the charter prompt crosses the process boundary (the fork answers ZEBRA where the task text says PONG, so the brief reached the forked model through Memory), and a charter check blocks `write_file` to `notes/hi.txt` against a `pathPrefix: out/` rule - Raven-Research, a fork running the full gate chain: `plain-first: escalated_tool`, then `sufficiency-gate: released on the pages at iteration 4 after 2 searches / 2 pages` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk No user-visible behaviour change is intended, and the hook-seam comparison is byte-identical on every phase it covers. For plugin authors: the six-phase `AgentHook` is unchanged and a plugin shipping one keeps working. `ConductHook` is an adapter that seats a conduct in that same chain. For anyone replacing a harness role: the role protocols gain `intake`, `advise`, `review` and `salvage`, so a replacement written against the old protocol needs them. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-18 14:37:11 +08:00
# back, and the loop should stream the reply rather than hold it.
rolls_back=False,
)
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
class SessionForget:
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
"""The session-events seat: a deleted session leaves the ledger, and its
saved checklist goes with it."""
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
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 __init__(self, ledger: SessionLedger, todos: TodoStore | None = None, read_owner: Owner | None = None) -> None:
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
self._ledger = ledger
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
self._todos = todos
self._read_owner = read_owner
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
def on_session_deleted(self, session_key: str, removed: bool) -> None:
self._ledger.forget(session_key)
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 self._read_owner is not None:
forget_session(self._read_owner, session_key)
if self._todos is not None:
try:
if self._todos.discard(session_key):
logger.info("code-flow: discarded the saved checklist of deleted session {}", session_key)
except OSError as exc:
logger.warning("code-flow: could not discard the checklist of {}: {}", session_key, exc)
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
def make_session_forget(ledger: SessionLedger) -> SessionForget:
return SessionForget(ledger)
def _flow_config(ctx: "PluginContext", seat: str) -> FlowConfig | None:
try:
return FlowConfig.from_slice(dict(ctx.config or {}))
except ValidationError as exc:
logger.warning("code-flow: config slice is malformed; declining the {}: {}", seat, exc)
return None
def make_flow_hook(ctx: "PluginContext") -> CodeFlowHook | None:
"""Factory for the ``code_flow`` hook contribution.
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
Checklist and file-observation lifecycles remain while tools are enabled,
even when the flow's notices and workspace reports are off. An absent or malformed
slice casts no surface.
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
"""
cfg = _flow_config(ctx, "hook")
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 cfg is None or not (cfg.enabled or cfg.tools.enabled):
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
return None
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 CodeFlowHook(
project_files=cfg.project_files,
todos=_todo_store(ctx, cfg),
flow_enabled=cfg.enabled,
reads=ReadSessions(owner_for(ctx)) if cfg.tools.enabled else None,
)
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
def make_session_observer(ctx: "PluginContext") -> SessionForget | None:
"""Factory for the ``session_forget`` observer contribution; same admission."""
cfg = _flow_config(ctx, "observer")
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 cfg is None or not (cfg.enabled or cfg.tools.enabled):
return None
return SessionForget(LEDGER, todos=_todo_store(ctx, cfg), read_owner=owner_for(ctx) if cfg.tools.enabled else None)
def _todo_store(ctx: "PluginContext", cfg: FlowConfig) -> TodoStore | None:
"""The checklist store the ``todo`` tool factory uses, or None when the
tool face is off -- then there is no tool to bind a session for."""
if not cfg.tools.enabled:
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
return None
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 STORES.for_home(ctx.services.workspace)
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
__all__ = [
"ACP_META_OBSERVER",
"CONCURRENCY_NOTICE",
"MANIFEST_META_KEY",
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
"PROJECT_FILES",
"PROJECT_FILE_MAX_CHARS",
"PROJECT_INSTRUCTIONS_HEAD",
refactor(*): close out the participant contract the five plugins now write (#495) ## Summary #469 gave a bundled sub-agent nine verbs in place of six hook phases. Reviewing it turned up a list of things the contract said but did not yet do, and this PR closes that list. No behaviour change is intended: the point is that the same seam becomes something a role can replace and something a generated judgement can enter. **1. The roles are named apart from the verbs, and `observe` is gone.** `ActionModule.review` and the participant's `review` were two different things a line apart. The four delegating role methods now say what they do -- they ask -- and the verbs keep their own names, so `ask_review` asks `review`. `observe` is removed: a verb with no return value decides nothing and can only keep state a participant is forbidden to keep. `outbound` says on its own docstring that it is the one verb with no role seat, and `StepView` gains `phase`, so a verb asked at two moments reads which one it is rather than inferring it from whichever other field happens to be set (`tools_ran` becomes a property derived from it, so the two cannot disagree). **2. The three verbs the seat was applying itself get a seat.** `system_addendum`, `archive` and `select_tools` were rendered straight onto the hook decision, so each was the one judgement in the set with nowhere to compose two participants, nowhere to vet what came back, and nothing a replacement role could decide. They join the other four: `MemoryModule.ask_system_addendum` / `ask_archive` and `CapabilityModule.ask_select_tools`. The seat is not the point where narrowing takes effect -- `select` still is, and the registry still adjudicates every call -- so a participant narrows after the product has spoken and never instead of it. **3. A participant answers with plain data.** `review`, `intake` and `system_addendum` returned host classes (`Verdict`, `Intake`) and `salvage` returned `Any`. `Accept`, `Resample`, `End` and `Intake` are now builders returning plain mappings, the host reads one back with `read_verdict` / `read_intake`, and an answer it cannot read is silence rather than a refusal. That is what makes the third invariant real and what lets a judgement compiled from source answer the same verbs a plugin does -- it can build a `dict`; it cannot build a host class. **4. A dispatch's judgements are a participant.** `judge` was the one verb a role answered by reading the dispatch's own `checks` and `code` for itself. A Charter now enters as a participant like any other, `ActionModule.ask_judge` takes the list, and the merge is a veto so the first refusal decides. The participant list becomes the only route an external judgement takes, which is the thing step four needs: a judgement generated for one dispatch joins the same list without a second way in. **5. The rename.** `AgentConduct` is `AgentParticipant`, `contracts/agent_conduct.py` is `contracts/participant.py`, `agent/hook/conduct.py` is `agent/hook/participant.py`, and `agent/harness/conducts.py` is `agent/harness/participants.py`. "Conduct" was already taken in this tree -- raven-code's Coding Conduct prompts are a different thing -- and a reader hitting both had no way to tell them apart. The rename was done symbol by symbol, not by search and replace, for exactly that reason. **7. Review (LivXue, at 3a1bf07c).** The `judge` disclosure had reached two of its four homes; the other two are `ActionModule.ask_judge` on the paper and `DefaultAction.ask_judge`, and they survived because they phrase the claim without naming any symbol the earlier fix touched. The test meant to pin that claim could not fail for the reason it was written -- it asserted the refusal rather than the argument, and built a `ParticipantHook` it dropped -- and now asserts what the registry hands the role, mutation-checked by wiring a participant through. `compose_judge` exploded a one-sentence `str` refusal into one refusal per character, because `str` satisfies `Sequence[str]` structurally; `charter_code.run_judge` coerced it where this composition used to live and the handling did not move with it. Two records corrected: the type-only `raven.contracts` -> `raven.agent` edge, the first in the tree and the price of moving `Verdict` and `Intake` off the paper, is now written beside the import contract it bends rather than left to be discovered; and the ledger entry for the 3,200 -> 3,410 bump is restored to the names and count it was written with. Not taken: reading `step.phase` at `research_flow/flow.py:1000` -- the gate chain's phase vocabulary and `StepView.phase` coincide on `after_iteration` only, and that call site wants `before_execute_tools`, which is the key `_phase` dispatches on. **6. What the paper was claiming and not doing.** Read back over the seam afterwards rather than over the diff. ``judge`` read as though a plugin's override were asked ahead of a dispatch's own rules; it is not, and cannot be as written, because the party that asks the verb is ``ToolRegistry.execute``, which is not the hook chain and holds no handle on this turn's participants. The merge order is real; nothing puts a plugin in the list. Wiring one through is a turn-scoped register this change does not add, and it would start refusing calls that run today, so it is named on the paper and pinned by a test instead. ``max_iterations`` had lost its docstring to the property inserted between the field and the string documenting it. No executable line moves in this commit: the module's AST, docstrings stripped, is identical to its parent's. CONTEXT.md's entry is rewritten to the end state, including the two kinds of role method, the two verbs that are exceptions, and the note that the Coding Conduct prompts are unrelated. One item from the same list is deliberately not here: a `planning.*` block on the dispatch parameters. It is not a contract closeout but a new model-facing field, and it needs the generator's schema and prompt to move with it. Contract papers: `participant.py` and `harness.py` are both factory-loop tier, so the contract-tier digest and `CONTRACTS_VERSION` do not move. `CONTRACTS_LINE_CEILING` 3,440 to 3,470 to 3,500 to 3,540 to 3,550 to 3,570, each bump with its own review paragraph in `tests/test_kernel_budget.py`. The chain was recomputed after rebasing onto #410, which added seven lines to `loop_hooks.py` inside the old headroom and left one commit here with one line of it; every "Measured at" figure in that file is the count at that commit. ## Type - [ ] Fix - [ ] Feature - [ ] Docs - [ ] CI / tooling - [x] Refactor - [ ] Other ## Verification Gates, run at each of the seven commits: ``` uv run ruff check --no-cache raven evolver agents plugins-dist tests scripts uv run ruff format --check --no-cache raven evolver agents plugins-dist tests scripts uv run lint-imports uv run pytest -q npx commitlint --from origin/main --to HEAD --config commitlint.config.cjs uv run python scripts/check_commit_messages.py origin/main..HEAD uv run python scripts/check_source_language.py origin/main..HEAD uv run python scripts/check_large_files.py origin/main..HEAD ``` Import contracts: 10 kept, 0 broken. The suite is green: the failures this machine shows are the same ones it shows on an unmodified `main` in the same worktree layout (missing browser and optional packages), and this branch adds none. Behaviour preservation. The oracle is the hook seam itself. `main` and this branch were run under the same scripted provider, outputs normalised for nonces and temp paths, then byte-compared. Four scenarios, all identical: - the five-plugin hook seam, every phase's decision and metadata per iteration (23,840 bytes) - a whole turn with no playbook: host turn, spawned sub-agent, tool calls and refusals - a playbook-on worker lane in process, including the charter refusals - six window-shrink scenarios This is the seam the change is about, and identical output across it is what "no behaviour change" means here -- it is not a claim about paths the four scenarios do not reach. Two claims had no assertion anywhere and now do. ``phase``, and the ``tools_ran`` derived from it, are what three of the five bundled plugins branch on -- ppt on its close, oncall on its counter, research on which gate runs -- and a mistyped phase string at one of the six call sites would have changed what they do with a green suite. The read-only test now also covers ``mode_overlay``, the one frozen field it skipped. All three assertions were mutation-checked: mislabelling a phase, deriving ``tools_ran`` from the wrong one, and dropping the freeze each turn exactly their own test red. New tests, each written against a claim the contract now makes rather than against the code: a participant cannot write through the `StepView` it is shown; an answer the host cannot read is silence, not a refusal; a participant that answers with a mapping it built itself is understood; every verb with a seat goes through its role rather than around it, asserted as a set so a new verb that bypasses its role fails; two seats in one chain each keep one addendum; two turns in flight keep their own participants; a bound role decides what a participant's verdict does; a plugin's own judgement speaks before the dispatch's, and a silent participant lets the next one speak. Real model, Sonnet 4.5 through OpenRouter, on this branch: a query generates a playbook, two sub-agents are instantiated and run, each writes its `summary.md` under its own fence, and both results are announced back to the originating session. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk For plugin authors: the six-phase `AgentHook` is untouched and a plugin shipping one keeps working. A plugin written against #469's `AgentConduct` needs the new names and, if it answered with `Verdict` or `Intake`, the builders instead -- the five bundled plugins are ported here and are the worked examples. One verb narrowed, and silently for a plugin that used the width. `salvage` was annotated `Any | None` and `compose_salvage` returned whatever was not None; it is now `str | None` and only a non-empty string is taken. A third-party plugin that salvages with a reply object rather than text stops being heard rather than raising -- which is the third invariant working as written, and worth knowing before upgrading. The narrowing is deliberate: `salvage` answers the text a turn sends when it produced none, and `Any` was not a contract. For anyone replacing a harness role: the four delegating methods are renamed and four more are added, so a replacement written against #469 needs them. `bind()` names the missing member at assembly rather than failing inside a turn. Rollback is a revert of the merge commit. Nothing persisted on disk changes shape. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues Follows #468 and #469. Generated with Claude Code (https://claude.com/claude-code) --------- Co-authored-by: yao pengfei <yaopengfei@shanda.com> Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-09-20 11:36:35 +08:00
"CodeParticipant",
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
"CodeFlowHook",
"SessionForget",
"concurrency_notice",
"make_flow_hook",
"make_session_forget",
"make_session_observer",
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
"project_instructions",
fix(tools): an array sent as its own JSON is still an array ## Summary Reported as "deliver_files is broken". It is not: **the tool never ran.** Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered: ``` Error: Invalid parameters for tool 'deliver_files': files should be array ``` What the model sent was the array, spelled as a string: ```json {"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."} ``` `cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify. ## Type - [x] Fix - [ ] Feature ## The edge of the forgiving is the design When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error. **Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through. **A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage. ## Not just deliver_files Six built-in tools declare an array or object parameter and were all exposed: | tool | parameter | |---|---| | `deliver_files` | `files` | | `ask_user` | `questions` | | `image_generate` | `images` | | `message` | `media` | | `create_playbook` | `skills` | | `video_generate` | `params` | The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch. ## Verification ``` make lint-python ruff check + ruff format --check, 1850 files make lint-imports 9 contracts kept, 0 broken pytest tests/ 19,699 passed, 7 failed (all pre-existing, see below) ``` - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots -- no user-facing string **End to end, through the real tool**, with the exact payload that failed five times in production: ``` files sent as: str -> [{"path": ".../poster.png", "title": "..."}] returned: Delivered 1 file(s): poster.png (72 B). still "should be array": False registered in the store: True ``` Twelve cases, five mutations, each killing at least one: | mutation | red | |---|---| | drop the whole branch (the old behaviour) | 3 | | raise instead of falling through on a parse failure | 5 | | accept the parse whatever type it yielded | 1 | | do not re-cast the parsed value, so items are not cast | 1 | | widen the tuple to include `string` | **survived -- unreachable** | The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so. **Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own. ## Risk - [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before - [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed - [x] Rollback path is clear -- single-commit revert ## Related Issues N/A ## Swept `mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`. - **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects. - **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`. - **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case). - **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts. - **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none. - **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value. - **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed. Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text). ## Deliberately not fixed The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument. ## Moved from !594 Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name. Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
]