Skip to content

The platform for continuously improving AI agents.

37.8 KB
Raw Blame
"""Flow stages as an agent writes and reads them, compiled to and from document nodes.

A stage states its kind, where each input comes from and its settings. A saved node carries
more: an operation envelope, connections, declared flow outputs, a title and a canvas
position. All of that follows from the stage, so an agent authors none of it.
"""

from copy import deepcopy
from uuid import UUID

from overbae.core.errors import InputValidationError
from overbae.modal.model_registry import get_model_config_any_backend
from overbae.models import Cell
from overbae.services import (
    experiment_catalog,
    experiment_interfaces,
    experiment_partitions,
    research_services,
)
from overbae.services.experiment_catalog import COMPONENTS, resolved
from overbae.services.experiment_settings import (
    CONTROL_SETTINGS,
    Comparison,
    Condition,
    Investigation,
    Publication,
)
from overbae.services.mcp.contracts.finetuning import StartFinetuneInput
from overbae.services.research_contract import TOOLS


def named(contract):
    """A contract's field names as they are written in arguments."""
    return {info.alias or name for name, info in contract.model_fields.items()}


# The operation a stage of each kind runs unless its settings name another.
OPERATIONS = {
    "ingest": ("platform", "import_traces"),
    "trace_dataset": ("platform", "create_trace_dataset"),
    "check_data": ("platform", "check_data"),
    "export_data": ("platform", "export_data"),
    "inference": ("serving", "infer"),
    "verify_deployment": ("platform", "verify_deployment"),
    "performance": ("platform", "measure_serving"),
    "stop_deployment": ("serving", "stop"),
    "transform": ("platform", "prepare_dataset"),
    "split": ("platform", "create_data_partition"),
    "train": ("training", "create"),
    "predict": ("prediction", "run"),
    "evaluate": ("benchmark", "run"),
    "qualify": ("benchmark", "run"),
    "publish": ("serving", "deploy"),
    "validate": ("component", "validate"),
}
# Settings a kind keeps on the node itself rather than passing to its operation.
CONFIGURATION = {
    "data": {"cell"},
    "model": {"model", "asset", "fingerprint", "name", "instructions"},
    "suite": {"asset", "fingerprint"},
    "component": {"asset", "fingerprint", "ports"},
    "compare": named(Comparison),
    "condition": named(Condition),
    "research": named(Investigation),
    "publish": named(Publication),
    **{kind: named(contract) for kind, contract in CONTROL_SETTINGS.items()},
}
# Recorded from the bound cell; never authored.
DERIVED = {"dataset", "fingerprint", "version"}
SOURCES = {"data", "model", "suite"}
# Which partition a stage's data input reads when its source is named without an output.
PARTITION = {
    ("train", "data"): "train",
    ("evaluate", "data"): "development",
    ("predict", "data"): "development",
    ("qualify", "data"): "final",
}
# The serving request fields each operation reads. One request contract serves them all, so
# a stage offers only its own.
SERVING = {
    "deploy": {"execution_seconds", "ttl_seconds", "max_requests"},
    "infer": {"decisions", "messages", "max_tokens", "enable_thinking", "example"},
    "stop": set(),
}
SCRIPT = ("code", "timeout")
# What a stage call can change about a stage, reported back as the differences it made.
AUTHORED = ("title", "inputs", "settings", "notes")
# What a train stage passes to start_finetune for every run of its campaign.
RUN = ("hyperparameters", "monitoring", "execution_limits", "name", "use_case")
SPLIT = {
    "seed": 42,
    "fractions": {"train": 0.7, "development": 0.15, "final": 0.15},
    "group_by": [],
    "stratify_by": None,
    "holdouts": [],
}


def operation_of(kind, settings, inputs):
    """The (tool, operation) a stage runs, or ``None`` for a kind its node settles itself."""
    named = settings.get("operation")
    if named is None:
        if kind == "evaluate" and "predictions" in inputs:
            return ("score", "run")
        if kind == "transform" and "pipeline" in settings:
            return ("platform", "run_dataset_pipeline")
        if kind == "component" and settings.get("asset"):
            return ("component", "run")
        return OPERATIONS.get(kind)
    selected = tuple(str(named).split(".", 1))
    matching = [item for item in COMPONENTS[kind].operations if item[1] == named]
    if len(matching) == 1:
        # Named without its tool, it is the kind's one operation of that name.
        selected = matching[0]
    if selected not in COMPONENTS[kind].operations:
        offered = ", ".join(f"{tool}.{name}" for tool, name in COMPONENTS[kind].operations)
        raise InputValidationError(
            f"{kind} cannot run {named}. Its operations: {offered or 'none'}."
        )
    return selected


def bound(selected):
    """Argument names an operation's connections supply."""
    return {
        path.rsplit(".", 1)[-1]: source
        for path, source in experiment_interfaces.bound_arguments(*selected).items()
    }


def operation_fields(tool, name):
    """The argument names an operation takes, apart from those its connections supply."""
    if tool == "platform":
        fields = named(research_services.OPERATIONS[name][0])
    elif TOOLS[tool].operations[name].payload is not None:
        # A campaign named on the stage addresses the operation; the rest is its payload.
        fields = named(TOOLS[tool].operations[name].payload) | {"campaign"}
    else:
        fields = named(TOOLS[tool].request) - {"operation", "describe"}
    if tool == "serving":
        fields &= SERVING[name]
    return fields - set(bound((tool, name))) - {"request_key", "arguments"}


def envelope(tool, name, arguments):
    if tool == "platform":
        return {"name": name, "arguments": arguments}
    if tool == "training":
        campaign = {"campaign": arguments.pop("campaign")} if "campaign" in arguments else {}
        return {"operation": name, **campaign, "arguments": arguments}
    return {"operation": name, **arguments}


def unwrap(operation):
    tool, arguments = operation["tool"], operation["arguments"]
    if tool == "platform":
        return tool, arguments.get("name"), dict(arguments.get("arguments", {}))
    if tool == "training":
        campaign = {"campaign": arguments["campaign"]} if arguments.get("campaign") else {}
        return tool, arguments.get("operation"), campaign | arguments.get("arguments", {})
    if tool == "workspace":
        # A script's stored envelope also carries paging defaults that are not settings.
        return (
            tool,
            arguments.get("operation"),
            {key: arguments[key] for key in SCRIPT if key in arguments},
        )
    return (
        tool,
        arguments.get("operation"),
        {
            key: value
            for key, value in arguments.items()
            if key != "operation"
            and (tool != "serving" or key in SERVING.get(arguments.get("operation"), ()))
        },
    )


def merged(current, changes):
    """``changes`` laid over ``current``: objects merge, null removes, anything else replaces."""
    result = dict(current)
    for key, value in changes.items():
        if value is None:
            result.pop(key, None)
        elif isinstance(value, dict) and isinstance(result.get(key), dict):
            result[key] = merged(result[key], value)
        else:
            result[key] = value
    return result


def connections(document, node):
    """A node's connections as a stage names them: port -> "stage.port"."""
    many = resolved(node).many
    inputs = {}
    for edge in document["edges"]:
        if edge["target"] != node["id"]:
            continue
        source = f"{edge['source']}.{edge['output']}"
        if edge["input"] in many:
            inputs.setdefault(edge["input"], []).append(source)
        else:
            inputs[edge["input"]] = source
    return inputs


def stage(document, node):
    """One saved node as a stage."""
    settings = {
        key: value
        for key, value in node["config"].items()
        if not key.startswith("_") and not (node["kind"] == "data" and key in DERIVED)
    }
    inputs = connections(document, node)
    if node.get("operation"):
        tool, name, arguments = unwrap(node["operation"])
        settings |= arguments
        if (tool, name) != operation_of(node["kind"], settings, inputs):
            settings["operation"] = f"{tool}.{name}"
        if (tool, name) == ("training", "create"):
            # Read back under the names it is written with: the run's settings beside trials.
            settings |= settings.pop("run", {})
            for key in ("dataset", "cell", "validation_cell", "base_model"):
                settings.pop(key, None)
    if node["kind"] != "model" and list(settings.get("model") or ()) == ["model"]:
        settings["model"] = settings["model"]["model"]
    return {
        "id": node["id"],
        "kind": node["kind"],
        "title": node["title"],
        **({"inputs": inputs} if inputs else {}),
        **({"settings": settings} if settings else {}),
        **({"notes": node["notes"]} if node.get("notes") else {}),
        "outputs": list(resolved(node).outputs),
    }


def describe(document):
    """A saved document as an agent reads it."""
    return {
        "stages": [stage(document, node) for node in document["nodes"]],
        "outputs": {
            name: f"{output['node']}.{output['port']}"
            for name, output in document.get("outputs", {}).items()
        },
    }


def accepted(kind, selected):
    """Every setting name a stage of this kind takes for the operation it runs."""
    names = set(CONFIGURATION.get(kind, ()))
    if "model" in COMPONENTS[kind].inputs:
        names.add("model")
    if selected:
        names |= operation_fields(*selected)
    if selected == ("training", "create"):
        names |= set(RUN)
    return names


def build(kind, title, settings, inputs, notes, *, created):
    """A stage's node configuration and operation. A stage being created has every default
    written out; one being updated changes only what its new settings say."""
    settings = deepcopy(settings)
    selected = operation_of(kind, settings, inputs)
    settings.pop("operation", None)
    if selected == ("workspace", "python"):
        # A script reads the rest of its settings as its parameters.
        arguments = {key: settings.pop(key) for key in SCRIPT if key in settings}
        return settings, {"tool": "workspace", "arguments": envelope(*selected, arguments)}
    if selected:
        # Connections supply these; a cell among them has already been read as an input.
        for name in (*bound(selected), "request_key"):
            settings.pop(name, None)
    # Fields of a nested contract written beside the other settings belong inside it.
    if selected == ("training", "create"):
        run = settings.pop("run", {}) | {key: settings.pop(key) for key in RUN if key in settings}
        if created:
            run.setdefault("hyperparameters", {})
            run.setdefault("name", title)
        if run:
            settings["run"] = run
    if selected == ("platform", "create_data_partition"):
        recipe = {key: settings.pop(key) for key in list(settings) if key in SPLIT}
        if recipe:
            settings["recipe"] = settings.get("recipe", {}) | recipe
    names = accepted(kind, selected)
    unknown = sorted(set(settings) - names)
    if unknown:
        raise InputValidationError(
            f"{kind} has no setting {', '.join(unknown)}. Its settings: "
            f"{', '.join(sorted(names))}. Read their shapes with "
            f"explore_context(operation=contracts, kind={kind})."
        )
    if kind != "model" and isinstance(settings.get("model"), str):
        settings["model"] = {"model": settings["model"]}
    chosen = settings.get("model") if selected == ("training", "create") else None
    if (
        isinstance(chosen, dict)
        and isinstance(chosen.get("model"), str)
        and get_model_config_any_backend(chosen["model"]) is None
    ):
        raise InputValidationError(
            f"{chosen['model']} is not a training model. Select an exact model ID from "
            "platform(name=get_model_catalog)."
        )
    fields = operation_fields(*selected) if selected else set()
    arguments = {key: settings.pop(key) for key in list(settings) if key in fields}
    config = settings
    if selected == ("platform", "create_data_partition") and created:
        arguments.setdefault("name", title)
        arguments["recipe"] = SPLIT | arguments.get("recipe", {})
    if selected == ("training", "create") and created:
        arguments.setdefault("trials", 1)
    operation = (
        {"tool": selected[0], "arguments": envelope(*selected, arguments)} if selected else None
    )
    return config, operation


def source_port(nodes, reference, target, port):
    """The (stage, output) a reference names, for the typed input it feeds."""
    wanted = resolved(target).inputs[port]
    identifier, _, output = reference.partition(".")
    source = nodes.get(identifier)
    if source is None:
        raise InputValidationError(
            f"{target['id']}.{port}: no stage {identifier}. Stages: {', '.join(sorted(nodes))}."
        )
    outputs = resolved(source).outputs
    fitting = [name for name, kind in outputs.items() if kind == wanted]
    if output:
        if outputs.get(output) != wanted:
            raise InputValidationError(
                f"{target['id']}.{port} takes {wanted}; {identifier}.{output} is "
                f"{outputs.get(output, 'not an output')}. "
                + (
                    f"Use {', '.join(f'{identifier}.{name}' for name in fitting)}."
                    if fitting
                    else f"{identifier} produces {outputs or 'nothing'}."
                )
            )
        return identifier, output
    # An output named for the input it feeds settles a choice between several of one type,
    # and so does the partition each kind of stage is meant to read.
    for preferred in (port, PARTITION.get((target["kind"], port))):
        if len(fitting) > 1 and preferred in fitting:
            fitting = [preferred]
    if len(fitting) != 1:
        raise InputValidationError(
            f"{target['id']}.{port} takes {wanted}. "
            + (
                f"Name one output: {', '.join(f'{identifier}.{name}' for name in fitting)}."
                if fitting
                else f"{identifier} produces {outputs or 'nothing'}."
            )
        )
    return identifier, fitting[0]


def fresh(nodes, kind):
    return next(
        f"{kind}_{index}" for index in range(len(nodes) + 1) if f"{kind}_{index}" not in nodes
    )


def place(nodes, x, y):
    taken = {(node["position"]["x"], node["position"]["y"]) for node in nodes.values()}
    while (x, y) in taken:
        y += 270
    return {"x": x, "y": y}


def is_cell(value):
    try:
        UUID(str(value))
    except ValueError:
        return False
    return isinstance(value, (str, UUID))


def data_stage(project, document, nodes, cell, row):
    """The stage bound to a dataset cell, added when the flow does not have one yet."""
    for node in nodes.values():
        if node["kind"] == "data" and node["config"].get("cell") == cell:
            return node["id"]
    record = (
        Cell.objects.select_related("dataset").filter(pk=cell, dataset__project=project).first()
    )
    if record is None:
        raise InputValidationError(f"No dataset cell {cell} exists in this project")
    node = {
        "id": fresh(nodes, "data"),
        "kind": "data",
        "title": record.dataset.name,
        "position": place(nodes, 80, row),
        "config": {"cell": cell},
        "operation": None,
        "notes": "",
    }
    document["nodes"].append(node)
    nodes[node["id"]] = node
    return node["id"]


def yielded(project, document, nodes, cell):
    """The partition output that is this cell, when the flow has the stage that yields it.
    A partition's member named by its cell names that output: the connection then shows where
    the data comes from, and a sealed member is named without being read."""
    for node in nodes.values():
        if node["kind"] != "split":
            continue
        for role in produced(node):
            edge = {"source": node["id"], "output": role}
            if experiment_partitions.member_cell(project, document, edge) == cell:
                return f"{node['id']}.{role}"
    return None


def connect(project, document, nodes, node, inputs):
    """Replace the connections into ``node`` for every port ``inputs`` names."""
    component = resolved(node)
    wired = {}
    for port, value in inputs.items():
        if port not in component.inputs:
            offered = ", ".join(f"{name} ({kind})" for name, kind in component.inputs.items())
            raise InputValidationError(
                f"{node['kind']} has no input {port}. Its inputs: {offered or 'none'}."
            )
        sources = [] if value is None else value if isinstance(value, list) else [value]
        if len(sources) > 1 and port not in component.many:
            raise InputValidationError(f"{node['id']}.{port} takes one connection")
        wired[port] = sources
    document["edges"] = [
        edge
        for edge in document["edges"]
        if not (edge["target"] == node["id"] and edge["input"] in wired)
    ]
    for port, sources in wired.items():
        for reference in sources:
            if is_cell(reference):
                if component.inputs[port] != "data":
                    raise InputValidationError(f"{node['id']}.{port} does not take a dataset")
                reference = yielded(project, document, nodes, str(reference)) or data_stage(
                    project, document, nodes, str(reference), node["position"]["y"]
                )
            source, output = source_port(nodes, str(reference), node, port)
            if source == node["id"]:
                raise InputValidationError(f"{node['id']} cannot consume its own output")
            document["edges"].append(
                {"source": source, "output": output, "target": node["id"], "input": port}
            )


def produced(node):
    """The outputs a completed stage always registers."""
    ports = resolved(node).outputs
    if node["kind"] == "research":
        return [port for port in node["config"].get("outputs", []) if port in ports]
    if node["kind"] in CONTROL_SETTINGS:
        return [port for port in node["config"].get("outputs", {}) if port in ports]
    if node["kind"] in {"compare", "join"}:
        return ["scores"]
    if operation_of(node["kind"], {}, {}) == ("platform", "create_data_partition"):
        # A partition yields the roles its recipe names.
        fractions = unwrap(node["operation"])[2].get("recipe", {}).get("fractions", {})
        return [port for port in ports if port in fractions]
    contract = experiment_interfaces.interface(node)
    return [port for port in contract["produces"] if port in ports] if contract else []


def declare(document):
    nodes = {node["id"]: node for node in document["nodes"]}
    available = experiment_interfaces.unconditional_outputs(document)
    # Generated exports cannot require a skipped branch; explicitly named outputs remain required.
    outputs = {
        name: output
        for name, output in document.get("outputs", {}).items()
        if output["node"] in nodes
        and output["port"] in resolved(nodes[output["node"]]).outputs
        and (
            name != f"{output['node']}_{output['port']}"
            or (output["node"], output["port"]) in available
        )
    }
    declared = {(output["node"], output["port"]) for output in outputs.values()}
    consumed = {edge["source"] for edge in document["edges"]}
    for node in document["nodes"]:
        if node["id"] in consumed or node["kind"] in SOURCES:
            continue
        for port in produced(node):
            if (node["id"], port) in available and (node["id"], port) not in declared:
                outputs[f"{node['id']}_{port}"] = {"node": node["id"], "port": port}
    document["outputs"] = outputs


def prepared_split(nodes, wiring):
    """How a partition of a transform spec's output is cut unless its author says otherwise:
    rows that share a group key stay together, and each role gets every label."""
    reference = wiring.get("data")
    source = nodes.get(reference.partition(".")[0]) if isinstance(reference, str) else None
    if source is None or source["kind"] != "transform" or not source.get("operation"):
        return {}
    tool, name, arguments = unwrap(source["operation"])
    spec = arguments.get("spec") if (tool, name) == ("platform", "prepare_dataset") else None
    if not isinstance(spec, dict):
        return {}
    return {
        "group_by": [key["name"] for key in spec.get("group_keys", [])],
        "stratify_by": "decision.target_probabilities",
    }


def partitioned(nodes, kind, wiring):
    """The development data a train stage takes from the partition it trains on, unless its
    author wired that port, even to nothing."""
    reference = wiring.get("data") if kind == "train" else None
    source = nodes.get(reference.partition(".")[0]) if isinstance(reference, str) else None
    if source is None or source["kind"] != "split" or "development" in wiring:
        return {}
    if "development" not in produced(source):
        return {}
    return {"development": f"{source['id']}.development"}


def reserve(document):
    """Wire what is missing between each train stage and the sealed data its model is
    qualified on. A train stage reserves the final output of the partition it trains on, or
    of the partition it is selected on when it trains on other data (an arm given a subset),
    or of the flow's only partition; a qualify stage reads its model's reservation; a qualify
    stage given other data reserves that for a model with none. Connections that already exist
    are left as written."""
    nodes = {node["id"]: node for node in document["nodes"]}

    def wired(target, port):
        return next(
            (
                f"{edge['source']}.{edge['output']}"
                for edge in document["edges"]
                if edge["target"] == target and edge["input"] == port
            ),
            None,
        )

    def wire(target, port, reference):
        source, _, output = reference.partition(".")
        document["edges"].append(
            {"source": source, "output": output, "target": target, "input": port}
        )

    sealing = [
        node for node in document["nodes"] if node["kind"] == "split" and "final" in produced(node)
    ]
    for node in document["nodes"]:
        if node["kind"] != "qualify" or wired(node["id"], "data"):
            continue
        model = nodes.get((wired(node["id"], "model") or "").partition(".")[0])
        if model is None or model["kind"] != "train":
            continue
        # A qualify stage reads, by default, the sealed final partition of the split that
        # feeds its model's training.
        feeding = [
            nodes.get((wired(model["id"], port) or "").partition(".")[0])
            for port in ("data", "development")
        ]
        source = next((item for item in feeding if item in sealing), None) or (
            sealing[0] if len(sealing) == 1 and any(feeding) else None
        )
        if source:
            wire(node["id"], "data", f"{source['id']}.final")


def apply(project, document, request):
    """The document with one stage added or updated, and that stage's identifier."""
    document = deepcopy(document)
    nodes = {node["id"]: node for node in document["nodes"]}
    current = nodes.get(request.id) if request.id else None
    kind = request.kind or (current["kind"] if current else None)
    if kind is None:
        raise InputValidationError(
            f"No stage {request.id} exists; name its kind to add it. "
            f"Stages: {', '.join(sorted(nodes)) or 'none'}."
        )
    if current is not None and current["kind"] != kind:
        raise InputValidationError(
            f"{request.id} is a {current['kind']} stage. Remove it to reuse its identifier, "
            "or give the new stage another one."
        )
    before = stage(document, current) if current else {}
    title = request.title or before.get("title") or COMPONENTS[kind].label
    notes = before.get("notes", "") if request.notes is None else request.notes
    settings = merged(before.get("settings", {}), request.settings or {})
    inputs = dict(request.inputs or {})
    wiring = {**before.get("inputs", {}), **inputs}
    # A value written where the operation's own argument would go is that input's connection.
    selected = operation_of(kind, settings, wiring)
    for argument, source in bound(selected).items() if selected else ():
        value = settings.get(argument)
        port, _, field = source.partition(".")
        if field == "cell" and is_cell(value) and port not in wiring:
            inputs[port] = value
        elif source == "model.model" and value and "model" not in settings:
            settings["model"] = value[0] if isinstance(value, list) else value
    inputs |= partitioned(nodes, kind, {**wiring, **inputs})
    if kind == "split" and current is None:
        written = settings.keys() | settings.get("recipe", {}).keys()
        settings = {
            key: value
            for key, value in prepared_split(nodes, {**wiring, **inputs}).items()
            if key not in written
        } | settings
    if current is not None and not request.settings:
        # Renaming or rewiring a stage leaves its saved configuration exactly as it was.
        config, operation = current["config"], current.get("operation")
    else:
        config, operation = build(
            kind, title, settings, {**wiring, **inputs}, notes, created=current is None
        )
        if kind == "data" and current and current["config"].get("cell") == config.get("cell"):
            config = current["config"]
    if current is None:
        current = {
            "id": request.id or fresh(nodes, kind),
            "kind": kind,
            "position": {"x": 0, "y": 0},
        }
        document["nodes"].append(current)
        nodes[current["id"]] = current
        placed = False
    else:
        placed = True
    current |= {"title": title, "config": config, "operation": operation, "notes": notes}
    connect(project, document, nodes, current, inputs)
    reserve(document)
    if not placed:
        sources = [
            nodes[edge["source"]]["position"]
            for edge in document["edges"]
            if edge["target"] == current["id"]
        ]
        others = {key: value for key, value in nodes.items() if key != current["id"]}
        current["position"] = place(
            others,
            max((position["x"] for position in sources), default=-260) + 340,
            min((position["y"] for position in sources), default=80),
        )
    declare(document)
    return document, current["id"]


def remove(document, identifiers):
    document = deepcopy(document)
    # A stage that is not there is already removed: the flow is as the call asked.
    removed = set(identifiers) & {node["id"] for node in document["nodes"]}
    document["nodes"] = [node for node in document["nodes"] if node["id"] not in removed]
    if not document["nodes"]:
        raise InputValidationError("A flow keeps at least one stage")
    document["edges"] = [
        edge
        for edge in document["edges"]
        if edge["source"] not in removed and edge["target"] not in removed
    ]
    declare(document)
    return document


def changes(before, after, path=()):
    """Every setting that differs between two stage views, as paths."""
    if isinstance(before, dict) and isinstance(after, dict):
        found = []
        for key in sorted(before.keys() | after.keys()):
            found += changes(before.get(key), after.get(key), (*path, key))
        return found
    if before == after:
        return []
    return [{"path": list(path), "before": before, "after": after}]


# Settings with a default written out when a stage is built, so none is required of an author.
DEFAULTED = {"split": {"name", "recipe"}, "train": {"run", "trials"}}
MODEL = {
    "description": "A model id from platform(name=get_model_catalog), or a retained candidate "
    'as {"asset": id, "fingerprint": hash}. Omit when a stage output is connected to model.',
    "anyOf": [{"type": "string"}, {"type": "object"}],
}
EXAMPLES = {
    "transform": {
        "kind": "transform",
        "inputs": {"data": "<cell of the approved source>"},
        "settings": {
            "spec": {
                "target": {
                    "column": "Survived",
                    "question": "Did this passenger survive?",
                    "options": [
                        {"value": "0", "label": "Did not survive"},
                        {"value": "1", "label": "Survived"},
                    ],
                },
                "inputs": [
                    {"name": "passenger_class", "sql": '"Pclass"'},
                    {"name": "age_years", "sql": "TRY_CAST(NULLIF(TRIM(\"Age\"), '') AS DOUBLE)"},
                    {"name": "family_size", "sql": '"SibSp" + "Parch" + 1'},
                ],
                "excluded": [
                    {"column": "PassengerId", "reason": "identifier"},
                    {"column": "Name", "reason": "identifier"},
                ],
                "group_keys": [{"name": "ticket", "sql": '"Ticket"'}],
            }
        },
    },
    "split": {
        "kind": "split",
        "inputs": {"data": "data_0"},
        # After a transform spec, rows are grouped by the spec's group keys and stratified by
        # label without being told to. group_by and stratify_by name columns of the rows read.
        "settings": {"fractions": {"train": 0.7, "development": 0.15, "final": 0.15}, "seed": 42},
    },
    "check_data": {
        "kind": "check_data",
        "inputs": {"data": "split_0.train"},
        "settings": {
            "row_schema": {"type": "object", "required": ["decision"]},
            "minimum_rows": 100,
        },
    },
    "export_data": {
        "kind": "export_data",
        "inputs": {"data": "split_0.development"},
        "settings": {"format": "jsonl"},
    },
    "train": {
        "kind": "train",
        "inputs": {"data": "split_0.train", "development": "split_0.development"},
        "settings": {
            "model": "<model id from get_model_catalog>",
            "hyperparameters": {"n_epochs": 3, "learning_rate": 0.0001},
            "trials": 1,
        },
    },
    "evaluate": {
        "kind": "evaluate",
        "inputs": {"data": "split_0.development", "model": "train_0"},
        "settings": {
            "name": "Development comparison",
            "participants": [
                {
                    "key": "reference",
                    "name": "OpenRouter reference model",
                    "kind": "external",
                    "model": "<OpenRouter model id from benchmark(operation=catalog)>",
                }
            ],
            "baseline": "reference",
        },
    },
    "compare": {
        "kind": "compare",
        "inputs": {"scores": ["evaluate_0"]},
        "settings": {"metric": "/report/metrics/accuracy/mean", "direction": "maximize"},
    },
    "qualify": {"kind": "qualify", "inputs": {"model": "train_0"}},
    "publish": {
        "kind": "publish",
        "inputs": {"model": "train_0", "scores": "qualify_0"},
        "settings": {"ttl_seconds": 1800, "max_requests": 4},
    },
    "inference": {
        "kind": "inference",
        "inputs": {"deployment": "publish_0"},
        "settings": {
            "decisions": [
                {
                    "kind": "choice",
                    "state": "<decision.state of one prepared row>",
                    "question": "<decision.question of that row>",
                    "options": ["<its options, in order>"],
                }
            ]
        },
    },
    "research": {
        "kind": "research",
        "inputs": {"data": "split_0.train"},
        "settings": {
            "objective": "Find why development loss plateaus after the first epoch.",
            "outputs": ["scores"],
        },
    },
}


def untitled(schema):
    """A generated schema without the titles that only repeat its field names."""
    if isinstance(schema, dict):
        return {
            key: untitled(value)
            for key, value in schema.items()
            if key != "title" or not isinstance(value, str)
        }
    if isinstance(schema, list):
        return [untitled(item) for item in schema]
    return schema


def settings_schema(kind, selected):
    """The settings a stage of this kind takes for one operation, as a JSON Schema."""
    properties, definitions, required = {}, {}, set()

    def take(schema, names=None):
        definitions.update(schema.get("$defs", {}))
        for name, value in schema.get("properties", {}).items():
            if names is None or name in names:
                properties[name] = value
        required.update(
            name for name in schema.get("required", []) if names is None or name in names
        )

    if selected == ("workspace", "python"):
        take(TOOLS["workspace"].request.model_json_schema(), set(SCRIPT))
        required.add("code")
    elif selected:
        tool, name = selected
        fields = operation_fields(tool, name)
        if tool == "platform":
            take(research_services.input_schema(name), fields)
        elif TOOLS[tool].operations[name].payload is not None:
            take(TOOLS[tool].payload_schema(name), fields)
            if "campaign" in fields and selected != ("training", "create"):
                properties["campaign"] = {"type": "string", "format": "uuid"}
        else:
            take(TOOLS[tool].request.model_json_schema(), fields)
    contract = {
        "compare": Comparison,
        "condition": Condition,
        "research": Investigation,
        "publish": Publication,
        **CONTROL_SETTINGS,
    }.get(kind)
    if contract is not None and (selected is None or kind == "publish"):
        take(contract.model_json_schema())
    if "model" in COMPONENTS[kind].inputs:
        properties["model"] = MODEL
    if kind == "suite":
        properties.update(
            {
                "asset": {
                    "type": "string",
                    "format": "uuid",
                    "description": "Published suite asset from asset(operation=publish, kind=suite, definition={eval_set: ...}).",
                },
                "fingerprint": {"type": "string"},
            }
        )
        required.add("asset")
    if selected == ("training", "create"):
        run = StartFinetuneInput.model_json_schema()
        definitions.update(run.get("$defs", {}))
        for name in RUN:
            if name in run["properties"]:
                properties[name] = run["properties"][name]
        properties.pop("run", None)
    return untitled(
        {
            "type": "object",
            "properties": properties,
            "required": sorted(required - DEFAULTED.get(kind, set()) - {"defaults"}),
            "additionalProperties": selected == ("workspace", "python"),
            **({"$defs": definitions} if definitions else {}),
        }
    )


def catalogue():
    """The node catalogue as an agent authors from it."""
    return experiment_catalog.catalogue()


def contract(kind, operation=None):
    """What an agent needs to configure a stage of this kind: its ports, the operation it runs,
    the settings that operation takes and a worked example. ``operation`` selects one of the
    kind's other operations."""
    component = COMPONENTS[kind]
    default = operation_of(kind, {}, {})
    selected = next((item for item in component.operations if ".".join(item) == operation), default)
    others = [item for item in component.operations if item != selected]
    example = EXAMPLES.get(kind) if selected == default else None
    return {
        "kind": kind,
        "label": component.label,
        "description": component.description,
        "inputs": {
            name: {
                "type": type_,
                "required": name in component.required,
                **({"many": True} if name in component.many else {}),
            }
            for name, type_ in component.inputs.items()
        },
        "outputs": dict(component.outputs),
        **(
            {
                "completion": "The stage starts a campaign of trials runs (1 to 5) on the connected "
                "train data. After each run the training agent plans the next learning rate and "
                "epochs, or stops; the campaign keeps the run with the lowest development loss. "
                "The stage emits that run's checkpoint when the campaign completes. Connect "
                "development data, or the run splits off its own validation rows."
            }
            if kind == "train" and selected == ("training", "create")
            else {}
        ),
        "operation": ".".join(selected) if selected else None,
        **(
            {
                "editing": "To add models to a saved benchmark, call experiment(stage) with its "
                "id and settings.participants containing the existing explicit participants plus "
                "the new entries. A connected training node supplies its published checkpoint "
                "at execution. Keep the data, model and suite inputs, eval_set and baseline as "
                "configured. Use exact OpenRouter IDs from benchmark(catalog), passing the eval "
                "set or suite for chat comparisons."
            }
            if selected == ("benchmark", "run")
            else {}
        ),
        "settings": settings_schema(kind, selected),
        **(
            {
                "other_operations": {
                    ".".join(item): "Select with settings.operation. Its settings: "
                    f"explore_context(operation=contracts, kind={kind}, query={'.'.join(item)})."
                    for item in others
                }
            }
            if others
            else {}
        ),
        **(
            {"example": {"tool": "experiment", "arguments": {"operation": "stage", **example}}}
            if example
            else {}
        ),
    }