Skip to content

The platform for continuously improving AI agents.

47.9 KB
Raw Blame
from copy import deepcopy
from functools import cache
from uuid import UUID

from django.db import transaction
from django.db.models import Case, F, IntegerField, Value, When
from django.utils import timezone
from pydantic import ValidationError

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    Project,
    ResearchAction,
    ResearchAssignment,
    ResearchExperiment,
)
from overbae.services import (
    context_graph,
    experiment_execution,
    experiment_operator,
    experiment_partitions,
    experiment_preflight,
    experiment_stages,
    research,
    research_context_authorship,
    research_evidence,
    research_metrics,
    research_requests,
    research_team,
)
from overbae.services.datasets import use
from overbae.services.experiment_catalog import PORTS
from overbae.services.experiment_compiler import references
from overbae.services.experiment_contract import Document
from overbae.services.experiment_settings import Mapping
from overbae.services.research_contract import TOOLS, Artifact
from overbae.services.research_errors import ToolStateError


def validate_document(project, document):
    from overbae.services import (
        experiment_assets,
    )  # Asset definitions are admitted before graph compilation.

    require_shape(document)
    context_graph.require_storable(document)
    document = inline_models(document)
    for node in document.get("nodes", []):
        kind, config = node.get("kind"), node.get("config", {})
        selection = config.get("model")
        if (
            isinstance(selection, dict)
            and selection.get("asset")
            and not list(references(selection))
        ):
            asset = experiment_assets.get(project, selection["asset"], "candidate")
            if selection.get("fingerprint") != asset.fingerprint:
                raise InputValidationError("Pin the exact retained candidate fingerprint")
            selection.pop("_checkpoint", None)
            if asset.definition["kind"] == "checkpoint":
                selection["_checkpoint"] = asset.definition["checkpoint"]
        if kind in {"component", "suite"} or kind == "model" and config.get("asset"):
            if not config.get("asset") and not node.get("operation"):
                continue
            config.pop("_checkpoint", None)
            if list(references(config)):
                if kind == "component":
                    raise InputValidationError(
                        "Component interfaces must be pinned before connecting ports"
                    )
                continue
            asset = experiment_assets.get(
                project, config.get("asset"), "candidate" if kind == "model" else kind
            )
            if kind == "model" and asset.definition["kind"] == "checkpoint":
                config["_checkpoint"] = asset.definition["checkpoint"]
            if kind == "component":
                config["ports"] = {
                    direction: {
                        name: port["type"] for name, port in asset.definition[direction].items()
                    }
                    for direction in ("inputs", "outputs")
                }
            if config.get("fingerprint") != asset.fingerprint:
                raise InputValidationError("Pin the exact retained asset fingerprint")
    try:
        parsed = Document.model_validate(document)
    except ValidationError as exc:
        raise InputValidationError(
            "Check node identities, compatible ports and acyclic connections"
        ) from exc
    for node in parsed.nodes:
        declared = set(references(node.model_dump(mode="json")))
        if declared - parsed.parameters.keys():
            raise InputValidationError("Declare every referenced flow parameter")
        if node.kind == "data":
            if list(references(node.config)):
                continue
            try:
                identifier = UUID(str(node.config.get("cell", "")))
            except ValueError as exc:
                raise InputValidationError(
                    "Data nodes require cell as a local version UUID string, not a cell descriptor."
                ) from exc
            cell = Cell.objects.filter(pk=identifier, dataset__project=project, state="ok").first()
            # The cell identifies the version; an omitted fingerprint is recorded from it.
            if (
                cell is None
                or not cell.fingerprint
                or node.config.get("fingerprint", cell.fingerprint) != cell.fingerprint
            ):
                raise InputValidationError(
                    "Select an available local dataset version and its exact fingerprint"
                )
            if node.config.get("dataset", str(cell.dataset_id)) != str(cell.dataset_id):
                raise InputValidationError("The data node names a different dataset from its cell")
            node.config = {
                **node.config,
                "dataset": str(cell.dataset_id),
                "fingerprint": cell.fingerprint,
            }
        if node.operation and not list(references(node.operation.arguments)):
            try:
                TOOLS[node.operation.tool].request.model_validate(node.operation.arguments)
            except ValidationError as exc:
                details = "; ".join(
                    f"operation.arguments.{'.'.join(map(str, item['loc']))}: {item['msg']}"
                    for item in exc.errors(include_input=False, include_url=False)[:8]
                )
                raise InputValidationError(
                    f"Node {node.id} ({node.operation.tool}) has invalid native arguments: {details}. "
                    f"Expected envelope fields: {', '.join(TOOLS[node.operation.tool].request.model_fields)}. "
                    "Use the same complete payload as a direct tool call inside operation.arguments."
                ) from exc
    return parsed.model_dump(mode="json")


def require_shape(document):
    """The asset and model passes read the raw JSON before the typed check; they need this much."""

    def records(value):
        return isinstance(value, list) and all(isinstance(item, dict) for item in value)

    def texts(record, *keys):
        return all(isinstance(record.get(key), str) for key in keys)

    if not (
        isinstance(document, dict)
        and records(document.get("nodes", []))
        and records(document.get("edges", []))
        and isinstance(document.get("outputs", {}), dict)
        and records(list(document.get("outputs", {}).values()))
        and all(texts(output, "node") for output in document.get("outputs", {}).values())
        and all(
            texts(edge, "source", "output", "target", "input") for edge in document.get("edges", [])
        )
        and all(
            texts(node, "id", "kind")
            and isinstance(node.get("config", {}), dict)
            and isinstance(node.get("operation") or {}, dict)
            and isinstance((node.get("operation") or {}).get("arguments", {}), dict)
            for node in document.get("nodes", [])
        )
    ):
        raise InputValidationError(
            "Check node identities, compatible ports and acyclic connections"
        )


def inline_models(document):
    # Constant model references belong to their consumers. Preserve old revisions
    # verbatim; saving a revision canonicalizes them without rewriting run evidence.
    document = deepcopy(document)
    sources = {n["id"]: n for n in document.get("nodes", []) if n["kind"] == "model"}
    nodes = {n["id"]: n for n in document.get("nodes", []) if n["id"] not in sources}
    for edge in document.get("edges", []):
        if edge["target"] in sources:
            raise InputValidationError("Model references cannot consume workflow outputs")
        if edge["source"] not in sources:
            continue
        if edge["input"] != "model" or edge["output"] != "model":
            raise InputValidationError("Model references bind the consumer's model input")
        node = nodes.get(edge["target"])
        if node is None:
            raise InputValidationError(f"Connection target {edge['target']} does not exist")
        config = node.setdefault("config", {})
        selection = sources[edge["source"]].get("config", {})
        if "model" in config and config["model"] != selection:
            raise InputValidationError("Select the model once on its consuming node")
        config["model"] = deepcopy(selection)
    if any(output["node"] in sources for output in document.get("outputs", {}).values()):
        raise InputValidationError("Declare a processing output, not a constant model reference")
    document["nodes"] = list(nodes.values())
    document["edges"] = [e for e in document.get("edges", []) if e["source"] not in sources]
    for node in document["nodes"]:
        selection = node.get("config", {}).get("model", {})
        operation = node.get("operation") or {}
        arguments = operation.get("arguments", {})
        if (
            node["kind"] == "train"
            and operation.get("tool") == "training"
            and arguments.get("operation") == "create"
        ):
            native = arguments.get("arguments", {})
            # Equal copies are executor-owned bindings, not additional constraints.
            if (
                isinstance(selection, dict)
                and isinstance(native, dict)
                and selection.get("model")
                and native.get("allowed_models") == [selection["model"]]
            ):
                native.pop("allowed_models")
    return document


def sources(project):
    cells = (
        Cell.objects.filter(dataset__project=project, state="ok")
        .exclude(fingerprint="")
        .select_related("dataset")
        .annotate(
            selected=Case(
                When(pk=F("dataset__active_id"), then=Value(1)),
                default=Value(0),
                output_field=IntegerField(),
            )
        )
        .order_by("dataset_id", "-selected", "-position")
        .distinct("dataset_id")
    )
    return [
        {
            "id": c.pk,
            "dataset": c.dataset_id,
            "name": c.dataset.name,
            "title": c.title,
            "version": c.position,
            "fingerprint": c.fingerprint,
            "available": True,
            "reason": "",
        }
        for c in sorted(cells, key=lambda item: item.dataset.name.lower())
    ]


@transaction.atomic
def create(project, user, *, name, objective, cells, request_key, document=None):
    Project.objects.select_for_update().get(pk=project.pk)
    identifiers = list(dict.fromkeys(str(c) for c in cells))
    request = {"name": name, "objective": objective, "cells": identifiers}
    if document is not None:
        # Absent for a plain send, so fingerprints retained before definitions still match.
        request["document"] = document
    identity = context_graph.fingerprint(request)
    existing = ResearchExperiment.objects.filter(project=project, request_key=request_key).first()
    if existing:
        if existing.fingerprint != identity:
            raise InputValidationError("This request key belongs to a different experiment")
        return existing
    sources = list(
        Cell.objects.filter(
            pk__in=identifiers, dataset__project=project, state="ok"
        ).select_related("dataset")
    )
    if len(sources) != len(identifiers):
        raise InputValidationError("Select existing readable datasets from this project")
    experiment = ResearchExperiment.objects.create(
        project=project,
        created_by=user,
        name=name,
        objective=objective,
        request_key=request_key,
        fingerprint=identity,
    )
    sources.sort(key=lambda c: identifiers.index(str(c.pk)))
    nodes = [
        {
            "id": f"data_{i}",
            "kind": "data",
            "title": cell.dataset.name,
            "position": {"x": 80, "y": 80 + i * 270},
            "config": {
                "cell": str(cell.pk),
                "fingerprint": cell.fingerprint,
                "dataset": str(cell.dataset_id),
                "version": cell.position,
            },
        }
        for i, cell in enumerate(sources)
    ]
    revise(
        experiment,
        expected_version=0,
        document={"nodes": nodes, "edges": []},
        request_key="initial",
        note="Dataset inputs",
    )
    experiment.refresh_from_db()
    return experiment


@transaction.atomic
def delete(experiment):
    experiment = ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
    # A hidden experiment has no stop control, so its runs stop here.
    for run in ResearchAssignment.objects.filter(experiment_revision__experiment=experiment):
        research.stop(run)
    experiment.deleted_at = timezone.now()
    experiment.save(update_fields=["deleted_at", "updated_at"])


def scientific_document(document):
    return {
        **document,
        "nodes": [
            {key: value for key, value in node.items() if key not in {"title", "position", "notes"}}
            for node in document["nodes"]
        ],
    }


@transaction.atomic
def revise(experiment, *, expected_version, document, request_key, note="", agent=None):
    experiment = ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
    if agent is not None:
        agent = research_team.current_turn(agent)
    document = validate_document(experiment.project, document)
    fingerprint = context_graph.fingerprint(document)
    existing = experiment.revisions.filter(request_key=request_key).first()
    if existing:
        if existing.fingerprint != fingerprint or existing.note != note:
            raise InputValidationError("This revision key already saved a different document")
        return existing
    if agent is not None:
        research_team.admit_mutation(agent)
    current = current_revision(agent.assignment).number if agent else experiment.version
    if current != expected_version:
        raise InputValidationError(
            f"The experiment changed: expected revision {expected_version}, current revision {current}. "
            "Inspect the current document before saving."
        )
    if experiment.scientific_lock or agent and research_evidence.can_read_final(agent.assignment):
        previous = experiment.revisions.get(number=current).document
        if scientific_document(document) != scientific_document(previous):
            raise InputValidationError(
                "Final-result observers may retain reporting notes, not change executable definitions"
            )
    for node in document["nodes"]:
        if node["kind"] == "data" and not list(references(node["config"])):
            use.freeze(Cell.objects.get(pk=node["config"]["cell"]))
    revision = experiment.revisions.create(
        number=experiment.version + 1,
        document=document,
        fingerprint=fingerprint,
        request_key=request_key,
        note=note,
        agent=agent,
    )
    experiment.version = revision.number
    experiment.save(update_fields=["version", "updated_at"])
    return revision


@transaction.atomic
def start(
    experiment,
    user,
    *,
    revision,
    request_key,
    budget,
    instructions="",
    execution_mandate=None,
    cause=None,
    frozen_objective=None,
    event_sources=None,
):
    # Research tools dispatch flow edits through this document service.
    from overbae.services.research_tools import source_cell

    experiment = ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
    from overbae.services import execution_mandates  # Admission shares research contracts.

    key = f"experiment:{experiment.pk}:{request_key}"
    previous = ResearchAssignment.objects.filter(
        project=experiment.project, request_key=key
    ).first()
    if previous:
        request = deepcopy(previous.specification)
        request["budget"] = budget
        request["task"] = {**request["task"], "revision": revision, "instructions": instructions}
        if cause:
            request["task"]["trigger"] = cause
        if event_sources is not None:
            request["task"]["event_sources"] = event_sources
        return research.initialize(
            experiment.project, user=user, execution_mandate=execution_mandate, **request
        )
    version = experiment.revisions.filter(number=revision).first()
    if version is None:
        raise InputValidationError("Select a saved experiment revision")
    roots = [
        f"cell:{n['config']['cell']}" for n in version.document["nodes"] if n["kind"] == "data"
    ]
    for source in event_sources or []:
        cell = Cell.objects.filter(
            pk=source["id"],
            dataset__project=experiment.project,
            fingerprint=source["fingerprint"],
            state="ok",
        ).first()
        if cell is None:
            raise InputValidationError("The retained event source is unavailable")
        execution_mandates.require_cell(execution_mandate, cell, project=experiment.project)
        roots.append(f"cell:{cell.pk}")
    roots = list(dict.fromkeys(roots))
    request = {
        "request_key": key,
        "objective": frozen_objective if frozen_objective is not None else experiment.objective,
        "task": {
            "experiment": str(experiment.pk),
            "revision": version.number,
            "instructions": instructions,
            "deliverable": "Fulfil the user's request for this saved experiment; an edit-only request does not authorize execution",
        },
        "context_roots": roots,
        "constraints": {"local_platform_data_only": True},
        "budget": budget,
        "execution_mandate": execution_mandate
        or execution_mandates.admission(
            roots=roots,
            sources=execution_mandates.flow_sources(
                experiment.project, version.document, allow_unbound=True
            ),
            experiment=experiment.pk,
            explicit={"local_platform_data_only": True},
        ),
    }
    if experiment.scientific_lock:
        request["execution_mandate"] = execution_mandates.normalize(
            {
                **request["execution_mandate"],
                "authority": "observe",
                "families": ["read", "author"],
            }
        )
    if cause:
        request["task"]["trigger"] = cause
    if event_sources is not None:
        request["task"]["event_sources"] = event_sources
    previous = ResearchAssignment.objects.filter(
        project=experiment.project, request_key=key
    ).first()
    if (
        previous is None
        and ResearchAssignment.objects.filter(
            experiment_revision__experiment=experiment, execution__isnull=True
        )
        .exclude(state__in=research.TERMINAL)
        .exists()
    ):
        raise InputValidationError("This experiment already has an active run")
    assignment = research.initialize(experiment.project, user=user, **request)
    if experiment.scientific_lock and not assignment.result.get("selection_locked"):
        assignment.result = {
            **assignment.result,
            "selection_locked": experiment.scientific_lock["at"],
        }
        assignment.save(update_fields=["result"])
    for root in roots:
        identifier = root.split(":", 1)[1]
        # Attaching a holdout names it for a Qualify stage; reading its rows is checked there.
        source_cell(assignment, identifier, platform_reads=True)
    if assignment.experiment_revision_id is None:
        assignment.experiment_revision = version
        assignment.save(update_fields=["experiment_revision"])
    return assignment


def identity_config(node):
    config = {
        key: value
        for key, value in node["config"].items()
        if key not in experiment_partitions.ACCESS_PINS
    }
    if node["kind"] == "map" and config.get("bindings"):
        try:
            settings = Mapping.model_validate(config)
        except ValidationError:
            return config
        config = {
            key: value for key, value in config.items() if key not in {"keys", "labels", "bindings"}
        }
        config["bindings"] = sorted(zip(settings.keys, settings.bindings, strict=True))
        for key in ("recipe", "_definition"):
            if config.get(key):
                child = config[key]
                config[key] = {
                    **child,
                    "nodes": sorted(
                        [
                            {
                                "id": item["id"],
                                "kind": item["kind"],
                                "config": identity_config(item),
                                "operation": item.get("operation"),
                            }
                            for item in child["nodes"]
                        ],
                        key=lambda item: item["id"],
                    ),
                    "edges": sorted(
                        child["edges"],
                        key=lambda edge: (
                            edge["source"],
                            edge["output"],
                            edge["target"],
                            edge["input"],
                        ),
                    ),
                }
    return config


def node_identity(document, node_id):
    nodes = {n["id"]: n for n in document["nodes"]}

    @cache
    def identity(identifier):
        node = nodes[identifier]
        return context_graph.fingerprint(
            {
                "kind": node["kind"],
                "config": identity_config(node),
                "operation": node.get("operation"),
                "inputs": sorted(
                    (e["input"], e["output"], identity(e["source"]))
                    for e in document["edges"]
                    if e["target"] == identifier
                ),
            }
        )

    return identity(node_id)


def current_revision(assignment):
    initial = assignment.experiment_revision
    if initial is None:
        # An operator belongs to the experiment, not to one of its revisions.
        if experiment_operator.is_operator(assignment):
            return experiment_operator.experiment(assignment).revisions.order_by("-number").first()
        return None
    if hasattr(assignment, "execution"):
        return initial
    authored = initial.experiment.revisions.filter(agent__assignment=assignment)
    boundary = research_requests.boundary_of(assignment)
    if boundary is not None:
        # A request starts from the flow as it stands, with what the user changed on the
        # canvas since; once the lead has saved a change for it, work continues from that.
        authored = authored.filter(created_at__gte=boundary.created_at)
        return authored.order_by("-number").first() or initial.experiment.revisions.latest("number")
    authored = authored.order_by("-number").first()
    return authored if authored and authored.number > initial.number else initial


def action_state(action):
    return experiment_execution.observe(action)["state"]


def describe(experiment):
    revisions = list(experiment.revisions.order_by("-number"))
    source_ids = {
        node["config"]["cell"]
        for revision in revisions
        for node in revision.document["nodes"]
        if node["kind"] == "data" and isinstance(node["config"].get("cell"), str)
    }
    runs = (
        ResearchAssignment.objects.filter(experiment_revision__experiment=experiment)
        .select_related("experiment_revision", "project", "created_by", "execution__revision")
        .order_by("-created_at")
    )
    return {
        "id": str(experiment.pk),
        "project": str(experiment.project_id),
        "name": experiment.name,
        "objective": experiment.objective,
        "version": experiment.version,
        "document": revisions[0].document,
        "source_references": [
            {"cell": str(cell), "dataset": str(dataset)}
            for cell, dataset in Cell.objects.filter(
                pk__in=source_ids, dataset__project=experiment.project
            ).values_list("pk", "dataset_id")
        ],
        "node_identities": {
            n["id"]: node_identity(revisions[0].document, n["id"])
            for n in revisions[0].document["nodes"]
        },
        "ports": PORTS,
        "revisions": [
            {
                "id": str(r.pk),
                "number": r.number,
                "document": r.document,
                "node_identities": {
                    n["id"]: node_identity(r.document, n["id"]) for n in r.document["nodes"]
                },
                "fingerprint": r.fingerprint,
                "note": r.note,
                "agent": str(r.agent_id) if r.agent_id else None,
                "created_at": r.created_at.isoformat(),
            }
            for r in revisions
        ],
        "runs": [run_record(run) for run in runs],
    }


def run_progress(run):
    flow = (
        run
        if hasattr(run, "execution")
        else (
            ResearchAssignment.objects.filter(
                project=run.project,
                execution__isnull=False,
                specification__task__controller_assignment=str(run.pk),
            )
            .order_by("-created_at")
            .first()
        )
    )
    if run.state in research.TERMINAL or run.state == "stopping":
        phase = run.state
    elif flow is None:
        phase = "drafting"
    elif flow.state == "completed":
        phase = "verifying"
    elif flow.state in research.TERMINAL:
        phase = "repairing"
    else:
        phase = "executing"
    return {
        "phase": phase,
        "flow_run": str(flow.pk) if flow else None,
        "controller": run.specification.get("task", {}).get("controller_assignment"),
    }


def node_result(node):
    """What a node's operation returned, as one record. Serving returns its deployments as a
    list."""
    result = node.action.result if node.action_id else {}
    record = result if isinstance(result, dict) else {"records": result}
    return {**record, **({"error": node.error} if node.error else {})}


def execution_scopes(execution):
    scopes = list(
        execution.scopes.exclude(parent__isnull=True)
        .select_related("parent__scope", "execution__revision")
        .prefetch_related("nodes__action", "nodes__reused_from__execution")
        .order_by("index", "pk")
    )
    seen = {scope.pk for scope in scopes}
    pending = list(execution.nodes.filter(reused_from__isnull=False).select_related("reused_from"))
    visited = set()
    while pending:
        receipt = pending.pop()
        if receipt.pk in visited:
            continue
        visited.add(receipt.pk)
        if receipt.reused_from_id:
            pending.append(receipt.reused_from)
        for scope in receipt.scopes.select_related(
            "parent__scope", "execution__revision"
        ).prefetch_related("nodes__action", "nodes__reused_from__execution"):
            if scope.pk not in seen:
                scopes.append(scope)
                seen.add(scope.pk)
                pending.extend(scope.nodes.all())
    return scopes


def run_record(run):
    progress = run_progress(run)
    if hasattr(run, "execution"):
        execution = run.execution
        nodes = list(
            execution.nodes.filter(scope__parent__isnull=True)
            .select_related("action", "reused_from__execution")
            .order_by("attempt", "node")
        )
        latest = {node.node: node.pk for node in nodes}
        return {
            **progress,
            "id": str(run.pk),
            "request_key": run.request_key,
            "state": run.state,
            "revision": execution.revision.number,
            "current_revision": execution.revision.number,
            "created_at": run.created_at.isoformat(),
            "completed_at": run.completed_at.isoformat() if run.completed_at else None,
            "budget": research.allowance(run),
            "result": run.result,
            "execution": "flow",
            "parameters": execution.parameters,
            "document": execution.document,
            "scopes": [
                {
                    "id": str(scope.pk),
                    "parent": scope.parent.node,
                    "parent_receipt": str(scope.parent_id),
                    "parent_scope": str(scope.parent.scope_id),
                    "run": str(scope.execution_id),
                    "index": scope.index,
                    "variant": scope.variant_key,
                    "document": scope.document,
                    "parameters": scope.parameters,
                    "state": scope.state,
                    "error": scope.error,
                    "outputs": scope.outputs,
                    "nodes": [
                        {
                            "node": node.node,
                            "receipt": str(node.pk),
                            "action": str(node.action_id or node.pk),
                            "revision": scope.execution.revision.number,
                            "identity": node.identity,
                            "tool": node.action.tool if node.action_id else "flow",
                            "arguments": node.action.arguments if node.action_id else {},
                            "current": not any(
                                other.node == node.node and other.attempt > node.attempt
                                for other in scope.nodes.all()
                            ),
                            "reused_from": {
                                "run": str(node.reused_from.execution_id),
                                "node": node.reused_from.node,
                                "receipt": str(node.reused_from_id),
                            }
                            if node.reused_from_id
                            else None,
                            "attempt": node.attempt,
                            "state": node.state,
                            "outputs": node.outputs,
                            "result": node_result(node),
                            "started_at": node.started_at.isoformat() if node.started_at else None,
                            "completed_at": node.completed_at.isoformat()
                            if node.completed_at
                            else None,
                        }
                        for node in scope.nodes.all()
                    ],
                }
                for scope in execution_scopes(execution)
            ],
            "nodes": [
                {
                    "node": node.node,
                    "revision": execution.revision.number,
                    "action": str(node.action_id or node.pk),
                    "identity": node.identity,
                    "tool": node.action.tool if node.action_id else "flow",
                    "state": node.state,
                    "outputs": node.outputs,
                    "current": latest[node.node] == node.pk,
                    "arguments": node.action.arguments if node.action_id else {},
                    "result": node_result(node),
                    "started_at": node.started_at.isoformat() if node.started_at else None,
                    "completed_at": node.completed_at.isoformat() if node.completed_at else None,
                    "attempt": node.attempt,
                    "reused_from": {
                        "run": str(node.reused_from.execution_id),
                        "node": node.reused_from.node,
                        "receipt": str(node.reused_from_id),
                    }
                    if node.reused_from_id
                    else None,
                }
                for node in nodes
            ],
            "artifacts": [research.artifact_record(artifact) for artifact in run.artifacts.all()],
        }
    revision = current_revision(run)
    actions = (
        ResearchAction.objects.filter(agent__assignment=run, experiment_revision__isnull=False)
        .select_related("agent__assignment", "experiment_revision")
        .order_by("created_at")
    )
    return {
        **progress,
        "id": str(run.pk),
        "state": run.state,
        "revision": run.experiment_revision.number,
        "current_revision": revision.number,
        "created_at": run.created_at.isoformat(),
        "completed_at": run.completed_at.isoformat() if run.completed_at else None,
        "budget": research.allowance(run),
        "result": run.result,
        "metrics": research_metrics.request(run),
        "nodes": [
            {
                "node": a.experiment_node,
                "revision": a.experiment_revision.number,
                "action": str(a.pk),
                "identity": node_identity(a.experiment_revision.document, a.experiment_node),
                "tool": a.tool,
                "state": action_state(a),
                "outputs": experiment_execution.observe(a)["outputs"],
                "current": any(n["id"] == a.experiment_node for n in revision.document["nodes"])
                and node_identity(revision.document, a.experiment_node)
                == node_identity(a.experiment_revision.document, a.experiment_node),
                "arguments": a.arguments,
                "result": experiment_execution.execution_result(a),
                "started_at": a.started_at.isoformat() if a.started_at else None,
                "completed_at": a.completed_at.isoformat() if a.completed_at else None,
            }
            for a in actions
        ],
        "artifacts": [research.artifact_record(a) for a in run.artifacts.all()],
    }


def flow(project, revision, *, assignment=None, base=None):
    """A saved revision as an agent reads it: its stages, and whether it can run."""
    readiness = experiment_preflight.readiness(project, revision.document)
    document = (
        research_context_authorship.project_document(assignment, revision, base=base)
        if assignment
        else revision.document
    )
    return {
        "experiment": str(revision.experiment_id),
        "revision": revision.number,
        **experiment_stages.describe(document),
        "ready": readiness["ready"],
        "issues": research_context_authorship.project_issue_titles(
            revision.document, document, readiness["errors"]
        ),
    }


def admit_inputs(agent, base, document):
    """New data cannot silently widen the input authority a run was admitted with."""
    from overbae.services import research_tools  # Native tool execution uses this service.

    admitted = {
        node["config"]["cell"]
        for node in base["nodes"]
        if node["kind"] == "data" and not list(references(node["config"]))
    }
    partitioned = None
    for node in document["nodes"]:
        cell = node["config"].get("cell") if node["kind"] == "data" else None
        if cell is None or list(references(node["config"])) or cell in admitted:
            continue
        if partitioned is None:
            # A partition's source is named for its retained split, never read.
            partitioned = {
                item["source"]["cell"] for item in research_tools.input_partitions(agent.assignment)
            }
        if cell not in partitioned:
            # A data stage names a version; the stage that reads its rows is checked, so a
            # final holdout can be named for a Qualify stage.
            research_tools.source_cell(agent.assignment, cell, platform_reads=True)


def agent_operation(action, request):
    from overbae.services import (
        experiment_dispatch,  # Dispatch consumes this document service.
        experiment_plans,  # Run review validates saved definitions through this service.
        experiment_source,  # Source revisions use this document service.
    )

    agent = action.agent
    revision = current_revision(agent.assignment)
    if revision is None:
        raise InputValidationError("This research assignment has no experiment document")
    experiment = revision.experiment
    if request.operation == "plan":
        return research_context_authorship.project_action(
            agent.assignment,
            action,
            experiment_plans.resolve(
                experiment,
                revision=request.revision or revision.number,
                parameters=request.parameters,
                reuse_run=request.reuse_run,
                rerun_from=request.rerun_from,
            ),
        )
    if request.operation in {"source", "save_source", "preview"}:
        if request.operation == "source":
            return experiment_source.page(
                experiment_source.inspect(
                    experiment,
                    revision=request.revision or revision.number,
                    node=request.id,
                    assignment=agent.assignment,
                ),
                request.file,
                request.offset,
                request.limit,
            )
        if agent.parent_id:
            raise InputValidationError("Return proposed source edits to the research lead")
        if request.operation == "save_source":
            if research_evidence.can_read_final(agent.assignment):
                raise InputValidationError(
                    "Final-result observers cannot publish reusable source changes"
                )
            return experiment_source.page(
                experiment_source.save(
                    experiment,
                    agent.assignment.created_by,
                    expected_version=request.expected_version,
                    node=request.id,
                    files=request.files,
                    manifest=request.manifest,
                    request_key=str(action.pk),
                    agent=agent,
                )
            )
        return experiment_source.preview(
            experiment,
            agent.assignment.created_by,
            revision=request.revision or revision.number,
            node=request.id,
            step=request.step,
            parameters=request.parameters or None,
            preview_rows=request.preview_rows,
            request_key=str(action.pk),
            reuse_run=request.reuse_run,
            assignment=agent.assignment,
            agent=agent,
        )
    if request.operation == "inspect":
        if request.automation:
            from overbae.services import (
                research_triggers,  # Trigger admission imports experiment services.
            )

            return research_triggers.inspect(
                experiment,
                evidence_fire=request.evidence_fire,
                evidence_cursor=request.evidence_cursor,
                limit=request.page_size,
            )
        return {
            "id": str(experiment.pk),
            "name": experiment.name,
            "objective": experiment.objective,
            **flow(experiment.project, revision, assignment=agent.assignment),
            "run": run_record(agent.assignment),
            "flow_runs": experiment_dispatch.observations(agent.assignment, include_reports=True),
        }
    if request.operation == "run":
        if research_requests.construction_only(agent.assignment):
            return {
                "started": False,
                "revision": revision.number,
                "reason": research_requests.CANVAS_EXECUTION,
            }
        version = (
            experiment.revisions.filter(number=request.revision).first()
            if request.revision
            else revision
        )
        if version is None:
            raise InputValidationError("Select a saved experiment revision")
        readiness = experiment_preflight.readiness(experiment.project, version.document)
        if all(node["kind"] in experiment_stages.SOURCES for node in version.document["nodes"]):
            readiness = {
                "ready": False,
                "errors": ["The flow has no stage to execute; add one before running it."],
            }
        issues = readiness["errors"]
        details = {}
        if not issues:
            try:
                return experiment_dispatch.launch(action, request, version)
            except InputValidationError as refused:
                issues = [str(refused.detail)]
                if isinstance(refused, ToolStateError):
                    details = {"details": refused.details}
        # A flow that cannot be admitted is an answer about the flow, not a failed call.
        return research_context_authorship.project_action(
            agent.assignment,
            action,
            {
                "started": False,
                "revision": version.number,
                "ready": False,
                "issues": issues,
                **details,
            },
        )
    if agent.parent_id:
        raise InputValidationError("Return proposed edits to the research lead")
    replayed = experiment.revisions.filter(request_key=str(action.pk)).first()
    if replayed is not None:
        # A retried call is answered from the revision it was first applied to.
        revision = (
            experiment.revisions.filter(number__lt=replayed.number).order_by("-number").first()
        )
    if request.operation == "remove":
        document, identifier = experiment_stages.remove(revision.document, request.stages), None
    elif request.operation == "define":
        document, identifier = revision.document, None
        for index, stage in enumerate(request.flow):
            try:
                document, _ = experiment_stages.apply(experiment.project, document, stage)
            except InputValidationError as refused:
                # Nothing is saved from a definition one of whose stages cannot be written.
                raise InputValidationError(
                    f"flow[{index}] ({stage.id or stage.kind}): {refused.detail}"
                ) from refused
    else:
        document, identifier = experiment_stages.apply(
            experiment.project, revision.document, request
        )
    # Native tool execution uses this document service.

    document = validate_document(experiment.project, document)
    admit_inputs(agent, revision.document, document)
    unchanged = document == revision.document
    saved = (
        revision
        if unchanged and not experiment.revisions.filter(request_key=str(action.pk)).exists()
        else revise(
            experiment,
            expected_version=revision.number,
            document=document,
            request_key=str(action.pk),
            note=request.note,
            agent=agent,
        )
    )
    result = {
        **flow(experiment.project, saved, assignment=agent.assignment, base=revision),
        "fingerprint": saved.fingerprint,
        "previous_revision": revision.number,
    }
    if request.operation == "define" and request.run:
        if research_requests.construction_only(agent.assignment):
            return result | {"started": False, "reason": research_requests.CANVAS_EXECUTION}
        if not result["ready"]:
            return result | {"started": False}
        try:
            return result | experiment_dispatch.launch(action, request, saved)
        except InputValidationError as refused:
            details = {"details": refused.details} if isinstance(refused, ToolStateError) else {}
            return result | {
                "started": False,
                "ready": False,
                "issues": [str(refused.detail)],
                **details,
            }
    if identifier:
        earlier = {
            node["id"]: experiment_stages.stage(revision.document, node)
            for node in revision.document["nodes"]
        }
        after = next(item for item in result["stages"] if item["id"] == identifier)
        before = earlier.get(identifier, {})
        result |= {
            "stage": identifier,
            # What the saved stage now holds, so an edit is verified against the definition.
            "changed": experiment_stages.changes(
                {key: before.get(key) for key in experiment_stages.AUTHORED},
                {key: after.get(key) for key in experiment_stages.AUTHORED},
            )
            # A reservation the call made on another stage changes what that stage runs on.
            + [
                {"stage": other["id"], **change}
                for other in result["stages"]
                if other["id"] != identifier and other["id"] in earlier
                for change in experiment_stages.changes(
                    earlier[other["id"]].get("reserved"), other.get("reserved"), ("reserved",)
                )
            ],
        }
    return research_context_authorship.project_action(
        agent.assignment, action, result, base=revision
    )


def definition(assignment):
    """The current revision, retained as an artifact of the action that saved it. It is created
    on first use and then reused, so its author and its reviewer cite one identity."""
    revision = current_revision(assignment)
    if revision is None:
        raise InputValidationError("A definition deliverable requires a saved experiment")
    try:
        author = ResearchAction.objects.filter(
            pk=UUID(revision.request_key), agent__assignment=assignment, tool="experiment"
        ).first()
    except ValueError:
        author = None
    if author is None:
        raise InputValidationError("The current flow was not edited in this assignment")
    return research.retain(
        author,
        Artifact(
            path=f"experiment/revision-{revision.number}.json",
            title=f"Experiment revision {revision.number}",
            kind="code",
            metadata={"experiment_revision": str(revision.pk), "definition": revision.fingerprint},
        ),
        context_graph.canonical(revision.document).encode(),
    )


def require_definition(assignment, artifacts):
    current = definition(assignment)
    if all(artifact.pk != current.pk for artifact in artifacts):
        raise InputValidationError(
            f"Deliver the current flow definition, artifact {current.pk}; an earlier revision "
            "cannot stand in for it"
        )
    revision = current_revision(assignment)
    return {
        "artifact": str(current.pk),
        "sha256": current.sha256,
        "revision": revision.number,
        "before": experiment_stages.describe(assignment.experiment_revision.document),
        "after": experiment_stages.describe(revision.document),
        "validation": experiment_preflight.readiness(assignment.project, revision.document),
    }


def require_delivery(assignment, artifacts, delivery):
    """Retain the matching flow receipt when the request was fulfilled through a flow."""
    from overbae.services import experiment_dispatch  # Dispatch consumes this document service.

    if delivery == "definition":
        require_definition(assignment, artifacts)
        return
    # The reconciler retains a settled run's receipt; a finish that arrives first does it here.
    try:
        run = require_outputs(assignment)
    except InputValidationError:
        return None
    if run is None:
        return None
    experiment_dispatch.reconcile_run(assignment, run)
    return run


def output_delivery(assignment):
    # Dispatch imports the document service to admit executions.
    from overbae.services import experiment_dispatch

    return {
        "completed_runs": [
            experiment_dispatch.receipt_record(run)
            for run in experiment_dispatch.owned(assignment)
            .filter(state="completed")
            .order_by("created_at", "pk")
        ]
    }


def require_outputs(assignment):
    # Flow dispatch consumes the document service when admitting an agent's run.
    from overbae.services import experiment_dispatch

    revision = current_revision(assignment)
    if revision is None:
        return
    identities = {
        node["id"]: node_identity(revision.document, node["id"])
        for node in revision.document["nodes"]
    }
    for run in experiment_dispatch.owned(assignment).order_by("-created_at"):
        document = run.execution.revision.document
        if revision.document.get("outputs") != document.get("outputs") or revision.document.get(
            "parameters"
        ) != document.get("parameters"):
            continue
        if identities == {
            node["id"]: node_identity(document, node["id"]) for node in document["nodes"]
        }:
            if run.state == "completed":
                return run
            break
    raise InputValidationError(
        "Execute the current saved flow with experiment.run and retain all declared outputs "
        "before completing. An earlier revision or individual scratch actions cannot satisfy it."
    )