Skip to content

The platform for continuously improving AI agents.

32.4 KB
Raw Blame
import json
from contextlib import suppress
from copy import deepcopy
from uuid import UUID

from django.db import transaction
from django.db.models import CharField, OuterRef, Q, Subquery
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions import Cast

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    ResearchAction,
    ResearchAgent,
    ResearchArtifact,
    ResearchAssignment,
    ResearchEvent,
)
from overbae.services import context_graph
from overbae.services.research_contract import WORKSPACE_RUNS

UNRESOLVED = {"unresolved_evidence"}
OBSERVATION_LIMIT = 200


def retained_sources(action, kind):
    limit = OBSERVATION_LIMIT if kind == "workspace_inputs" else 1
    receipts = list(
        ResearchEvent.objects.filter(
            assignment_id=action.agent.assignment_id,
            agent_id=action.agent_id,
            kind=kind,
            payload__action=str(action.pk),
        ).values_list("payload", flat=True)[: limit + 1]
    )
    if not receipts:
        return None
    if len(receipts) > limit:
        return UNRESOLVED
    return set().union(*(saved_sources(receipt) for receipt in receipts))


@transaction.atomic
def retain_sources(action, kind, source_cells, *, model=None, workspace=None):
    if kind not in {"authoring_sources", "workspace_inputs"}:
        raise InputValidationError("Choose a retained authoring or workspace source receipt")
    ResearchAssignment.objects.select_for_update().get(pk=action.agent.assignment_id)
    ResearchAgent.objects.select_for_update().get(pk=action.agent_id)
    action = (
        ResearchAction.objects.select_for_update(of=("self",))
        .select_related("agent")
        .get(pk=action.pk)
    )
    previous = retained_sources(action, kind)
    if previous is not None:
        if kind == "authoring_sources":
            return previous
        bound = (
            workspace is None
            or ResearchEvent.objects.filter(
                assignment_id=action.agent.assignment_id,
                agent_id=action.agent_id,
                kind=kind,
                payload__action=str(action.pk),
                payload__sandbox=workspace["sandbox"],
                payload__lease=workspace["lease"],
            ).exists()
        )
        if source_cells <= previous and bound:
            return previous
    if (
        kind == "workspace_inputs"
        and ResearchEvent.objects.filter(
            assignment_id=action.agent.assignment_id,
            agent_id=action.agent_id,
            kind=kind,
            payload__action=str(action.pk),
        ).count()
        >= OBSERVATION_LIMIT
    ):
        raise InputValidationError("This workspace action exceeds its retained input limit")
    ResearchEvent.objects.create(
        assignment_id=action.agent.assignment_id,
        agent=action.agent,
        kind=kind,
        payload={
            "action": str(action.pk),
            "model": str(model.pk) if model else None,
            "source_cells": sorted(source_cells),
            **(
                {"sandbox": workspace["sandbox"], "lease": workspace["lease"]}
                if workspace is not None
                else {}
            ),
        },
    )
    return set(source_cells) | (previous or set())


def extend_workspace_inputs(agent, source_cells):
    workspace = agent.workspace
    bindings = (
        agent.assignment.events.filter(
            agent=agent,
            kind="workspace_inputs",
            payload__sandbox=workspace["sandbox"],
            payload__lease=workspace["lease"],
        )
        .annotate(action_key=KeyTextTransform("action", "payload"))
        .values("action_key")
    )
    # Only the original workspace can deliver more inputs to an unobserved execution.
    pending = list(
        agent.actions.alias(action_key=Cast("pk", CharField()))
        .filter(
            action_key__in=bindings,
            tool="workspace",
            arguments__operation__in=WORKSPACE_RUNS,
        )
        .filter(
            Q(state__in=["pending", "running", "unknown"])
            | Q(result__state__in=["accepted", "running", "unknown"])
            | Q(state="failed", result__state__isnull=True)
        )
        .select_related("agent__assignment")[: OBSERVATION_LIMIT + 1]
    )
    if len(pending) > OBSERVATION_LIMIT:
        raise InputValidationError("This workspace exceeds its retained execution limit")
    for action in pending:
        retain_sources(action, "workspace_inputs", source_cells, workspace=workspace)


def retain_authorship(action, *, model=None):
    if model is not None:
        if model.tool != "model" or model.agent_id != action.agent_id:
            raise InputValidationError("Authorship must bind this agent's retained model request")
        source_cells = saved_sources(model.arguments)
    else:
        source_cells = observed_sources(action, projected=True)
    return retain_sources(action, "authoring_sources", source_cells, model=model)


def observed_sources(writer, *, projected=True):
    retained = retained_sources(writer, "authoring_sources")
    if retained is not None:
        return retained
    actions = list(
        writer.agent.actions.filter(created_at__lte=writer.created_at)
        .exclude(pk=writer.pk)
        .exclude(state__in=["pending", "running", "denied"])
        .select_related("agent__assignment")
        .order_by("created_at", "pk")[: OBSERVATION_LIMIT + 1]
    )
    return observation_sources(writer.agent.assignment, actions=actions, projected=projected)


def sources_in_messages(assignment, history):
    return observation_sources(assignment, messages=history, projected=False)


def assistant_sources(assignment, message):
    # Exact authoring receipts own historical assistant text, including reasoning envelopes.
    from overbae.services import research_evidence

    calls = message.get("tool_calls", [])
    text = any(
        message.get(key)
        for key in ("content", "thinking", "reasoning", "reasoning_details", "_responses_output")
    )
    if not text and not calls:
        return set()
    candidates = ResearchAction.objects.filter(
        agent__assignment=assignment, tool="model", state__in=["completed", "unknown"]
    ).filter(
        Q(usage__assistant_message=message)
        | Q(result__text=message.get("content"), result__calls=calls)
    )
    candidates = list(candidates[: OBSERVATION_LIMIT + 1])
    if len(candidates) > OBSERVATION_LIMIT:
        return UNRESOLVED
    cells, matched = set(), False
    for model in candidates:
        envelope = model.usage.get("assistant_message") or {
            "role": "assistant",
            "content": model.result.get("text"),
            "tool_calls": model.result.get("calls", []),
        }
        if context_graph.canonical(envelope) == context_graph.canonical(message):
            matched = True
            cells.update(saved_sources(model.arguments))
    if matched:
        return cells
    if text or len(calls) > OBSERVATION_LIMIT:
        return UNRESOLVED
    for call in calls:
        try:
            arguments = json.loads(call.get("function", {}).get("arguments", ""))
        except (TypeError, ValueError):
            return UNRESOLVED
        records = list(
            ResearchAction.objects.filter(
                agent__assignment=assignment,
                request_key=call.get("id"),
                tool=call.get("function", {}).get("name"),
            ).select_related("agent__assignment")[:2]
        )
        if len(records) != 1:
            return UNRESOLVED
        action = records[0]
        if arguments == action.arguments:
            cells.update(research_evidence.action_sources(assignment, action))
        elif arguments != research_evidence.action_arguments(assignment, action):
            return UNRESOLVED
    return cells


def observation_sources(assignment, *, actions=(), messages=(), projected):
    # Model history imports this resolver when freezing request provenance.
    from overbae.services import research_agent, research_evidence
    from overbae.services.research_tools import source_boundary

    boundary = source_boundary(assignment) if projected else None
    hidden = (boundary[1] | UNRESOLVED) if boundary and boundary[1] else set()
    cache, seen = {}, set()
    remaining = [10000]

    def resolved(key, lookup):
        if key not in cache:
            if len(cache) >= OBSERVATION_LIMIT:
                return UNRESOLVED
            cache[key] = UNRESOLVED
            cache[key] = lookup()
        return cache[key]

    def reference(identifier, *, required=False):
        try:
            identifier = UUID(str(identifier))
        except ValueError:
            return UNRESOLVED if required else set()

        def lookup():
            action = (
                ResearchAction.objects.filter(
                    pk=identifier, agent__assignment__project=assignment.project
                )
                .select_related("agent__assignment")
                .first()
            )
            if action:
                return action_cells(action)
            artifact = (
                ResearchArtifact.objects.filter(
                    pk=identifier, assignment__project=assignment.project
                )
                .select_related("action__agent__assignment")
                .first()
            )
            return research_evidence.artifact_sources(artifact) if artifact else UNRESOLVED

        return resolved(("reference", identifier), lookup)

    def packet_cells(message, packet):
        if (
            message.get("role") == "tool"
            and isinstance(packet, dict)
            and isinstance(packet.get("data"), dict)
            and isinstance(packet["data"].get("access"), str)
            and packet["data"].get("access") in {"sealed_data", "sealed_results"}
        ):
            try:
                identifier = UUID(str(packet.get("receipt")))
            except ValueError:
                pass
            else:
                action = (
                    ResearchAction.objects.filter(
                        pk=identifier,
                        agent__assignment=assignment,
                        request_key=message.get("tool_call_id"),
                        tool=packet.get("tool"),
                    )
                    .select_related("agent__assignment")
                    .first()
                )
                if (
                    action
                    and research_evidence.action_result(assignment, action) != action.result
                    and research_agent.tool_observation(action) == packet
                ):
                    # The verified projection's receipt identifies hidden bytes, not sent bytes.
                    packet = {key: value for key, value in packet.items() if key != "receipt"}
        return walk(packet) | report_cells(packet)

    def walk(value, *, transcript=False):
        remaining[0] -= 1
        if remaining[0] < 0:
            return UNRESOLVED
        if isinstance(value, list):
            cells = set()
            for item in value:
                cells.update(walk(item, transcript=transcript))
                if remaining[0] < 0:
                    break
            return cells
        if not isinstance(value, dict):
            return set()
        if transcript and value.get("role") == "assistant":
            return assistant_sources(assignment, value)
        if isinstance(value.get("access"), str) and value["access"] in {
            "sealed_data",
            "sealed_results",
            "metadata_only",
            "sealed",
            "platform_only",
        }:
            # A partly redacted report may still contain readable source-backed children.
            cells = set()
            for key, child in value.items():
                if key not in {
                    "source_cells",
                    "cell",
                    "source_cell",
                    "prepared_cell",
                    "artifact_cell",
                    "receipt",
                    "full_receipt",
                    "action",
                    "artifact",
                    "artifacts",
                    "input_artifacts",
                    "notes_provenance",
                    "delegation_provenance",
                }:
                    cells.update(walk(child))
            return cells
        if {"event", "sender", "recipient", "message"} <= value.keys():
            return message_sources(assignment, value)
        cells = set(context_identity_sources(assignment, value))
        cells.update(research_evidence.context_execution_sources(assignment, value))
        if isinstance(value.get("kind"), str) and value["kind"] in {"action", "artifact"}:
            cells.update(reference(value.get("id"), required=True))
        if (
            transcript
            and isinstance(value.get("role"), str)
            and value["role"] in {"user", "tool", "assistant"}
            and isinstance(value.get("content"), str)
        ):
            if len(value["content"]) > 1_000_000:
                return UNRESOLVED
            try:
                packet = json.loads(value["content"])
            except ValueError:
                pass
            else:
                cells.update(
                    resolved(
                        ("packet", context_graph.fingerprint(value)),
                        lambda: packet_cells(value, packet),
                    )
                )
        if isinstance(value.get("function"), dict):
            arguments = value["function"].get("arguments")
            if isinstance(arguments, str):
                with suppress(ValueError):
                    cells.update(walk(json.loads(arguments)))
        for key, child in value.items():
            if key == "notes_provenance" and value.get("notes") == "":
                continue
            if key == "source_cells" and isinstance(child, list):
                cells.update(source_identifiers(child))
            elif (
                key in {"cell", "source_cell", "prepared_cell", "artifact_cell"}
                and isinstance(child, str)
                and child
            ):
                cells.update(source_identifiers([child]))
            elif key in {"receipt", "full_receipt", "action", "artifact", "handoff"}:
                cells.update(reference(child))
            elif key in {"artifacts", "input_artifacts"} and isinstance(child, list):
                for identifier in child:
                    if isinstance(identifier, str):
                        cells.update(reference(identifier, required=True))
            cells.update(walk(child))
            if remaining[0] < 0:
                break
        return cells

    def report_cells(packet):
        cells = set()
        for item, fields, sources in research_evidence.report_fields(assignment, packet, seen=seen):
            if item.get("access") not in {
                "sealed_data",
                "sealed_results",
                "sealed",
                "platform_only",
                "metadata_only",
            } and any(item.get(field) for field in fields):
                cells.update(sources)
        return cells

    def action_cells(action):
        def lookup():
            arguments = (
                research_evidence.action_arguments(assignment, action, boundary=boundary)
                if projected
                else action.arguments
            )
            result = (
                research_evidence.action_result(assignment, action, boundary=boundary)
                if projected
                else action.result
            )
            cells = research_evidence.action_sources(assignment, action, seen=seen) - hidden
            if (
                projected
                and isinstance(result, dict)
                and result.get("access") == "sealed_data"
                and result != action.result
            ):
                cells = set()
            return cells | walk(arguments) | walk(result)

        return resolved(("action", action.pk), lookup)

    cells = set(UNRESOLVED) if len(actions) > OBSERVATION_LIMIT else set()
    for action in actions[:OBSERVATION_LIMIT]:
        cells.update(action_cells(action))
    cells.update(walk(messages, transcript=True))
    cells = source_identifiers(cells)
    cells.difference_update(hidden - UNRESOLVED)
    identifiers = set()
    for cell in cells - UNRESOLVED:
        try:
            identifiers.add(UUID(cell))
        except (ValueError, TypeError):
            cells.update(UNRESOLVED)
    retained = set(
        Cell.objects.filter(pk__in=identifiers, dataset__project=assignment.project).values_list(
            "pk", flat=True
        )
    )
    if identifiers != retained:
        cells.update(UNRESOLVED)
    return cells


def source_identifiers(values):
    cells = set()
    for item in values:
        identifier = item.get("cell") if isinstance(item, dict) else item
        try:
            cells.add(str(UUID(identifier)))
        except (ValueError, TypeError, AttributeError):
            cells.update(UNRESOLVED)
    return cells


def saved_sources(payload):
    cells = payload.get("source_cells")
    if not isinstance(cells, list) or any(not isinstance(cell, str) for cell in cells):
        return UNRESOLVED
    return source_identifiers(cells)


def provenance(agent):
    identity = context_graph.fingerprint(agent.notes)
    receipt = (
        agent.assignment.events.filter(
            kind="working_notes", agent=agent, payload__identity=identity
        )
        .order_by("-pk")
        .first()
    )
    return {
        "agent": str(agent.pk),
        "identity": identity,
        "note_receipt": receipt.pk if receipt else None,
        "source_cells": sorted(saved_sources(receipt.payload))
        if receipt
        else sorted(UNRESOLVED if agent.notes else set()),
    }


@transaction.atomic
def write(agent, text, *, writer=None, append=False):
    locked = ResearchAgent.objects.select_for_update().select_related("assignment").get(pk=agent.pk)
    if writer:
        previous = locked.assignment.events.filter(
            kind="working_notes", agent=locked, payload__writer=str(writer.pk)
        ).first()
        if previous:
            return {"agent": str(locked.pk), "note_receipt": previous.pk, **previous.payload}
    cells = observed_sources(writer) if writer else set()
    if append:
        cells.update(provenance(locked)["source_cells"])
        text = locked.notes + text
    identity = context_graph.fingerprint(text)
    payload = {
        "identity": identity,
        "source_cells": sorted(cells),
        "writer": str(writer.pk) if writer else None,
    }
    # The note and its immutable provenance commit together; the owning action emits the wake.
    receipt = ResearchEvent.objects.create(
        assignment=locked.assignment, agent=locked, kind="working_notes", payload=payload
    )
    ResearchAgent.objects.filter(pk=locked.pk).update(notes=text)
    agent.notes = text
    return {"agent": str(agent.pk), "note_receipt": receipt.pk, **payload}


def project(assignment, value, *, boundary):
    # Native source admission imports the note projector.
    from overbae.services.research_tools import sources_permitted

    value = dict(value)
    if not value.get("text"):
        return value
    receipt = None
    try:
        agent_id = UUID(str(value.get("agent")))
        receipt_id = int(value.get("note_receipt"))
    except (ValueError, TypeError):
        pass
    else:
        receipt = ResearchEvent.objects.filter(
            pk=receipt_id,
            kind="working_notes",
            agent_id=agent_id,
            assignment__project=assignment.project,
            payload__identity=context_graph.fingerprint(value["text"]),
        ).first()
    cells = saved_sources(receipt.payload) if receipt else UNRESOLVED
    if not sources_permitted(assignment, cells, boundary=boundary):
        value.update(text="", access="sealed_data")
    return value


def record(agent, *, assignment=None, boundary=None):
    # The shared source boundary imports the native tool dispatcher.
    from overbae.services.research_tools import source_boundary

    assignment = assignment or agent.assignment
    return project(
        assignment,
        {"text": agent.notes, "authority": "agent_report", **provenance(agent)},
        boundary=boundary or source_boundary(assignment),
    )


def context_record(agent):
    # The shared source boundary imports the native tool dispatcher.
    from overbae.services.research_tools import source_boundary

    latest = ResearchEvent.objects.filter(
        agent_id=OuterRef("pk"), assignment_id=OuterRef("assignment_id"), kind="working_notes"
    ).order_by("-pk")
    # One MVCC snapshot binds text and latest receipt without locking another agent.
    current = (
        ResearchAgent.objects.select_related("assignment")
        .annotate(
            context_note_receipt=Subquery(latest.values("pk")[:1]),
            context_note_payload=Subquery(latest.values("payload")[:1]),
        )
        .get(pk=agent.pk)
    )
    identity = context_graph.fingerprint(current.notes)
    payload = current.context_note_payload
    valid = isinstance(payload, dict) and payload.get("identity") == identity
    return project(
        current.assignment,
        {
            "text": current.notes,
            "authority": "agent_report",
            "agent": str(current.pk),
            "identity": identity,
            "note_receipt": current.context_note_receipt if valid else None,
            "source_cells": sorted(
                saved_sources(payload) if valid else UNRESOLVED if current.notes else set()
            ),
        },
        boundary=source_boundary(current.assignment),
    )


def context_delegation(agent):
    kind = "delegated" if agent.parent_id else "accepted"
    receipts = agent.assignment.events.filter(kind=kind)
    if agent.parent_id:
        receipts = receipts.filter(agent=agent)
    receipt = receipts.order_by("pk").first()
    return {"agent": str(agent.pk), "kind": kind, "event": receipt.pk if receipt else None}


def context_delegation_receipt(assignment, proof):
    try:
        identifier = UUID(str(proof.get("agent")))
        event_id = int(proof.get("event"))
    except (TypeError, ValueError):
        return None
    receipts = ResearchEvent.objects.filter(pk=event_id, assignment__project=assignment.project)
    if proof.get("kind") == "delegated":
        receipt = receipts.filter(
            kind="delegated", agent_id=identifier, payload__agent=str(identifier)
        ).first()
        if receipt:
            return (
                {
                    "task": receipt.payload.get("task"),
                    "work_order": context_graph.public_facts(receipt.payload.get("work_order")),
                },
                saved_sources(receipt.payload),
            )
    elif proof.get("kind") == "accepted":
        receipt = (
            receipts.filter(
                kind="accepted",
                assignment__agents__pk=identifier,
                assignment__agents__parent__isnull=True,
            )
            .select_related("assignment")
            .first()
        )
        if receipt:
            # Assignment projection imports retained note provenance.
            from overbae.services import research_context_authorship

            fields = research_context_authorship.record_fields(
                receipt.assignment, "research_assignment"
            )
            sources = fields.get(("specification", "objective"), set())
            if receipt.payload.get("objective") != receipt.assignment.specification.get(
                "objective"
            ):
                sources = UNRESOLVED
            return {"task": receipt.payload.get("objective"), "work_order": {}}, sources
    return None


def context_identity_sources(assignment, value):
    reference = value.get("reference")
    if (
        not isinstance(reference, str)
        or not reference.startswith("research_agent:")
        or "label" not in value
    ):
        return set()
    identifier = reference.removeprefix("research_agent:")
    label = value["label"]
    if not isinstance(label, str):
        return UNRESOLVED
    if label in {"research_agent", f"research_agent {identifier}"}:
        return set()
    try:
        agent_id = UUID(identifier)
    except (ValueError, TypeError):
        return UNRESOLVED
    agent = (
        ResearchAgent.objects.select_related("assignment")
        .filter(pk=agent_id, assignment__project=assignment.project)
        .first()
    )
    retained = context_delegation_receipt(assignment, context_delegation(agent)) if agent else None
    if retained is None or label != str(retained[0]["task"])[:512]:
        return UNRESOLVED
    return retained[1]


def context_sources(assignment, action):
    value = action.result
    if not isinstance(value, dict):
        return UNRESOLVED
    identifier = action.arguments.get("reference", "").removeprefix("research_agent:")
    page_identity = context_graph.fingerprint(
        {key: item for key, item in value.items() if key not in {"note_read", "delegation_read"}}
    )

    def bound(proof):
        return (
            isinstance(proof, dict)
            and proof.get("agent") == identifier
            and proof.get("page_fingerprint") == page_identity
        )

    cells = set()
    path = value.get("path")
    field = path.split("/")[1] if isinstance(path, str) and path.startswith("/") else None
    if value.get("content") and (path == "" or field == "notes" or path is None):
        proof = value.get("note_read")
        if not bound(proof) or type(proof.get("disclosed")) is not bool:
            cells.update(UNRESOLVED)
        elif proof["disclosed"]:
            try:
                agent_id = UUID(identifier)
                receipt_id = int(proof.get("note_receipt"))
            except (ValueError, TypeError):
                cells.update(UNRESOLVED)
            else:
                receipt = ResearchEvent.objects.filter(
                    pk=receipt_id,
                    kind="working_notes",
                    agent_id=agent_id,
                    assignment__project=assignment.project,
                    payload__identity=proof.get("identity"),
                ).first()
                cells.update(saved_sources(receipt.payload) if receipt else UNRESOLVED)
    label = value.get("node", {}).get("label")
    neutral_labels = {"research_agent", f"research_agent {identifier}"}
    proof = value.get("delegation_read")
    if proof is not None:
        if not bound(proof) or not isinstance(proof.get("fields"), dict):
            return cells | UNRESOLVED
        fields = proof["fields"]
        if set(fields) - {"task", "work_order"} or (
            label not in neutral_labels and "task" not in fields
        ):
            return cells | UNRESOLVED
        if fields:
            retained = context_delegation_receipt(assignment, proof)
            if retained is None:
                return cells | UNRESOLVED
            authored, sources = retained
            if any(
                context_graph.fingerprint(authored[key]) != digest for key, digest in fields.items()
            ):
                return cells | UNRESOLVED
            if label not in neutral_labels and label != str(authored["task"])[:512]:
                return cells | UNRESOLVED
            cells.update(sources)
        return cells
    # Old opaque pages cannot borrow the current task or notes as proof of their contents.
    if value.get("content") and (path == "" or field in {"task", "work_order"} or path is None):
        cells.update(UNRESOLVED)
    cells.update(context_identity_sources(assignment, value.get("node", {})))
    return cells


def delegation(agent):
    if agent.parent_id is None:
        if not agent.assignment.request_key.startswith("flow-research:"):
            return None
        proof = context_delegation(agent)
        retained = context_delegation_receipt(agent.assignment, proof)
        return {**proof, "source_cells": sorted(retained[1] if retained else UNRESOLVED)}
    receipt = agent.assignment.events.filter(kind="delegated", agent=agent).order_by("pk").first()
    return {
        "agent": str(agent.pk),
        "event": receipt.pk if receipt else None,
        "source_cells": sorted(saved_sources(receipt.payload) if receipt else UNRESOLVED),
    }


def project_delegation(assignment, value, *, boundary=None):
    # Native packets and context graph records share the current source boundary.
    from overbae.services.research_tools import source_boundary, sources_permitted

    value = dict(value)
    provenance = value.get("delegation_provenance")
    if not isinstance(provenance, dict):
        return value
    boundary = boundary or source_boundary(assignment)
    try:
        identifier = UUID(str(provenance.get("agent")))
        event_id = int(provenance.get("event"))
    except (TypeError, ValueError):
        receipt = None
    else:
        receipt = ResearchEvent.objects.filter(
            pk=event_id,
            agent_id=identifier,
            kind="delegated",
            assignment__project=assignment.project,
            payload__agent=str(identifier),
        ).first()
    if provenance.get("kind") == "accepted":
        retained = context_delegation_receipt(assignment, provenance)
        cells = retained[1] if retained else UNRESOLVED
    else:
        cells = saved_sources(receipt.payload) if receipt else UNRESOLVED
    if not sources_permitted(assignment, cells, boundary=boundary):
        for key in ("task", "your_task"):
            if isinstance(value.get(key), str):
                value[key] = ""
        if "work_order" in value:
            value["work_order"] = {}
        value["delegation_provenance"] = {**provenance, "source_cells": []}
        value["access"] = "sealed_data"
    return value


def project_calls(agent, history, *, boundary):
    # Provider reasoning can retain the same source values as normalized assistant text.
    from overbae.services import research_evidence
    from overbae.services.research_tools import sources_permitted

    calls = {call["id"] for message in history for call in message.get("tool_calls", [])}
    actions = {
        action.request_key: action
        for action in agent.actions.filter(request_key__in=calls).select_related(
            "agent__assignment"
        )
    }
    projected_arguments = {}
    for key, action in actions.items():
        arguments = research_evidence.action_arguments(agent.assignment, action, boundary=boundary)
        if arguments != action.arguments:
            projected_arguments[key] = context_graph.canonical(arguments)
    result = []
    for original in history:
        message = deepcopy(original)
        if message.get("role") == "assistant" and not sources_permitted(
            agent.assignment, assistant_sources(agent.assignment, message), boundary=boundary
        ):
            if not message.get("tool_calls"):
                continue
            message = {"role": "assistant", "tool_calls": message["tool_calls"]}
        for call in message.get("tool_calls", []):
            if call["id"] in projected_arguments:
                call["function"]["arguments"] = projected_arguments[call["id"]]
        for item in message.get("_responses_output", []):
            if item.get("type") == "function_call" and item.get("call_id") in projected_arguments:
                item["arguments"] = projected_arguments[item["call_id"]]
        result.append(message)
    return result


def message_sources(assignment, value, *, cache=None):
    if not value.get("message"):
        return set()
    cache = {} if cache is None else cache
    try:
        identifier = int(value.get("event"))
    except (TypeError, ValueError):
        return UNRESOLVED
    if identifier not in cache:
        if len(cache) >= OBSERVATION_LIMIT:
            return UNRESOLVED
        cache[identifier] = ResearchEvent.objects.filter(
            pk=identifier, kind="agent_message", assignment__project=assignment.project
        ).first()
    event = cache[identifier]
    if event is None or any(
        event.payload.get(key) != value.get(key) for key in ("sender", "recipient", "message")
    ):
        return UNRESOLVED
    if event.agent_id is None and event.payload.get("sender") == "user":
        return set()
    if str(event.agent_id) != event.payload.get("sender"):
        return UNRESOLVED
    return saved_sources(event.payload)


def project_message(assignment, value, *, boundary, cache=None):
    # Native source admission imports the note projector.
    from overbae.services.research_tools import sources_permitted

    value = dict(value)
    if not sources_permitted(
        assignment, message_sources(assignment, value, cache=cache), boundary=boundary
    ):
        value.update(message="", access="sealed_data")
    return value