Raven-1/tests/test_simulation_cards.py
tzteyang ad2f054dd4
feat(*): add an experimental Curator that cultivates harness-of-harnesses workers (#802)
## Summary

Adds `experimental/`, a first version of worker RSI: a Curator that
shapes a
Raven worker's harness from the task, the materials handed to it and
feedback,
the way a new employee is trained.

The worker is a harness-of-harnesses. A root Raven harness faces the
user and
calls child harnesses, each a full Raven agent hosted over ACP, through
the
nodes of its playbooks. Every harness has the same four strategy facets
(memory, planning, capability, action). The Curator reads the actual
harnesses
and generates code and config on those facets at both levels: the root
candidate sets the playbooks and writes per-node requirements, each
child is
curated against the requirements of its nodes, and the set is checked on
copies and activated together.

Layout:
- `curator/`: staged generation (understand, select, design, implement,
repair), two-level composition, harness contracts, and `raven_adapter/`,
  the only layer that touches a worker's Raven runtime
- `analyst/`: turns an evaluator's words and execution records into
  observable behavior requirements
- `iteration/`: the generic loop (onboarding curation, then trial,
review and
  curation each round) and a CLI for a human evaluator
- `simulation/`: a simulated travel agency that runs the loop, plus one
  showcase case (`simulation/cases/s0925c/`: case notes, the exported
  transcript split by phase, and the round 1 and round 3 decks)
- `docs/design.md` (structure, curation flow, composition sequence, the
Raven
  connection) and `docs/rsi-iteration.md` (the loop and the Analyst)

Key decisions:
- No change under `raven/`, and `raven/` does not import
`experimental/`.
Generated artifacts land on Raven's existing extension points. The few
Raven
internals the adapter reads are listed in `docs/design.md` section 5.4.
- The Curator explores a read-only source snapshot; the caller names the
evaluation side to withhold from it, so the generic layers name no
scenario.
- The single-layer owner analysis is kept only to reproduce the showcase
case
  and is marked for removal; the two-layer Analyst is the default.
- The two decks are `.pptx` files of about 230 KB each. They pass
  `check-large-files`; flagging them in case they count as report assets
under AGENTS.md section 7, in which case they can move out of git behind
a
  link.
- One follow-up for Raven 0.2.2: playbooks in prompt and rounds modes
ship no
  fixed nodes, so node requirements are read from dag playbooks only.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

On the branch rebased onto the latest `main`:

- `uv run pytest tests/test_harness_curator_*.py tests/test_analyst_*.py
tests/test_iteration_*.py tests/test_simulation_*.py -q`: 368 passed
- `uv run pytest -m integration
tests/integration/test_harness_curator_*.py --deselect
tests/integration/test_harness_curator_real_llm.py -q`
  (offline, stub providers): 57 passed
- `uv run pytest -q` (whole suite, with the host proxy variables unset
and
`PYTHONTZPATH` set): 26692 passed, 2 failed. One was an order-dependent
test
  of this PR and is fixed here; the other,

`tests/test_subagent_node_runtime.py::test_what_cannot_be_read_names_nothing`,
  fails only because the machine runs as root and is unrelated.
- `uv run ruff check` and `uv run ruff format --check` on the touched
files:
  clean
- `scripts/check_large_files.py origin/main..HEAD`,
  `scripts/check_source_language.py origin/main..HEAD`,
  `scripts/check_commit_messages.py origin/main..HEAD` and
  `npx commitlint --from origin/main --to HEAD`: all exit 0

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

No user-visible change for Raven: `experimental/` is not imported by
`raven/` and is not packaged in the wheel (`packages = ["raven"]`).
`CONTEXT.md` gains one glossary entry. The Curator's exploration offers
a
shell only under an OS sandbox executor. Rollback is a revert of the
squash
commit; nothing else depends on `experimental/`.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Yuqi Yang <yiqiyang524@gmail.com>
Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-09-26 21:00:58 +08:00

78 lines
3.5 KiB
Python

"""Drill cards with drawn values: every playing meets new facts, yet each card keeps the path it was written for."""
import random
import pytest
from experimental.simulation.cards import draw, split
from experimental.simulation.reference import Rules
from experimental.simulation.scenario import BUNDLED, Scenario
from experimental.simulation.traveller import Traveller
from raven.contracts.llm_provider import LLMResponse
TRAVEL = BUNDLED / "travel_agency"
DRAWS = 300
class Provider:
def __init__(self):
self.requests = []
async def chat_with_retry(self, **kwargs):
self.requests.append(kwargs)
return LLMResponse(content="Hello")
def chosen(rules: Rules, trip) -> tuple[str, int]:
"""The product the SOP's selection matrix leads to (S3.1, S3.3): by nightly budget, then down while it does not fit."""
order = list(rules.products)
nightly = trip.budget / trip.persons / trip.nights
tier = 2 if nightly > 2000 else 1 if nightly > 500 else 0
while tier >= 0:
product = order[tier]
expected = rules.expected(product, trip)
if rules.products[product].base <= trip.nights and expected and expected.total <= trip.budget:
return product, tier
tier -= 1
raise AssertionError(f"no product fits {trip}")
def test_every_card_draws_fresh_facts_but_keeps_its_product_season_and_budget_fit():
scenario = Scenario.load(TRAVEL)
rules = Rules.load(scenario)
tiers = {}
for persona in scenario.personas:
played = [persona.play(random.Random(f"7:{persona.name}:{count}")) for count in range(DRAWS)]
assert all(card.trip and "{" not in card.text and card.trip.phone in card.text for card in played)
assert all(f"{card.trip.start[0]}" in card.text and str(card.trip.budget) in card.text for card in played)
assert len({(card.trip.start, card.trip.phone, card.trip.budget) for card in played}) > DRAWS * 0.9
assert len({rules.season(card.trip.start) for card in played}) == 1
assert len({card.trip.persons for card in played}) == 1
tiers[persona.name] = {chosen(rules, card.trip)[1] for card in played}
assert tiers == {"family": {0}, "premium": {2}, "professional": {1}, "returning": {0}, "student": {0}}
def test_one_seed_draws_the_same_facts_and_a_card_without_values_plays_as_written():
values, body = split("---\nvalues:\n who: [Ann, Bo]\n n: {from: 1, to: 9}\n---\n{who} has {n}.\n")
first, again = (draw("x", values, body, random.Random("s")) for _ in range(2))
assert first == again and first.trip is None and "{" not in first.text
assert split("Plain card.") == ({}, "Plain card.")
assert draw("plain", {}, "Keep {braces}.", random.Random(1)).text == "Keep {braces}."
trip = {"start": {"from": "10-30", "to": "10-30"}, "nights": 3}
with pytest.raises(ValueError, match="phone"):
draw("x", trip, "", random.Random(1))
async def test_the_traveller_plays_its_card_afresh_each_conversation_and_one_seed_repeats_the_rounds():
scenario = Scenario.load(TRAVEL)
student = next(persona for persona in scenario.personas if persona.name == "student")
traveller = Traveller(student, Provider(), seed=3)
await traveller.speak([])
first = traveller.card
await traveller.speak([])
assert traveller.card != first and traveller.played == 2
again = Traveller(student, Provider(), seed=3)
await again.speak([])
assert again.card == first
assert first.trip.end == (first.trip.start[0], first.trip.start[1] + 3)