## 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.
559 lines
19 KiB
Python
559 lines
19 KiB
Python
"""UnifiedContextEngine — EverOS lane (recall + SkillForgeRouter) behavior.
|
||
|
||
Formerly the ``DefaultContextEngine`` two-track tests. The two-track
|
||
gather (``backend.recall`` for ``# Memory`` + ``SkillForgeRouter`` for
|
||
``# Skills``) is now the EverOS lane of the single
|
||
:class:`UnifiedContextEngine`. These tests exercise that lane through
|
||
the fast path (empty history → no Curator LLM call), which is where the
|
||
recall / router outputs land in the prompt.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import pytest
|
||
|
||
from raven.agent.context import ContextBuilder
|
||
from raven.config.raven import ContextConfig
|
||
from raven.context_engine import ContextAssembler, TurnContext
|
||
from raven.context_engine.segments import (
|
||
ActiveSkillsSegmentBuilder,
|
||
BootstrapSegmentBuilder,
|
||
IdentitySegmentBuilder,
|
||
MemorySegmentBuilder,
|
||
SkillsSegmentBuilder,
|
||
)
|
||
from raven.context_engine.segments.curator import CuratorSegmentBuilder
|
||
from raven.contracts.assembled import TokenBudget
|
||
from raven.contracts.memory import Memory
|
||
from raven.memory_engine.skill_forge import RouterHit, SkillForgeRouter
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Test doubles
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class _StubSource:
|
||
"""Configurable SkillSource — records call args + delay."""
|
||
|
||
def __init__(
|
||
self,
|
||
name: str,
|
||
weight: float = 1.0,
|
||
hits: list[RouterHit] | None = None,
|
||
delay_s: float = 0.0,
|
||
) -> None:
|
||
self.name = name
|
||
self.weight = weight
|
||
self._hits = hits or []
|
||
self._delay = delay_s
|
||
self.calls: list[tuple[str, int]] = []
|
||
|
||
async def search(self, query, history, k):
|
||
await asyncio.sleep(self._delay)
|
||
self.calls.append((query, k))
|
||
return list(self._hits)
|
||
|
||
|
||
class _StubBackend:
|
||
"""Minimal MemoryBackend mock — recall returns canned hits."""
|
||
|
||
def __init__(
|
||
self,
|
||
recall_response: list[Memory] | None = None,
|
||
delay_s: float = 0.0,
|
||
recall_raises: Exception | None = None,
|
||
) -> None:
|
||
self._recall_response = recall_response or []
|
||
self._delay = delay_s
|
||
self._recall_raises = recall_raises
|
||
self.recall_calls: list[dict[str, Any]] = []
|
||
|
||
async def start(self):
|
||
pass
|
||
|
||
async def stop(self):
|
||
pass
|
||
|
||
async def feedback(self, signals):
|
||
pass
|
||
|
||
async def store(self, session_id, messages, *, metadata=None):
|
||
pass
|
||
|
||
async def recall(self, query, *, user_id=None, agent_id=None, top_k):
|
||
await asyncio.sleep(self._delay)
|
||
self.recall_calls.append(
|
||
{
|
||
"query": query,
|
||
"user_id": user_id,
|
||
"agent_id": agent_id,
|
||
"top_k": top_k,
|
||
}
|
||
)
|
||
if self._recall_raises is not None:
|
||
raise self._recall_raises
|
||
return list(self._recall_response)
|
||
|
||
|
||
class _StubProvider:
|
||
api_key = "test"
|
||
|
||
def get_default_model(self) -> str:
|
||
return "stub"
|
||
|
||
async def chat_with_retry(self, *args, **kwargs):
|
||
# Only reached on the slow path; these tests stay on fast path.
|
||
raise NotImplementedError
|
||
|
||
|
||
def _budget() -> TokenBudget:
|
||
return TokenBudget(
|
||
context_length=100_000,
|
||
reserved_output=4_000,
|
||
reserved_tools=2_000,
|
||
reserved_system=1_000,
|
||
available_history=93_000,
|
||
)
|
||
|
||
|
||
def _turn(msg: str = "hi", **kw) -> TurnContext:
|
||
return TurnContext(
|
||
current_message=msg,
|
||
media=kw.get("media"),
|
||
channel=kw.get("channel"),
|
||
chat_id=kw.get("chat_id"),
|
||
selected_skills=kw.get("selected_skills"),
|
||
)
|
||
|
||
|
||
@pytest.fixture
|
||
def builder(tmp_path: Path) -> ContextBuilder:
|
||
return ContextBuilder(workspace=tmp_path)
|
||
|
||
|
||
def _engine(
|
||
builder: ContextBuilder,
|
||
*,
|
||
router: SkillForgeRouter,
|
||
backend: _StubBackend | None,
|
||
user_id: str = "default",
|
||
skill_top_k: int = 5,
|
||
memory_top_k: int = 5,
|
||
) -> ContextAssembler:
|
||
builders = [
|
||
IdentitySegmentBuilder(builder.workspace),
|
||
BootstrapSegmentBuilder(builder.workspace),
|
||
MemorySegmentBuilder(
|
||
builder.memory,
|
||
backend,
|
||
user_id=user_id,
|
||
memory_top_k=memory_top_k,
|
||
),
|
||
ActiveSkillsSegmentBuilder(builder.skills),
|
||
SkillsSegmentBuilder(router, skill_top_k=skill_top_k),
|
||
CuratorSegmentBuilder(
|
||
workspace=builder.workspace,
|
||
config=ContextConfig(),
|
||
provider=_StubProvider(),
|
||
model="stub",
|
||
context_window_tokens=100_000,
|
||
get_tool_definitions=lambda: [],
|
||
),
|
||
]
|
||
return ContextAssembler(builders, lambda: [])
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Identity / lifecycle
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestEngineIdentity:
|
||
def test_name(self, builder: ContextBuilder) -> None:
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
assert eng.name == "context_assembler"
|
||
|
||
def test_owns_compaction_is_true(self, builder: ContextBuilder) -> None:
|
||
# The unified engine owns its own archival compaction (Curator
|
||
# lane), so AgentLoop hands it the full append-only log and skips
|
||
# the host MemoryConsolidator.
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
assert eng.owns_compaction is True
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Two-track concurrency (recall + router.select)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestTwoTrackConcurrency:
|
||
async def test_skill_and_memory_run_concurrently(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
"""Neither track is let through until both have arrived, so this passes
|
||
only if they overlap. The wall-clock total this used to assert on raced
|
||
whatever else the machine was doing, and failed under load."""
|
||
rendezvous = asyncio.Barrier(2)
|
||
|
||
class _RendezvousSource(_StubSource):
|
||
async def search(self, query, history, k):
|
||
await rendezvous.wait()
|
||
return await super().search(query, history, k)
|
||
|
||
class _RendezvousBackend(_StubBackend):
|
||
async def recall(self, query, *, user_id=None, agent_id=None, top_k):
|
||
await rendezvous.wait()
|
||
return await super().recall(query, user_id=user_id, agent_id=agent_id, top_k=top_k)
|
||
|
||
eng = _engine(
|
||
builder,
|
||
router=SkillForgeRouter([_RendezvousSource("local", hits=[])]),
|
||
backend=_RendezvousBackend(recall_response=[]),
|
||
)
|
||
async with asyncio.timeout(5):
|
||
await eng.assemble(
|
||
session_key="s1",
|
||
session_messages=[],
|
||
budget=_budget(),
|
||
turn=_turn(),
|
||
)
|
||
|
||
async def test_track_ids_passed_to_recall(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
backend = _StubBackend()
|
||
eng = _engine(
|
||
builder,
|
||
router=SkillForgeRouter([]),
|
||
backend=backend,
|
||
user_id="alice",
|
||
)
|
||
await eng.assemble("s", [], _budget(), turn=_turn("git resolver"))
|
||
assert backend.recall_calls == [
|
||
{
|
||
"query": "git resolver",
|
||
"user_id": "alice",
|
||
"agent_id": None,
|
||
"top_k": 5,
|
||
},
|
||
]
|
||
|
||
async def test_top_k_propagated_per_track(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
source = _StubSource("local", hits=[])
|
||
backend = _StubBackend()
|
||
eng = _engine(
|
||
builder,
|
||
router=SkillForgeRouter([source]),
|
||
backend=backend,
|
||
skill_top_k=3,
|
||
memory_top_k=7,
|
||
)
|
||
await eng.assemble("s", [], _budget(), turn=_turn("q"))
|
||
# SkillForgeRouter applies an over-fetch factor; the source sees k*2
|
||
# by default.
|
||
assert source.calls[0][1] == 6 # 3 × default over_fetch_factor 2
|
||
assert backend.recall_calls[0]["top_k"] == 7
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# AssembledContext metadata
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestAssembledMetadata:
|
||
async def test_injected_skill_ids(self, builder: ContextBuilder) -> None:
|
||
hits = [
|
||
RouterHit(qualified_id="local/a", name="a", content="", score=0.5),
|
||
RouterHit(qualified_id="everos/b", name="b", content="", score=0.5),
|
||
]
|
||
source = _StubSource("local", hits=hits)
|
||
eng = _engine(builder, router=SkillForgeRouter([source]), backend=_StubBackend())
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert set(ac.metadata["injected_skill_ids"]) == {"local/a", "everos/b"}
|
||
|
||
async def test_memory_hits_count(self, builder: ContextBuilder) -> None:
|
||
memories = [Memory(text=f"fact-{i}") for i in range(3)]
|
||
eng = _engine(
|
||
builder,
|
||
router=SkillForgeRouter([]),
|
||
backend=_StubBackend(recall_response=memories),
|
||
)
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.metadata["memory_hits"] == 3
|
||
|
||
async def test_engine_label(self, builder: ContextBuilder) -> None:
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.metadata["engine"] == "context_assembler"
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Block rendering — recall → # Memory, router → # Skills
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestRendering:
|
||
async def test_recalled_memory_merged_into_memory_segment(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
backend = _StubBackend(
|
||
recall_response=[Memory(text="user likes espresso")],
|
||
)
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=backend)
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
sys_msg = ac.messages[0]
|
||
assert sys_msg["role"] == "system"
|
||
assert "# Memory" in sys_msg["content"]
|
||
assert "# Recalled memory" not in sys_msg["content"]
|
||
assert "user likes espresso" in sys_msg["content"]
|
||
|
||
async def test_router_skills_in_skills_segment(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
hits = [
|
||
RouterHit(
|
||
qualified_id="local/git-resolver",
|
||
name="git-resolver",
|
||
content="resolves git refs.",
|
||
score=0.8,
|
||
),
|
||
]
|
||
source = _StubSource("local", hits=hits)
|
||
eng = _engine(builder, router=SkillForgeRouter([source]), backend=_StubBackend())
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
sys_content = ac.messages[0]["content"]
|
||
# No addendum channel and no "# Retrieved skills" heading — the
|
||
# router body lands in segment 5 (# Skills).
|
||
assert ac.system_prompt_addition is None
|
||
assert "# Retrieved skills" not in sys_content
|
||
assert "# Skills" in sys_content
|
||
assert "git-resolver" in sys_content
|
||
assert "[local/git-resolver]" in sys_content
|
||
assert "resolves git refs" in sys_content
|
||
|
||
async def test_no_skills_addition_when_empty(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.system_prompt_addition is None
|
||
|
||
async def test_no_recalled_block_when_empty(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
eng = _engine(
|
||
builder,
|
||
router=SkillForgeRouter([]),
|
||
backend=_StubBackend(recall_response=[]),
|
||
)
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert "# Recalled memory" not in ac.messages[0]["content"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Graceful degrade — no backend wired
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestNoBackendDegrade:
|
||
async def test_recall_skipped_router_local_only(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
"""With ``backend=None`` the recall lane yields [] and the local
|
||
router still feeds # Skills."""
|
||
hits = [
|
||
RouterHit(
|
||
qualified_id="local/x",
|
||
name="x",
|
||
content="body",
|
||
score=0.5,
|
||
)
|
||
]
|
||
source = _StubSource("local", hits=hits)
|
||
eng = _engine(builder, router=SkillForgeRouter([source]), backend=None)
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.metadata["memory_hits"] == 0
|
||
assert "local/x" in ac.metadata["injected_skill_ids"]
|
||
assert "# Skills" in ac.messages[0]["content"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Failure semantics
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestFailureSemantics:
|
||
async def test_backend_recall_exception_degrades_to_no_hits(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
"""Memory backend outage no longer surfaces to AgentLoop: recall is
|
||
bounded and isolated the same way SkillForgeRouter's sources are."""
|
||
backend = _StubBackend(recall_raises=RuntimeError("backend down"))
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=backend)
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.metadata["memory_hits"] == 0
|
||
|
||
async def test_phase_a_builder_failure_degrades_its_segment_only(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
"""One failing segment builder loses its segment, never the turn; the
|
||
name lands in metadata so the loop can tell the user."""
|
||
|
||
class _Boom:
|
||
name = "boom"
|
||
order = 5
|
||
|
||
async def build(self, ctx):
|
||
raise RuntimeError("segment source down")
|
||
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
eng._phase_a = [*eng._phase_a, _Boom()]
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.metadata["degraded_segments"] == ["boom"]
|
||
assert ac.messages is not None # the turn assembled; only the segment is gone
|
||
|
||
async def test_phase_b_builder_failure_degrades_its_segment_only(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
"""The prefix-dependent phase is isolated the same way: a Curator that
|
||
raises loses its segment and is named, and the turn still assembles on
|
||
the prefix and the raw history."""
|
||
|
||
class _Boom:
|
||
name = "curator-boom"
|
||
order = 60
|
||
needs_prefix = True
|
||
|
||
async def build(self, ctx):
|
||
raise RuntimeError("curator down")
|
||
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
eng._phase_b = [*eng._phase_b, _Boom()]
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert ac.metadata["degraded_segments"] == ["curator-boom"]
|
||
assert ac.messages is not None
|
||
|
||
async def test_single_skill_source_failure_isolated(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
"""SkillForgeRouter's _safe_search swallows per-source exceptions;
|
||
assemble still returns an AssembledContext."""
|
||
|
||
class _Failing:
|
||
name = "broken"
|
||
weight = 1.0
|
||
|
||
async def search(self, q, h, k):
|
||
raise RuntimeError("source dead")
|
||
|
||
good_hits = [
|
||
RouterHit(
|
||
qualified_id="local/x",
|
||
name="x",
|
||
content="",
|
||
score=0.5,
|
||
)
|
||
]
|
||
eng = _engine(
|
||
builder,
|
||
router=SkillForgeRouter([_Failing(), _StubSource("local", hits=good_hits)]),
|
||
backend=_StubBackend(),
|
||
)
|
||
ac = await eng.assemble("s", [], _budget(), turn=_turn())
|
||
assert "local/x" in ac.metadata["injected_skill_ids"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Turn fields passthrough
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestTurnPassthrough:
|
||
async def test_channel_chat_id_propagate_to_builder(
|
||
self,
|
||
builder: ContextBuilder,
|
||
) -> None:
|
||
eng = _engine(builder, router=SkillForgeRouter([]), backend=_StubBackend())
|
||
ac = await eng.assemble(
|
||
"s",
|
||
[],
|
||
_budget(),
|
||
turn=_turn("hello", channel="slack", chat_id="C123"),
|
||
)
|
||
joined = "\n".join(str(m.get("content")) for m in ac.messages)
|
||
assert "slack" in joined
|
||
assert "C123" in joined
|
||
|
||
|
||
# ── consecutive-assistant coalescing (2b deliver_text support) ──
|
||
|
||
|
||
def test_coalesce_assistant_merges_adjacent_plain_only():
|
||
from raven.context_engine.assembler import _coalesce_assistant
|
||
|
||
# The ack ("on it") + a verbatim deliver_text answer land as two adjacent
|
||
# assistant messages; they merge into one so providers that reject
|
||
# consecutive same-role messages do not choke on the next turn.
|
||
history = [
|
||
{"role": "user", "content": "research X"},
|
||
{"role": "assistant", "content": "on it"},
|
||
{"role": "assistant", "content": "FULL REPORT"},
|
||
]
|
||
out = _coalesce_assistant(history)
|
||
assert [m["role"] for m in out] == ["user", "assistant"]
|
||
assert out[-1]["content"] == "on it\n\nFULL REPORT"
|
||
|
||
|
||
def test_coalesce_assistant_preserves_tool_call_adjacency():
|
||
from raven.context_engine.assembler import _coalesce_assistant
|
||
|
||
# An assistant carrying tool_calls is never merged — its tool result follows
|
||
# it, so merging would break tool-call adjacency.
|
||
history = [
|
||
{"role": "assistant", "content": "", "tool_calls": [{"id": "t1"}]},
|
||
{"role": "tool", "tool_call_id": "t1", "content": "res"},
|
||
{"role": "assistant", "content": "done"},
|
||
]
|
||
assert _coalesce_assistant(history) == history
|
||
|
||
|
||
def test_coalesce_assistant_ignores_non_adjacent():
|
||
from raven.context_engine.assembler import _coalesce_assistant
|
||
|
||
history = [
|
||
{"role": "assistant", "content": "a"},
|
||
{"role": "user", "content": "u"},
|
||
{"role": "assistant", "content": "b"},
|
||
]
|
||
assert _coalesce_assistant(history) == history
|
||
|
||
|
||
def test_coalesce_assistant_skips_when_merged_in_carries_reasoning():
|
||
from raven.context_engine.assembler import _coalesce_assistant
|
||
|
||
# The merged-in message carries reasoning_content — merging would silently
|
||
# drop it (contra the reasoning-field history projection), so skip the merge.
|
||
history = [
|
||
{"role": "assistant", "content": "a"},
|
||
{"role": "assistant", "content": "b", "reasoning_content": "why"},
|
||
]
|
||
assert _coalesce_assistant(history) == history
|