Skip to content

The platform for continuously improving AI agents.

45.0 KB
Raw Blame
import io
import json
import uuid
import zipfile
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from datetime import timedelta

import pytest
from django.db import close_old_connections
from django.utils import timezone
from factories import make_project, make_research_campaign, make_user
from jsonschema import Draft202012Validator

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    Dataset,
    FinetuningJob,
    ResearchAgent,
    TrainingCampaign,
    TrainingTrial,
)
from overbae.services import (
    execution_mandates,
    experiment_checkpoints,
    experiment_engine,
    research,
    research_acceptance,
    research_agent,
    research_experiments,
    research_team,
    research_tools,
    research_workspace,
)
from overbae.services.datasets import land, pipeline_packages
from overbae.services.research_contract import (
    Artifact,
    Delegate,
    EvidenceReference,
    Workspace,
)

pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]


@pytest.fixture(autouse=True)
def checkpoint_schema():
    with experiment_checkpoints.store() as store:
        store.setup()


def assignment(*, project=None, user=None, context_roots=(), sealed_cells=(), **budget):
    if project is None:
        user = user or make_user()
        project = make_project(member=user)
    else:
        assert user is not None
    roots = list(context_roots)
    work = research.create(
        project,
        user=user,
        request_key="investigate",
        objective="Diagnose a training failure",
        task={"deliverable": "A reproducible diagnosis"},
        context_roots=roots,
        sealed_cells=[str(key) for key in sealed_cells],
        execution_mandate=execution_mandates.admission(roots=roots),
        budget={"max_agents": 16, **budget},
    )
    return work, work.agents.get(parent__isnull=True)


def test_stale_cancelled_reconciliation_preserves_resumed_agent():
    work, lead = assignment()
    research_agent.reconcile(research.stop(work))
    work.refresh_from_db()
    assert work.state == "cancelled"
    research.resume(work, request_key="retry", instructions="Continue the investigation")
    research_agent.reconcile(work)
    lead.refresh_from_db()
    work.refresh_from_db()
    assert work.state == "running"
    assert lead.state == "ready"
    assert lead.completed_at is None


def test_empty_deployment_lookup_is_retained_in_agent_history():
    _, lead = assignment()
    action = research.claim(lead, "inspect-serving", "serving", {"operation": "inspect"})
    result = research_tools.invoke(action)
    assert result == []
    research.complete(action, result, cost=0)
    lead.messages = research_agent.messages(lead) + [
        {
            "role": "assistant",
            "content": "Checking existing deployments",
            "tool_calls": [
                {
                    "id": action.request_key,
                    "type": "function",
                    "function": {"name": "serving", "arguments": json.dumps(action.arguments)},
                }
            ],
        }
    ]
    lead.save(update_fields=["messages"])
    history = research_agent.messages(lead)
    returned = next(item for item in history if item.get("tool_call_id") == action.request_key)
    assert json.loads(returned["content"])["data"]["items"] == []
    assert json.loads(returned["content"])["receipt"] == str(action.pk)
    action.refresh_from_db()
    assert action.result == []
    assert lead.actions.filter(request_key=action.request_key).count() == 1


@pytest.mark.parametrize("new_evidence", [False, True])
def test_report_rewrites_require_new_evidence_after_two_saved_versions(new_evidence):
    _, lead = assignment()
    request = Workspace(operation="write", path="report.md", text="Measured result")
    for index in range(2):
        prior = research.claim(lead, f"write-{index}", "workspace", request.model_dump())
        research_workspace.validate_write_progress(prior, request)
        research.complete(prior, {"path": "report.md", "sha256": str(index) * 64}, cost=0)
        model = research.claim(lead, f"model-{index}", "model", {})
        research.complete(model, {}, cost=0.01)
    if new_evidence:
        review = research.claim(lead, "review", "review", {"operation": "report"})
        research.complete(
            review, {"accepted": False, "reason": "Incorrect metric attribution"}, cost=0
        )
    current = research.claim(lead, "rewrite", "workspace", request.model_dump())
    if new_evidence:
        research_workspace.validate_write_progress(current, request)
    else:
        with pytest.raises(InputValidationError, match="dated cost snapshot"):
            research_workspace.execute(current, request)


def test_reported_token_estimates_release_reservations_without_claiming_an_invoice():
    work, lead = assignment()
    action = research.claim(lead, "direct-call", "model", {}, reservation=1)
    research.complete(action, {}, usage={"cost_estimate": {"estimated_usd": 0.12}})
    assert float(research.allowance(work)["committed_usd"]) == pytest.approx(0.12)
    costs = research.recorded_costs(work)
    assert costs["estimated_action_usd"] == pytest.approx(0.12)
    assert costs["all_in_actual_usd"] is None
    assert action.cost_usd is None


def test_invalid_native_arguments_return_fields_without_echoing_payloads():
    _, lead = assignment()
    action = research.claim(
        lead,
        "bad-job-lookup",
        "platform",
        {"name": "get_job", "arguments": {"job": "private-payload"}},
    )
    assert research_agent.run_tools(lead)
    action.refresh_from_db()
    assert action.state == "failed"
    assert {item["field"] for item in action.result["details"]} == {
        "arguments.kind",
        "arguments.id",
        "arguments.job",
    }
    assert "attached schema" in action.result["recovery"]
    assert "private-payload" not in json.dumps(action.result)


@pytest.mark.parametrize("stop_condition", ["deadline", "revoked", "cancelled"])
def test_model_call_limit_preserves_admitted_training_until_authority_ends(stop_condition):
    work, lead = assignment(max_model_calls=1)
    previous = research.claim(lead, "previous-model", "model", {}, 1)
    research.complete(previous, {}, cost=1)
    reservation = research.claim(lead, "admitted-training", "campaign_allocation", {}, 9)
    research.complete(reservation, {"admitted": True})
    campaign = make_research_campaign(work, "admitted-training")
    denied = research.claim(lead, "next-model", "model", {}, 2)
    assert denied.state == "denied"
    assert denied.result["reason"] == "model_call_limit"
    lead.state, lead.result = "exhausted", denied.result
    lead.save(update_fields=["state", "result"])
    research_agent.exhaust(lead)
    campaign.refresh_from_db()
    assert campaign.state == "running"
    assert research.claim(lead, "new-work", "workspace", {}, 0).state == "denied"

    work.refresh_from_db()
    if stop_condition == "deadline":
        work.deadline = timezone.now() - timedelta(seconds=1)
        work.save(update_fields=["deadline"])
    elif stop_condition == "revoked":
        work.created_by.is_active = False
        work.created_by.save(update_fields=["is_active"])
    else:
        work = research.stop(work)
    research_agent.reconcile(work)
    campaign.refresh_from_db()
    assert campaign.state == "cancelled"


def test_a_stopped_run_is_released_while_its_campaign_still_winds_down():
    work, _ = assignment()
    campaign = make_research_campaign(work, "on-a-gpu")
    research_agent.reconcile(research.stop(work))
    work.refresh_from_db()
    campaign.refresh_from_db()
    # The campaign closes on its own record; the user does not wait for the provider.
    assert (work.state, campaign.state) == ("cancelled", "cancelled")


def test_stop_wins_over_a_model_admission_rejected_during_shutdown():
    work, lead = assignment()
    research.stop(work)
    work.refresh_from_db()
    denied = research.claim(lead, "late-model", "model", {}, 1)
    assert denied.state == "denied"
    lead.state, lead.result = "exhausted", denied.result
    research_agent.exhaust(lead)
    work.refresh_from_db()
    assert work.state == "cancelled"
    assert work.result.get("reason") != "admission_denied"


@pytest.mark.parametrize("job_state", ["running", "succeeded", "failed"])
def test_a_running_campaign_keeps_its_run_waiting_until_the_campaign_ends(job_state):
    work, _ = assignment()
    campaign = make_research_campaign(work, "training")
    dataset = Dataset.objects.create(project=work.project, name="Training")
    job = FinetuningJob.objects.create(
        project=work.project, dataset=dataset, base_model="Cloudflare/clef-flash", status=job_state
    )
    TrainingTrial.objects.create(campaign=campaign, index=1, job=job)
    assert research_tools.pending_work(work)
    TrainingCampaign.objects.filter(pk=campaign.pk).update(
        state="completed", completed_at=timezone.now()
    )
    assert not research_tools.pending_work(work)


def specialist(lead, name="data-audit", **kwargs):
    return research.delegate(
        lead,
        Delegate(
            request_key=name,
            role="data",
            responsibility=name,
            task="Check input semantics",
            deliverables=[
                {"name": "audit", "kind": "report", "acceptance": "Cite the inspected input"}
            ],
            **kwargs,
        ),
    )


def invoke(agent, tool, arguments, key=None):
    action = research.claim(agent, key or str(uuid.uuid4()), tool, arguments)
    result = research_tools.invoke(action)
    research.complete(action, result, cost=0)
    return action


def submit(agent, *, outcome="completed"):
    retention = research.claim(agent, str(uuid.uuid4()), "retain_artifact", {})
    artifact = research.retain(
        retention,
        Artifact(path="audit.md", title="Input audit", kind="report"),
        b"The inspected input contract is retained for the integration test.\n",
    )
    research.complete(retention, research.artifact_record(artifact), cost=0)
    action = invoke(
        agent,
        "finish",
        {
            "outcome": outcome,
            "summary": "Input audit retained",
            "artifacts": [str(artifact.pk)],
            "deliverables": [{"name": "audit", "artifacts": [str(artifact.pk)]}],
        },
    )
    agent.refresh_from_db()
    return action, artifact


def review(lead, child, handoff, decision="accepted"):
    inspection = invoke(lead, "inspect_action", {"action": str(handoff.pk)})
    return invoke(
        lead,
        "review_handoff",
        {
            "agent": str(child.pk),
            "handoff": str(handoff.pk),
            "decision": decision,
            "rationale": "Inspected retained deliverable and its evidence",
            "evidence": [{"kind": "action", "id": str(inspection.pk)}],
        },
    )


def test_independent_work_runs_but_dependent_work_waits_for_accepted_bytes():
    work, lead = assignment()
    data = specialist(lead)
    independent = specialist(lead, "runtime-diagnosis")
    consumer = specialist(lead, "recipe", depends_on=[data.pk])
    assert research_agent.lease(independent.pk) is not None
    assert research_agent.lease(consumer.pk) is None
    assert not consumer.actions.exists()
    handoff, artifact = submit(data)
    assert research_agent.lease(consumer.pk) is None
    review(lead, data, handoff)
    leased = research_agent.lease(consumer.pk)
    assert leased is not None
    assert str(artifact.pk) in research_agent.packet(leased)["input_artifacts"]
    assert research_team.dependencies(leased)[0]["handoff"] == str(handoff.pk)
    assert (
        next(item for item in research.describe(work)["agents"] if item["id"] == str(data.pk))[
            "role"
        ]
        == "data"
    )


def test_revision_requires_new_handoff_and_preserves_spending():
    work, lead = assignment()
    data = specialist(lead)
    consumer = specialist(lead, "recipe", depends_on=[data.pk])
    cost = research.claim(data, "spent", "workspace_lease", {}, reservation=0.4)
    research.complete(cost, {"closed": True}, cost=0.2)
    stale = research.claim(data, "stale-proposal", "remember", {"text": "Superseded"})
    first, _ = submit(data)
    review(lead, data, first, "needs_revision")
    data.refresh_from_db()
    assert data.state == "ready"
    stale.refresh_from_db()
    assert stale.state == "denied"
    assert research_agent.run_tools(data) is False
    assert research_agent.lease(consumer.pk) is None
    assert research.allowance(work)["committed_usd"] == "0.20000000"
    second, _ = submit(data)
    assert second.pk != first.pk
    review(lead, data, second)
    assert research_agent.lease(consumer.pk) is not None
    assert research_team.dependencies(consumer)[0]["handoff"] == str(second.pk)


def test_same_responsibility_and_changed_retry_cannot_create_competing_workers():
    _, lead = assignment()
    child = specialist(lead)
    assert specialist(lead).pk == child.pk
    with pytest.raises(InputValidationError, match="responsibility"):
        research.delegate(
            lead,
            Delegate(
                request_key="different",
                role="training",
                responsibility="data-audit",
                task="Duplicate",
                deliverables=[
                    {"name": "recipe", "kind": "training_plan", "acceptance": "Executable"}
                ],
            ),
        )
    with pytest.raises(InputValidationError, match="different task"):
        specialist(lead, artifacts=[uuid.uuid4()])
    submit(child)
    with pytest.raises(InputValidationError, match="responsibility"):
        research.delegate(
            lead,
            Delegate(
                request_key="third",
                role="data",
                responsibility="data-audit",
                task="Duplicate",
                deliverables=[{"name": "audit", "kind": "report", "acceptance": "Evidence"}],
            ),
        )


@pytest.mark.parametrize(
    "tool,arguments",
    [
        ("training", {"operation": "create"}),
        ("serving", {"operation": "deploy"}),
        ("retain_pipeline", {"describe": True}),
        (
            "manage_agent",
            {"agent": str(uuid.uuid4()), "operation": "stop", "reason": "Not authorized"},
        ),
    ],
)
def test_specialist_cannot_mutate_shared_work_even_with_unadvertised_tool(tool, arguments):
    _, lead = assignment()
    child = specialist(lead)
    with pytest.raises(InputValidationError, match="research lead"):
        invoke(child, tool, arguments)
    description = invoke(child, "training", {"operation": "create", "describe": True})
    assert "properties" in description.result


@pytest.mark.parametrize(
    ("tool", "arguments", "allowed"),
    [
        ("benchmark", {"operation": "run"}, False),
        ("benchmark", {"operation": "stop"}, False),
        ("benchmark", {"operation": "inspect"}, True),
        ("training", {"operation": "create", "describe": True}, True),
        ("training", {"operation": "create"}, False),
        ("platform", {"name": "get_model_catalog"}, True),
        ("platform", {"name": "create_data_partition", "describe": True}, True),
        ("platform", {"name": "create_data_partition"}, False),
    ],
)
def test_helper_advertised_operations_match_native_authority(tool, arguments, allowed):
    _, lead = assignment()
    child = specialist(lead)
    schema = next(
        item["function"]["parameters"]
        for item in research_agent.definitions(child)
        if item["function"]["name"] == tool
    )
    assert Draft202012Validator(schema).is_valid(arguments) is allowed
    assert research_team.permits(child, tool, arguments) is allowed
    if allowed and tool == "training" and arguments["operation"] == "runtime":
        with pytest.raises(InputValidationError, match="campaign does not belong"):
            invoke(child, tool, arguments)
    elif allowed:
        assert invoke(child, tool, arguments).state == "completed"
    else:
        with pytest.raises(InputValidationError, match="research lead"):
            invoke(child, tool, arguments)


def test_cross_assignment_dependencies_and_evidence_are_rejected():
    _, lead = assignment()
    _, other = assignment()
    foreign = specialist(other)
    with pytest.raises(InputValidationError, match="Dependencies"):
        specialist(lead, depends_on=[foreign.pk])
    with pytest.raises(InputValidationError, match="Dependencies"):
        specialist(lead, depends_on=[lead.pk])
    child = specialist(lead)
    handoff, _ = submit(child)
    foreign_action = invoke(other, "remember", {"text": "Foreign observation"})
    with pytest.raises(InputValidationError, match="Evidence must cite"):
        invoke(
            lead,
            "review_handoff",
            {
                "agent": str(child.pk),
                "handoff": str(handoff.pk),
                "decision": "accepted",
                "rationale": "Unrelated evidence",
                "evidence": [{"kind": "action", "id": str(foreign_action.pk)}],
            },
        )
    assert not research_team.ready(specialist(lead, "consumer", depends_on=[child.pk]))


def test_unread_messages_survive_page_limit_and_cannot_be_skipped():
    _, lead = assignment()
    child = specialist(lead)
    sent = [
        invoke(lead, "message_agent", {"agent": str(child.pk), "message": str(index)})
        for index in range(25)
    ]
    page = invoke(child, "inbox", {"operation": "read"}).result
    ids = [item["event"] for item in page["messages"]]
    assert ids == [action.result["event"] for action in sent[:20]]
    last = sent[-1].result["event"]
    skipped = invoke(child, "inbox", {"operation": "acknowledge", "events": [last]}).result
    assert skipped["acknowledged_through"] == 0 and len(skipped["unread"]) == 25
    invoke(child, "inbox", {"operation": "acknowledge", "events": ids})
    remaining = invoke(child, "inbox", {"operation": "read"}).result
    assert [item["message"] for item in remaining["messages"]] == [
        str(index) for index in range(20, 25)
    ]
    replay = invoke(child, "inbox", {"operation": "acknowledge", "events": ids}).result
    assert replay["acknowledged_through"] == ids[-1]
    foreign = invoke(lead, "inbox", {"operation": "acknowledge", "events": ids}).result
    assert foreign == {"acknowledged_through": 0, "unread": []}


def test_recipient_finishing_during_a_turn_returns_the_next_coordination_action():
    _, lead = assignment()
    child = specialist(lead)
    request = {"agent": str(child.pk), "message": "Review the new observation"}
    handoff, _ = submit(child)
    late = invoke(lead, "message_agent", request)
    assert late.result["delivery"] == "not_delivered"
    assert late.result["recipient"]["coordination"] == {
        "message": False,
        "next_tool": "review_handoff",
        "handoff": str(handoff.pk),
    }
    assert not lead.assignment.events.filter(
        kind="agent_message", payload__recipient=str(child.pk)
    ).exists()
    review(lead, child, handoff)
    child.refresh_from_db()
    assert research_team.record(child)["coordination"]["next_tool"] == "delegate"
    assert child.state == "completed"
    child.assignment.state = "completed"
    child.assignment.save(update_fields=["state"])
    assert research_team.record(child)["coordination"] == {"message": False, "next_tool": None}


def test_stopping_helper_fences_a_late_model_response_and_pending_tools():
    _, lead = assignment()
    child = specialist(lead)
    leased = research_agent.lease(child.pk)
    fence = leased.lease
    model = research_agent.admit_model(
        leased,
        fence,
        "inflight-model",
        {},
        0.1,
        source_scope=research_agent.model_source_scope(leased.assignment),
    )
    pending = research.claim(child, "pending-write", "remember", {"text": "Late change"})
    stopped = invoke(
        lead,
        "manage_agent",
        {"agent": str(child.pk), "operation": "stop", "reason": "Duplicate work"},
    )
    child.refresh_from_db()
    assert child.state == "cancelled"
    assert stopped.result["state"] == "cancelled"
    assert child.lease is None
    assert not research_team.accepts_response(child, fence)
    research_agent.accept_model_response(
        model,
        fence,
        [],
        "Late response",
        [{"id": "late-tool", "function": {"name": "remember", "arguments": '{"text":"Revived"}'}}],
        {},
    )
    model.refresh_from_db()
    child.refresh_from_db()
    assert model.result["accepted"] is False
    assert model.cost_usd is None
    assert not child.actions.filter(request_key="late-tool").exists()
    assert child.state == "cancelled"
    assert child.messages == []
    with pytest.raises(InputValidationError, match="execution authority"):
        research_tools.invoke(pending)
    child.refresh_from_db()
    assert child.notes == ""
    invoke(
        lead,
        "manage_agent",
        {"agent": str(child.pk), "operation": "resume", "reason": "Investigate new evidence"},
    )
    child.refresh_from_db()
    assert research_agent.run_tools(child) is False
    assert "Investigate new evidence" in child.notes
    with pytest.raises(InputValidationError, match="already settled"):
        research_tools.invoke(pending)


def test_resume_waits_for_inflight_effects_to_settle():
    _, lead = assignment()
    child = specialist(lead)
    pending = research.claim(child, "inflight", "remember", {"text": "Old observation"})
    assert [action.pk for action in research_team.next_tools(child)] == [pending.pk]
    invoke(
        lead,
        "manage_agent",
        {"agent": str(child.pk), "operation": "stop", "reason": "Replan"},
    )
    with pytest.raises(InputValidationError, match="in-flight"):
        invoke(
            lead,
            "manage_agent",
            {"agent": str(child.pk), "operation": "resume", "reason": "New work"},
        )


def test_reviewed_negative_finding_remains_an_immutable_dependency():
    _, lead = assignment()
    child = specialist(lead)
    consumer = specialist(lead, "recipe", depends_on=[child.pk])
    handoff, _ = submit(child, outcome="unmet")
    accepted = review(lead, child, handoff)
    replay = invoke(lead, "review_handoff", accepted.arguments)
    assert replay.result["event"] == accepted.result["event"]
    with pytest.raises(InputValidationError, match="different review"):
        invoke(lead, "review_handoff", {**accepted.arguments, "decision": "rejected"})
    with pytest.raises(InputValidationError, match="immutable"):
        invoke(
            lead,
            "manage_agent",
            {"agent": str(child.pk), "operation": "resume", "reason": "New evidence"},
        )
    assert research_team.ready(consumer)
    assert research_team.dependencies(consumer)[0]["handoff"] == str(handoff.pk)


def test_completion_requires_the_declared_deliverable_and_lead_review():
    _, lead = assignment()
    child = specialist(lead)
    undelivered = invoke(child, "finish", {"outcome": "completed", "summary": "Done"}).result
    assert undelivered["accepted"] is False and "each declared" in undelivered["reason"]
    handoff, artifact = submit(child)
    evaluator = lead.children.get(role="evaluation")
    invoke(
        lead,
        "manage_agent",
        {
            "agent": str(evaluator.pk),
            "operation": "stop",
            "reason": "Checking the handoff boundary",
        },
    )
    held = invoke(
        lead,
        "finish",
        {"outcome": "completed", "summary": "Done", "artifacts": [str(artifact.pk)]},
    )
    assert held.result["accepted"] is False
    lead.refresh_from_db()
    assert lead.state not in research.TERMINAL
    review(lead, child, handoff, "rejected")
    assert research_team.unsettled_handoffs(lead.assignment) == []


def test_work_order_and_revision_feedback_survive_history_reset():
    _, lead = assignment()
    child = specialist(lead)
    handoff, _ = submit(child)
    review(lead, child, handoff, "needs_revision")
    child.refresh_from_db()
    child.messages = []
    packet = research_agent.messages(child)
    current = json.loads(packet[-1]["content"])
    assert current["role"] == "data"
    assert current["work_order"]["deliverables"][0]["name"] == "audit"
    assert (
        next(member for member in current["observations"]["team"] if member["id"] == str(child.pk))[
            "handoff"
        ]["state"]
        == "needs_revision"
    )
    assert "label quality" in packet[0]["content"]
    for _ in range(3):
        child.messages = research_agent.messages(child) + [
            {"role": "user", "content": "Continue inspecting evidence"}
        ]
        child.save(update_fields=["messages"])
    current = research_agent.messages(child)
    # Unchanged state is not sent again; the work order stays in the first packet.
    assert current == child.messages
    assert json.loads(current[1]["content"])["work_order"]["deliverables"][0]["name"] == "audit"


@pytest.mark.parametrize("state", ["waiting", "completed"])
def test_stop_during_tool_execution_cannot_be_overwritten_at_commit(state):
    _, lead = assignment()
    child = specialist(lead)
    inflight = research_agent.lease(child.pk)
    invoke(
        lead,
        "manage_agent",
        {"agent": str(child.pk), "operation": "stop", "reason": "No longer needed"},
    )
    with pytest.raises(InputValidationError, match="authority changed"):
        research_team.transition(
            inflight, fence=inflight.lease, state=state, result={"handoff": "late"}
        )
    child.refresh_from_db()
    assert child.state == "cancelled"
    assert "handoff" not in child.result


def test_abandoned_revision_withdraws_handoff_without_releasing_dependencies():
    _, lead = assignment()
    child = specialist(lead)
    consumer = specialist(lead, "recipe", depends_on=[child.pk])
    handoff, _ = submit(child)
    review(lead, child, handoff, "needs_revision")
    invoke(
        lead,
        "manage_agent",
        {
            "agent": str(child.pk),
            "operation": "stop",
            "reason": "Alternative evidence is sufficient",
        },
    )
    child.refresh_from_db()
    assert research_team.handoff_status(child)["state"] == "withdrawn"
    assert research_team.unsettled_handoffs(lead.assignment) == []
    assert not research_team.ready(consumer)
    assert research_agent.lease(consumer.pk) is None


@pytest.mark.django_db(transaction=True)
def test_concurrent_duplicate_delegations_create_one_specialist():
    _, lead = assignment()

    def create():
        close_old_connections()
        try:
            return specialist(ResearchAgent.objects.get(pk=lead.pk)).pk
        finally:
            close_old_connections()

    with ThreadPoolExecutor(max_workers=2) as pool:
        ids = list(pool.map(lambda _: create(), range(2)))
    assert ids[0] == ids[1]
    assert lead.children.filter(work_order__responsibility="data-audit").count() == 1


def test_a_handoff_that_names_a_receipt_as_a_reviewed_artifact_goes_back_to_its_author():
    work, lead = assignment()
    evaluator = lead.children.get(role="evaluation")
    check = invoke(evaluator, "inspect_action", {"action": str(uuid.uuid4())})
    returned = invoke(
        evaluator,
        "finish",
        {
            "outcome": "completed",
            "summary": "Checked the run",
            # A call's receipt, where an artifact another agent retained belongs.
            "reviewed_artifacts": [str(check.pk)],
            "verification_verdict": "passed",
            "deliverables": [
                {
                    "name": "verification",
                    "findings": [
                        {
                            "kind": "observation",
                            "statement": "The run was inspected.",
                            "evidence": [{"kind": "action", "id": str(check.pk)}],
                            "limitations": [],
                        }
                    ],
                }
            ],
        },
    )
    # The handoff is not accepted, and its author is told which identifier is not an artifact.
    assert returned.state == "completed" and returned.result["accepted"] is False
    assert str(check.pk) in returned.result["reason"]
    evaluator.refresh_from_db()
    assert evaluator.state not in {"completed", "unmet", "blocked"}


@pytest.mark.parametrize("max_agents", [2, 3])
def test_core_evaluator_must_verify_the_exact_candidate_before_success(max_agents, fake_llm):
    work, lead = assignment(max_agents=max_agents)
    evaluator = lead.children.get(role="evaluation")
    assert work.agents.count() == 2
    assert evaluator.work_order["responsibility"] == "independent-evaluation"
    retention = research.claim(lead, "candidate", "retain_artifact", {})
    candidate = research.retain(
        retention,
        Artifact(path="result.md", title="Candidate", kind="report"),
        b"Candidate for independent review\n",
    )
    research.complete(retention, research.artifact_record(candidate), cost=0)
    with pytest.raises(InputValidationError, match="independent evaluation"):
        research_team.require_verification(work, [candidate])
    check = invoke(evaluator, "inspect_action", {"action": str(retention.pk)})
    verification = invoke(
        evaluator,
        "finish",
        {
            "outcome": "completed",
            "summary": "Checked candidate identity",
            "reviewed_artifacts": [str(candidate.pk)],
            "verification_verdict": "passed",
            "deliverables": [
                {
                    "name": "verification",
                    "findings": [
                        {
                            "kind": "observation",
                            "statement": "The candidate is retained at the reported hash; content quality is not established by this contract test.",
                            "evidence": [
                                {"kind": "action", "id": str(check.pk)},
                                {"kind": "artifact", "id": str(candidate.pk)},
                            ],
                            "limitations": [
                                "This verifies the handoff contract, not research quality."
                            ],
                        }
                    ],
                }
            ],
        },
    )
    with pytest.raises(InputValidationError, match="independent evaluation"):
        research_team.require_verification(work, [candidate])
    assert research_acceptance.facts(work)["independent_verifications"] == []
    with pytest.raises(InputValidationError, match="Review the current handoff"):
        invoke(
            lead,
            "manage_agent",
            {"agent": str(evaluator.pk), "operation": "resume", "reason": "A new assessment"},
        )
    consumer = specialist(lead, "consumer", depends_on=[evaluator.pk]) if max_agents == 3 else None
    review(lead, evaluator, verification)
    research_team.require_verification(work, [candidate])

    evaluator.refresh_from_db()
    assert research_team.record(evaluator)["coordination"] == {
        "message": False,
        "next_tool": "manage_agent",
        "operation": "resume",
    }
    resume = {
        "agent": str(evaluator.pk),
        "operation": "resume",
        "reason": "Verify the repaired candidate",
    }
    schema = next(
        item["function"]["parameters"]
        for item in research_agent.definitions(lead)
        if item["function"]["name"] == "manage_agent"
    )
    assert Draft202012Validator(schema).is_valid(resume)
    changed = research.claim(lead, "revised-candidate", "retain_artifact", {})
    revised = research.retain(
        changed, Artifact(path="result.md", title="Revision", kind="report"), b"Changed candidate\n"
    )
    research.complete(changed, research.artifact_record(revised), cost=0)
    with pytest.raises(InputValidationError, match="independent evaluation"):
        research_team.require_verification(work, [revised])
    invoke(
        lead,
        "manage_agent",
        resume,
    )
    evaluator.refresh_from_db()
    if consumer:
        consumer.refresh_from_db()
        assert research_team.ready(consumer)
        assert research_team.dependencies(consumer)[0]["handoff"] == str(verification.pk)
    second_check = invoke(evaluator, "inspect_action", {"action": str(changed.pk)})
    args = {**deepcopy(verification.arguments), "reviewed_artifacts": [str(revised.pk)]}
    args["deliverables"][0]["findings"][0]["evidence"] = [
        {"kind": "action", "id": str(second_check.pk)}
    ]
    next_review = invoke(evaluator, "finish", args)
    # The reviewed candidate is bound to the grounded observation with its exact bytes.
    assert {"kind": "artifact", "id": str(revised.pk), "sha256": revised.sha256} in (
        next_review.result["deliverables"][0]["findings"][0]["evidence"]
    )
    review(lead, evaluator, next_review)
    research_team.require_verification(work, [revised])
    assert work.agents.count() == max_agents
    if consumer:
        consumer.refresh_from_db()
        assert research_team.dependencies(consumer)[0]["handoff"] == str(verification.pk)
    verification.refresh_from_db()
    assert verification.result["verification"]["artifacts"][0]["id"] == str(candidate.pk)


@pytest.mark.parametrize(
    "outcome,verdict", [("unmet", "passed"), ("completed", "failed"), ("completed", "insufficient")]
)
def test_accepting_a_negative_or_unmet_assessment_cannot_qualify_a_candidate(outcome, verdict):
    work, lead = assignment()
    evaluator = lead.children.get(role="evaluation")
    retention = research.claim(lead, "candidate", "retain_artifact", {})
    candidate = research.retain(
        retention, Artifact(path="result.md", title="Candidate", kind="report"), b"Candidate\n"
    )
    research.complete(retention, research.artifact_record(candidate), cost=0)
    assessment = invoke(
        evaluator,
        "finish",
        {
            "outcome": outcome,
            "summary": "Candidate remains unqualified",
            "reviewed_artifacts": [str(candidate.pk)],
            "verification_verdict": verdict,
            "deliverables": []
            if outcome == "unmet"
            else [
                {
                    "name": "verification",
                    "findings": [
                        {
                            "kind": "observation",
                            "statement": "The required acceptance evidence is absent.",
                            "evidence": [{"kind": "artifact", "id": str(candidate.pk)}],
                        }
                    ],
                }
            ],
        },
    )
    review(lead, evaluator, assessment)
    with pytest.raises(InputValidationError, match="independent evaluation"):
        research_team.require_verification(work, [candidate])


@pytest.mark.parametrize("verdict", ["failed", "insufficient", "passed"])
def test_evaluator_can_report_a_failed_campaign_without_qualifying_it(verdict):
    work, lead = assignment()
    evaluator = lead.children.get(role="evaluation")
    campaign = make_research_campaign(work, "failed-training", state="failed")
    args = {
        "outcome": "unmet",
        "summary": "Training failed before qualification",
        "reviewed_campaigns": [str(campaign.pk)],
        "verification_verdict": verdict,
    }
    if verdict == "passed":
        # A handoff that cannot be accepted as written goes back to its author.
        returned = invoke(evaluator, "finish", args).result
        assert returned["accepted"] is False
        assert "passed verdict requires a completed campaign" in returned["reason"]
    else:
        assessment = invoke(evaluator, "finish", args)
        assert assessment.result["verification"]["campaigns"][0]["state"] == "failed"
        review(lead, evaluator, assessment)
        campaign.refresh_from_db()
        assert campaign.state == "failed"


def test_native_dataset_access_preserves_project_scope_and_specialist_authority():
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Native input")
    cell = Cell.objects.create(
        dataset=dataset, position=0, title="Source", state="ok", fingerprint="a" * 64
    )
    dataset.active = cell
    dataset.save(update_fields=["active"])
    work, lead = assignment(
        project=project, user=user, context_roots=[f"cell:{cell.pk}"], sealed_cells=()
    )
    changed = invoke(
        lead,
        "platform",
        {
            "name": "update_dataset",
            "arguments": {"dataset": str(dataset.pk), "name": "Renamed through native services"},
        },
    )
    dataset.refresh_from_db()
    assert dataset.name == changed.result["name"] == "Renamed through native services"
    evaluator = lead.children.get(role="evaluation")
    inspected = invoke(
        evaluator,
        "platform",
        {"name": "inspect_dataset_workbench", "arguments": {"dataset": str(dataset.pk)}},
    )
    assert inspected.result["dataset"] == str(dataset.pk)
    models = invoke(evaluator, "platform", {"name": "get_model_catalog"})
    assert models.result["models"]
    with pytest.raises(InputValidationError, match="research lead"):
        invoke(
            evaluator,
            "platform",
            {
                "name": "update_dataset",
                "arguments": {"dataset": str(dataset.pk), "name": "Unauthorized"},
            },
        )
    _, other = assignment()
    with pytest.raises(InputValidationError, match="this project"):
        invoke(
            other,
            "platform",
            {"name": "inspect_dataset_workbench", "arguments": {"dataset": str(dataset.pk)}},
        )


@pytest.mark.parametrize("controlled_flow", [False, True])
def test_native_pipeline_uses_approved_immutable_input_when_dataset_active_changes(controlled_flow):
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Pinned transformation")
    land.land_rows(dataset, [{"text": "approved input"}])
    dataset.refresh_from_db()
    source = dataset.active_cell
    work, lead = assignment(
        project=project, user=user, context_roots=[f"cell:{source.pk}"], sealed_cells=()
    )
    controller = work
    if controlled_flow:
        experiment = research_experiments.create(
            work.project,
            work.created_by,
            name="Transform",
            objective=work.specification["objective"],
            cells=[source.pk],
            request_key="transform",
        )
        action = research.claim(lead, "dispatch", "experiment", {"operation": "run"})
        work = experiment_engine.start(
            experiment,
            work.created_by,
            revision=1,
            request_key="transform",
            budget={},
            controller=action,
        )
        lead = work.agents.get(parent__isnull=True)
    dataset.active = Cell.objects.create(
        dataset=dataset, position=1, title="Unapproved revision", state="ok", fingerprint="c" * 64
    )
    dataset.save(update_fields=["active"])
    contract = invoke(lead, "retain_pipeline", {"describe": True}).result
    manifest = contract["manifest"]
    manifest["steps"] = [{"name": "Preserve", "entrypoint": "transform.py"}]
    bundle = io.BytesIO()
    with zipfile.ZipFile(bundle, "w") as archive:
        archive.writestr("manifest.json", json.dumps(manifest))
        archive.writestr("transform.py", contract["starter_script"])
    bundle.seek(0)
    package = pipeline_packages.save(work.project, work.created_by, bundle)
    saved = invoke(
        lead,
        "platform",
        {
            "name": "save_dataset_pipeline",
            "arguments": {"name": "Preserve", "package": str(package.pk)},
        },
    )
    submitted = invoke(
        lead,
        "platform",
        {
            "name": "run_dataset_pipeline",
            "arguments": {
                "dataset": str(dataset.pk),
                "pipeline": saved.result["pipeline"]["id"],
                "source_cell": str(source.pk),
                "source_fingerprint": source.fingerprint,
            },
        },
    )
    assert submitted.result["run"]["source_cell"] == str(source.pk)
    assert submitted.result["run"]["state"] == "queued"
    facts = research_acceptance.transformation_facts(controller)
    assert len(facts) == 1
    assert facts[0]["source"]["id"] == str(source.pk)
    assert facts[0]["output"] is None
    assert facts[0]["package"]["sha256"] == package.sha256
    assert facts[0]["entrypoints"][0]["content"] == contract["starter_script"]
    unrelated, _ = assignment()
    assert research_acceptance.transformation_facts(unrelated) == []


def toxicity_campaign(cells):
    return {
        "operation": "create",
        "arguments": {
            "task": "Classify request toxicity",
            "train_cell": str(cells[0].pk),
            "development_cell": str(cells[1].pk),
            "allowed_models": ["Cloudflare/clef-flash"],
            "budget": {
                "max_cost_usd": 3,
                "max_seconds": 1800,
                "max_trials": 2,
                "max_decisions": 4,
                "evaluation_reserve_usd": 1,
            },
            "metric": "/eval_loss",
            "direction": "minimize",
        },
    }


def test_evaluator_authored_model_cannot_escape_candidate_coverage():
    work, lead = assignment()
    evaluator = lead.children.get(role="evaluation")
    retention = research.claim(evaluator, "model-candidate", "retain_artifact", {})
    model = research.retain(
        retention,
        Artifact(path="model.bin", title="Candidate", kind="model"),
        b"contract test artifact",
    )
    research.complete(retention, research.artifact_record(model), cost=0)
    with pytest.raises(InputValidationError, match="independent evaluation"):
        research_team.require_verification(work, [model])


def test_unfinished_execution_cannot_be_returned_as_a_verified_finding():
    _, lead = assignment()
    child = specialist(lead)
    pending = research.claim(child, "running-script", "workspace", {"operation": "python"})
    with pytest.raises(InputValidationError, match="pending execution"):
        research_team.references(
            child.assignment,
            [EvidenceReference(kind="action", id=pending.pk)],
        )


@pytest.mark.parametrize("boundary", ["deadline", "retries", "calls"])
def test_provider_recovery_respects_original_limits(boundary):
    work, lead = assignment()
    work.state = "blocked"
    work.result = {
        "reason": "model_provider_unavailable",
        "retry_at": (timezone.now() - timedelta(seconds=1)).isoformat(),
    }
    lead.state = "blocked"
    lead.result = {"provider_probe": True}
    lead.save()
    if boundary == "deadline":
        work.deadline = timezone.now() - timedelta(seconds=1)
    elif boundary == "retries":
        for _ in range(3):
            research.event(work, "provider_recovery", {})
    else:
        work.specification["budget"]["max_model_calls"] = 0
    work.save()
    research_agent.recover_provider(work)
    work.refresh_from_db()
    assert work.state == "blocked"
    assert not lead.actions.exists()


def test_spent_historical_money_limit_does_not_prevent_resume_or_new_work():
    work, lead = assignment()
    work.specification["budget"]["max_cost_usd"] = 1
    charge = research.claim(lead, "prior-work", "workspace_lease", {}, 3)
    research.complete(charge, {"retained": True}, cost=3)
    work.state = "exhausted"
    work.result = {"reason": "budget_limit"}
    work.completed_at = timezone.now()
    work.save()
    work.agents.update(state="exhausted", completed_at=work.completed_at)
    resumed = research.resume(
        work, request_key="continue", instructions="Continue the investigation"
    )
    lead.refresh_from_db()
    admitted = research.claim(lead, "next-work", "workspace_lease", {}, 5)
    assert resumed.state == "running"
    assert admitted.state == "pending"
    charge.refresh_from_db()
    assert charge.cost_usd == 3
    assert research.recorded_costs(resumed)["all_in_actual_usd"] is None


def test_a_call_that_can_mean_one_teammate_or_handoff_need_not_name_it():
    work, lead = assignment()
    evaluator = lead.children.get(role="evaluation")
    # The lead's only teammate, and a specialist's lead, are who an unnamed call addresses.
    sent = invoke(lead, "message_agent", {"message": "Please review the export"})
    assert sent.result["recipient"] == str(evaluator.pk)
    replied = invoke(evaluator, "message_agent", {"message": "Reviewed"})
    assert replied.result["recipient"] == str(lead.pk)
    assert invoke(lead, "inspect_agent", {}).result["agent"] == str(evaluator.pk)
    child = specialist(lead)
    with pytest.raises(InputValidationError, match="another agent"):
        invoke(lead, "message_agent", {"message": "Ambiguous with two teammates"})
    handoff, _ = submit(child)
    reviewed = invoke(
        lead, "review_handoff", {"decision": "accepted", "rationale": "Read the audit"}
    )
    assert reviewed.result["handoff"] == str(handoff.pk)
    assert reviewed.result["evidence"] == [
        {
            "kind": "action",
            "id": str(handoff.pk),
            "state": "completed",
            "fingerprint": reviewed.result["evidence"][0]["fingerprint"],
        }
    ]
    assert research_team.handoff_status(child)["state"] == "accepted"
    # With nothing waiting the call answers; it does not fail.
    idle = invoke(lead, "review_handoff", {"decision": "accepted", "rationale": "Nothing waits"})
    assert idle.result["executed"] is False and idle.result["awaiting"] == []