Skip to content

The platform for continuously improving AI agents.

34.7 KB
Raw Blame
import hashlib
import json
from contextlib import contextmanager
from datetime import timedelta
from decimal import Decimal
from tempfile import SpooledTemporaryFile

from django.core.files.base import ContentFile
from django.db import transaction
from django.db.models import Max, Sum
from django.utils import timezone

from overbae.api.credit_gate import require_credits
from overbae.core.errors import InputValidationError
from overbae.core.model_registry import TaskType, resolve_model
from overbae.models import (
    Capability,
    Cell,
    ComponentExecution,
    ExperimentExecution,
    FinetuningJob,
    PredictionAttempt,
    Project,
    ProjectMembership,
    ResearchAction,
    ResearchAgent,
    ResearchArtifact,
    ResearchAssignment,
    ResearchEvent,
)
from overbae.services import (
    context_graph,
    execution_mandates,
    experiment_training,
    research_evidence,
    research_notes,
    research_requests,
    research_team,
    research_telemetry,
)
from overbae.services.research_contract import TOOLS, Delegate, ResearchBudget, ResearchRequest

TERMINAL = {"completed", "unmet", "blocked", "cancelled", "exhausted"}
PROVIDER_BLOCKS = {"model_provider_unavailable", "model_provider_rejected"}
FINISHED_ACTIONS = {"completed", "failed", "denied", "unknown"}


def authorized(assignment):
    return ProjectMembership.objects.filter(
        project_id=assignment.project_id,
        project__is_active=True,
        user_id=assignment.created_by_id,
        user__is_active=True,
    ).exists()


def continues_admitted_work(assignment, *, agent=None):
    reason = assignment.result.get("reason")
    permitted = (
        assignment.state == "running"
        or assignment.state == "exhausted"
        and reason == "model_call_limit"
        or assignment.state == "blocked"
        and reason in PROVIDER_BLOCKS
    )
    if not permitted or agent is None:
        return permitted
    return (
        agent.state not in TERMINAL
        or agent.state == "exhausted"
        and agent.result.get("reason") == "model_call_limit"
        or agent.state == "blocked"
        and agent.result.get("provider_probe") is True
        and assignment.state == "blocked"
        and reason in PROVIDER_BLOCKS
    )


def number(value):
    result = Decimal(str(value))
    if not result.is_finite() or result < 0:
        raise InputValidationError("Costs must be finite and nonnegative")
    return result


def event(assignment, kind, payload, agent=None):
    from overbae.services import (
        research_wakes,  # Events wake executors after their transaction commits.
    )

    saved = ResearchEvent.objects.create(
        assignment=assignment,
        agent=agent,
        kind=kind,
        payload=json.loads(context_graph.canonical(payload)),
    )
    research_wakes.notify(assignment)
    research_telemetry.event_recorded(saved)
    return saved


def model_calls(assignment):
    return (
        ResearchAction.objects.filter(agent__assignment=assignment, tool="model")
        .exclude(state="denied")
        .count()
    )


@transaction.atomic
def initialize(project, *, user, **values):
    request = ResearchRequest.model_validate(values)
    specification = request.model_dump(mode="json", exclude={"execution_mandate"})
    identity = context_graph.fingerprint(specification)
    if (
        not user.is_active
        or not ProjectMembership.objects.filter(project=project, user=user).exists()
    ):
        raise InputValidationError("Research requires active project membership")
    Project.objects.select_for_update().get(pk=project.pk)
    prior = ResearchAssignment.objects.filter(
        project=project, request_key=request.request_key
    ).first()
    if prior:
        if prior.fingerprint != identity:
            raise InputValidationError(
                "This request key identifies a different research assignment"
            )
        if (
            request.execution_mandate is not None
            and prior.mandate_fingerprint != execution_mandates.identity(request.execution_mandate)
        ):
            raise InputValidationError("This request key has a different execution mandate")
        return prior
    if request.execution_mandate is None:
        raise InputValidationError("New research requires an explicit execution mandate")
    mandate = execution_mandates.normalize(request.execution_mandate)
    require_credits(project)
    capability = None
    roots = list(request.context_roots)
    if request.capability:
        capability = (
            Capability.objects.filter(project=project, pk=request.capability)
            .exclude(status="deleted")
            .first()
        )
        if capability is None:
            raise InputValidationError("The capability is unavailable in this project")
        roots.insert(0, f"capability:{capability.pk}")
    if Cell.objects.filter(pk__in=request.sealed_cells, dataset__project=project).count() != len(
        set(request.sealed_cells)
    ):
        raise InputValidationError("Select sealed cells from this project")
    roots = list(dict.fromkeys(roots)) or [f"agent:{project.pk}"]
    context_graph.observe(project, roots=roots, additional_sealed_cells=request.sealed_cells)
    snapshot = context_graph.capture(
        project, roots=roots, purpose="training", request_key=f"research:{request.request_key}"
    )
    assignment = ResearchAssignment.objects.create(
        project=project,
        created_by=user,
        capability=capability,
        context=snapshot,
        request_key=request.request_key,
        fingerprint=identity,
        specification=specification,
        execution_mandate=mandate,
        mandate_fingerprint=execution_mandates.identity(mandate),
        deadline=timezone.now() + timedelta(seconds=request.budget.max_seconds),
    )
    ResearchAgent.objects.create(
        assignment=assignment,
        request_key="owner",
        fingerprint=identity,
        task=request.objective,
        role="lead",
        model=resolve_model(TaskType.RESEARCH_AGENT),
    )
    event(assignment, "accepted", {"objective": request.objective, "context": str(snapshot.pk)})
    return assignment


@transaction.atomic
def create(project, *, user, **values):
    if (
        "execution_mandate" not in values
        and not ResearchAssignment.objects.filter(
            project=project, request_key=values["request_key"]
        ).exists()
    ):
        roots = list(values.get("context_roots", []))
        if values.get("capability"):
            roots.append(f"capability:{values['capability']}")
        values["execution_mandate"] = execution_mandates.admission(
            roots=roots, explicit=values.get("constraints", {})
        )
    assignment = initialize(project, user=user, **values)
    ensure_evaluator(assignment)
    return assignment


def ensure_evaluator(assignment):
    lead = assignment.agents.get(parent__isnull=True)
    delegate(
        lead,
        Delegate(
            request_key="independent-evaluation",
            role="evaluation",
            responsibility="independent-evaluation",
            task=(
                "Own independent verification of this research assignment. Inspect the task and approved evidence; "
                "send material data/measurement problems to the lead while work progresses. Inspect real development "
                "outputs, retained code and experiment receipts, independently reload or check outputs where needed, "
                "and assess task acceptance. Coordinate the exact candidate deliverables with the lead. Wait for "
                "new evidence while work runs; do not invent results or repeat unchanged checks. Finish only after "
                "the candidate artifacts/campaigns have been checked, listing their exact identities in "
                "reviewed_artifacts/reviewed_campaigns, giving verification_verdict as passed, failed or insufficient, "
                "and grounding the assessment in retained actions/artifacts. "
                "Your verification deliverable is a finding: submit observations in "
                "deliverables[{name: verification, findings: [...]}], each citing exact action/artifact evidence. "
                "No new report artifact is required for this finding. reviewed_artifacts lists another agent's "
                "candidate, never your own verification. Top-level prose evidence does not replace findings. "
                "Native export handoffs automatically verify all records against the pinned source; "
                "review.data exposes that check without a workspace. "
                "Independently assess requested semantics and coverage as well as those "
                "deterministic fidelity checks. "
                "A failed candidate is a finding to report early so the lead can remediate."
            ),
            deliverables=[
                {
                    "name": "verification",
                    "kind": "finding",
                    "acceptance": "Evidence-backed assessment of exact candidate outputs against task acceptance, with failures and limitations.",
                }
            ],
        ),
    )
    return assignment


def recorded_costs(assignment):
    # An assignment's flow runs spend on its behalf: their charges are its charges.
    scope = research_evidence.owners(assignment)
    actions = ResearchAction.objects.filter(agent__assignment_id__in=scope)
    jobs = FinetuningJob.objects.filter(
        trial__campaign__in=experiment_training.campaigns(scope)
    ).distinct()
    action_ledger = actions.aggregate(total=Sum("cost_usd"), through=Max("completed_at"))
    training_ledger = jobs.filter(cost_usd__isnull=False).aggregate(
        total=Sum("cost_usd"), through=Max("updated_at")
    )
    action_cost = action_ledger["total"]
    training_cost = training_ledger["total"]
    timestamps = [
        value["through"] for value in (action_ledger, training_ledger) if value["through"]
    ]
    observed = [value for value in (action_cost, training_cost) if value is not None]
    estimates = [
        number(action.usage["cost_estimate"]["estimated_usd"])
        for action in actions.filter(cost_usd__isnull=True, state="completed")
        if action.usage.get("cost_estimate", {}).get("estimated_usd") is not None
    ]
    return {
        "as_of": max(timestamps).isoformat() if timestamps else None,
        "recorded_action_usd": float(action_cost) if action_cost is not None else None,
        "recorded_training_gpu_usd": float(training_cost) if training_cost is not None else None,
        "known_recorded_usd": float(sum(observed)) if observed else None,
        "estimated_action_usd": float(sum(estimates)) if estimates else None,
        "all_in_actual_usd": None,
        "unsettled_action_count": actions.filter(
            cost_usd__isnull=True, reservation_usd__gt=0
        ).count(),
        "training_jobs_without_charge": jobs.filter(cost_usd__isnull=True).count(),
        "basis": "Recorded action charges plus training GPU ledger entries, including failed attempts. Reservations are not spend. Preparation, workspace, evaluation, serving and provider overhead may remain unmeasured; this is not a total bill.",
    }


def committed_cost(action):
    if action.cost_usd is not None:
        return action.cost_usd
    estimate = action.usage.get("cost_estimate", {}).get("estimated_usd")
    if action.state == "completed" and estimate is not None:
        return number(estimate)
    return action.reservation_usd


def allowance(assignment, agent=None):
    actions = list(
        ResearchAction.objects.filter(agent__assignment=assignment).only(
            "agent_id", "cost_usd", "reservation_usd", "tool", "state", "usage"
        )
    )
    total = sum((committed_cost(a) for a in actions), Decimal(0))
    calls = sum(a.tool == "model" and a.state != "denied" for a in actions)
    call_limit = assignment.specification["budget"]["max_model_calls"]
    return {
        "committed_usd": str(total),
        "remaining_seconds": max(0, int((assignment.deadline - timezone.now()).total_seconds())),
        "model_calls_used": calls,
        "model_calls_remaining": max(0, call_limit - calls),
    }


def require_recorded_effect(agent, effect, key, tool, arguments):
    if isinstance(effect, ExperimentExecution):
        from overbae.services import experiment_dispatch  # Dispatch journals terminal receipts.

        current = (
            ExperimentExecution.objects.select_for_update(of=("self",))
            .select_related("assignment", "revision")
            .get(pk=effect.pk)
        )
        run = current.assignment
        parent = execution_mandates.parent_assignment(run)
        controller_id = run.specification.get("task", {}).get("controller_action")
        controller = ResearchAction.objects.filter(
            pk=controller_id, agent=agent, tool="experiment"
        ).first()
        record = experiment_dispatch.receipt_record(run)
        valid = (
            agent.parent_id is None
            and parent is not None
            and parent.pk == agent.assignment_id
            and controller is not None
            and run.state in TERMINAL
            and tool == "flow_receipt"
            and key == f"flow-receipt:{run.pk}:{context_graph.fingerprint(record)}"
            and arguments == record
            and ResearchAction.objects.filter(
                agent=agent,
                request_key=f"flow-allocation:{controller_id}",
                tool="flow_allocation",
                state="running",
                result__run=str(run.pk),
                arguments=controller.arguments,
            ).exists()
        )
        if not valid:
            raise InputValidationError("This journal action does not match a terminal owned flow")
        # Terminal evidence and cost bookkeeping must survive loss of execution authority.
        return True
    if isinstance(effect, ComponentExecution):
        current = (
            ComponentExecution.objects.select_for_update(of=("self",))
            .select_related("action", "component")
            .get(pk=effect.pk)
        )
        port = arguments.get("port")
        valid = (
            current.state == "running"
            and current.expires_at > timezone.now()
            and current.action.agent_id == agent.pk
            and current.action.state in {"pending", "running", "completed"}
            and tool == "artifact"
            and isinstance(port, str)
            and port in current.component.definition["outputs"]
            and key == f"component-output:{current.action_id}:{port}"
            and arguments == {"component": str(current.component_id), "port": port}
        )
        family = "prepare"
    elif isinstance(effect, PredictionAttempt):
        current = (
            PredictionAttempt.objects.select_for_update(of=("self",))
            .select_related("row__prediction_set__candidate")
            .get(pk=effect.pk)
        )
        predictions = current.row.prediction_set
        definition = predictions.candidate.definition
        step = arguments.get("step")
        valid = (
            current.state == "running"
            and current.expires_at > timezone.now()
            and current.row.state == "running"
            and predictions.state == "running"
            and predictions.assignment_id == agent.assignment_id
            and agent.parent_id is None
            and tool == "prediction_model"
            and definition["kind"] != "component"
            and type(step) is int
            and 0 <= step < definition["max_steps"]
            and key == f"prediction:{current.pk}:{step}"
            and set(arguments) == {"attempt", "step", "model", "request_fingerprint", "max_tokens"}
            and arguments["attempt"] == str(current.pk)
            and arguments["model"] == definition["model"]
            and arguments["max_tokens"] == definition["max_tokens"]
        )
        family = "evaluate"
    else:
        valid = False
    if not valid:
        raise InputValidationError("This journal action does not belong to retained execution")
    execution_mandates.require_continuation(agent.assignment, family)
    return False


@transaction.atomic
def claim(agent, key, tool, arguments, reservation=0, *, effect=None, authored_by=None):
    from overbae.services import research_science  # Scientific decisions use this action journal.

    research_science.experiment_for(agent.assignment, lock=True)
    assignment = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    agent = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
    agent.assignment = assignment
    research_team.require_turn(agent)
    identity = context_graph.fingerprint({"tool": tool, "arguments": arguments})
    existing = ResearchAction.objects.filter(agent=agent, request_key=key).first()
    if existing:
        if existing.fingerprint != identity:
            raise InputValidationError("This research action key has different arguments")
        return existing
    reserve = number(reservation)
    authority_denied = (
        assignment.state != "running"
        or not authorized(assignment)
        or agent.state in TERMINAL
        or assignment.deadline <= timezone.now()
    )
    if effect is not None:
        settlement = require_recorded_effect(agent, effect, key, tool, arguments)
        authority_denied = not settlement and not continues_admitted_work(assignment, agent=agent)
    call_limited = (
        tool == "model"
        and model_calls(assignment) >= assignment.specification["budget"]["max_model_calls"]
    )
    denied = authority_denied or call_limited
    action = ResearchAction.objects.create(
        agent=agent,
        request_key=key,
        tool=tool,
        fingerprint=identity,
        arguments=json.loads(context_graph.canonical(arguments)),
        reservation_usd=0 if denied else reserve,
        cost_usd=0 if denied else None,
        state="denied" if denied else "pending",
        result={
            "error": "Research authority, deadline or call limit does not admit this action",
            "reason": "admission_denied" if authority_denied else "model_call_limit",
        }
        if denied
        else {},
    )
    if authored_by is not None or tool in TOOLS:
        research_notes.retain_authorship(action, model=authored_by)
    if denied:
        event(assignment, "admission_denied", {"action": str(action.pk), "tool": tool}, agent)
    return action


def complete(
    action,
    result,
    *,
    state="completed",
    cost=None,
    usage=None,
    trace_inputs=None,
    trace_outputs=None,
):
    action.state = state
    action.result = json.loads(context_graph.canonical(result))
    action.completed_at = timezone.now()
    if cost is not None:
        action.cost_usd = number(cost)
    if usage is not None:
        action.usage = json.loads(context_graph.canonical(usage))
    action.save(update_fields=["state", "result", "completed_at", "cost_usd", "usage"])
    event(
        action.agent.assignment,
        "action",
        {"action": str(action.pk), "tool": action.tool, "state": state},
        action.agent,
    )
    research_telemetry.action_completed(action, inputs=trace_inputs, outputs=trace_outputs)
    return action


@transaction.atomic
def delegate(parent, request, *, writer=None):
    parent = research_team.current_turn(parent)
    assignment = parent.assignment
    if (
        parent.parent_id
        or parent.state in TERMINAL
        or assignment.state != "running"
        or not authorized(assignment)
    ):
        raise InputValidationError("Only the active research lead delegates specialist work")
    if writer is not None and (
        writer.agent_id != parent.pk
        or writer.tool != "delegate"
        or Delegate.model_validate(writer.arguments) != request
    ):
        raise InputValidationError("The delegation must retain its authoring action")
    identity = context_graph.fingerprint(request.model_dump(mode="json"))
    key = f"{parent.pk}:{request.request_key}"
    previous = assignment.agents.filter(request_key=key).first()
    if previous:
        if previous.fingerprint != identity:
            raise InputValidationError("This helper key identifies a different task")
        return previous
    for member in assignment.agents.filter(work_order__responsibility=request.responsibility):
        if member.state not in TERMINAL or research_team.handoff_status(member)["state"] in {
            "submitted",
            "needs_revision",
        }:
            raise InputValidationError(
                "This responsibility already has an active or unreviewed specialist"
            )
    predecessors = list(assignment.agents.filter(pk__in=request.depends_on, parent=parent))
    if len(predecessors) != len(set(request.depends_on)):
        raise InputValidationError("Dependencies must be existing specialists in this assignment")
    budget = assignment.specification["budget"]
    if budget["max_depth"] < 1 or assignment.agents.count() >= budget["max_agents"]:
        raise InputValidationError("This assignment's helper limit has been reached")
    artifacts = [
        accessible_artifact(assignment, identifier) for identifier in set(request.artifacts)
    ]
    if len(artifacts) != len(set(request.artifacts)):
        raise InputValidationError("Select artifacts belonging to this assignment")
    child = ResearchAgent.objects.create(
        assignment=assignment,
        parent=parent,
        request_key=key,
        fingerprint=identity,
        task=request.task,
        role=request.role,
        work_order=request.model_dump(mode="json", exclude={"request_key", "task", "role"}),
        model=parent.model,
        result={"input_artifacts": [str(item.pk) for item in artifacts]},
    )
    research_team.bind_dependencies(child)
    event(
        assignment,
        "delegated",
        {
            "parent": str(parent.pk),
            "agent": str(child.pk),
            "task": request.task,
            "role": child.role,
            "work_order": child.work_order,
            "writer": str(writer.pk) if writer else None,
            "source_cells": sorted(research_notes.observed_sources(writer)) if writer else [],
        },
        child,
    )
    return child


def accessible_artifact(assignment, identifier):
    artifact = research_evidence.artifacts(assignment).filter(pk=identifier).first()
    if artifact is None:
        raise InputValidationError("The artifact is outside this assignment's approved inputs")
    return artifact


def artifact_record(artifact):
    return {
        "id": str(artifact.pk),
        "kind": artifact.kind,
        "title": artifact.title,
        "sha256": artifact.sha256,
        "bytes": artifact.size,
        "metadata": artifact.metadata,
        "agent": str(artifact.agent_id),
        "created_at": artifact.created_at.isoformat(),
    }


def artifact_bytes(artifact, *, limit):
    if artifact.size > limit:
        raise InputValidationError("The retained artifact no longer matches its identity")
    with artifact_stream(artifact) as file:
        return file.read()


@contextmanager
def artifact_stream(artifact):
    # Verify and read the same immutable bytes, spilling large exports to disk.
    with SpooledTemporaryFile(max_size=8 * 1024 * 1024) as snapshot:
        digest, size = hashlib.sha256(), 0
        with artifact.file.open("rb") as file:
            while chunk := file.read(1024 * 1024):
                size += len(chunk)
                if size > artifact.size:
                    raise InputValidationError(
                        "The retained artifact no longer matches its identity"
                    )
                digest.update(chunk)
                snapshot.write(chunk)
        if size != artifact.size or digest.hexdigest() != artifact.sha256:
            raise InputValidationError("The retained artifact no longer matches its identity")
        snapshot.seek(0)
        yield snapshot


def retain(action, request, data, *, source_cells=()):
    existing = ResearchArtifact.objects.filter(action=action).first()
    if existing:
        return existing
    record = ResearchArtifact(
        assignment=action.agent.assignment,
        agent=action.agent,
        action=action,
        title=request.title,
        kind=request.kind,
        sha256=hashlib.sha256(data).hexdigest(),
        size=len(data),
        metadata={
            **request.metadata,
            **(
                {
                    "phase": "final",
                    "access": "final_data"
                    if request.metadata.get("access") == "final_data"
                    else "final_results",
                }
                if research_evidence.can_read_final(action.agent.assignment)
                else {}
            ),
            "verification": "retained_bytes",
            "source_path": request.path,
            "source_cells": sorted(set(source_cells)),
        },
    )
    record.file.save(f"{record.pk}.bin", ContentFile(data), save=False)
    with transaction.atomic():
        research_team.current_turn(action.agent)
        existing = ResearchArtifact.objects.filter(action=action).first()
        if existing:
            return existing
        record.save()
    return record


def describe(assignment, *, after=0):
    # Serving imports the assignment authority and budget service.
    from overbae.services import research_serving
    from overbae.services.research_tools import (
        source_boundary,
    )  # Native admission imports research.

    boundary = source_boundary(assignment)
    message_records = {}
    events = list(assignment.events.filter(pk__gt=after).order_by("pk")[:100])
    return {
        "id": str(assignment.pk),
        "project": str(assignment.project_id),
        "capability": str(assignment.capability_id) if assignment.capability_id else None,
        "objective": assignment.specification["objective"],
        "state": assignment.state,
        "budget": allowance(assignment),
        "result": assignment.result,
        "serving": research_serving.describe(assignment),
        "qualifications": [
            {"id": str(a.pk), "state": a.state, "result": a.result}
            for a in ResearchAction.objects.filter(
                agent__assignment=assignment, tool="qualification"
            )
        ],
        "context": str(assignment.context_id),
        "deadline": assignment.deadline.isoformat(),
        "agents": [
            {
                **research_team.record(a),
                "notes": research_notes.record(a, boundary=boundary)["text"],
                "result": a.result,
            }
            for a in assignment.agents.order_by("created_at")
        ],
        "artifacts": [artifact_record(a) for a in assignment.artifacts.order_by("created_at")],
        "events": [
            {
                "id": e.pk,
                "kind": e.kind,
                "agent": str(e.agent_id) if e.agent_id else None,
                "payload": {
                    key: value
                    for key, value in research_notes.project_message(
                        assignment,
                        {"event": e.pk, **e.payload},
                        boundary=boundary,
                        cache=message_records,
                    ).items()
                    if key != "event"
                }
                if e.kind == "agent_message"
                else e.payload,
                "at": e.created_at.isoformat(),
            }
            for e in events
        ],
        "next_after": events[-1].pk if events else after,
    }


def observation_identity(assignment):
    return assignment.events.aggregate(latest=Max("pk"))["latest"] or 0


@transaction.atomic
def stop(assignment):
    # Serving imports the assignment authority and budget service.
    from overbae.services import research_qualification, research_serving

    assignment = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
    if assignment.state == "stopping":
        # Already asked: a run that waits on this one asks again at every pass.
        return assignment
    if (
        assignment.state not in TERMINAL
        or continues_admitted_work(assignment)
        or research_qualification.pending_actions([assignment.pk]).exists()
        or experiment_training.pending([assignment.pk])
        or research_serving.pending(assignment)
    ):
        assignment.state = "stopping"
        assignment.save(update_fields=["state"])
        assignment.agents.update(lease=None, lease_expires_at=None)
        event(assignment, "stop_requested", {})
        # Settled now, not at the next periodic pass.
        from overbae.tasks.research import settle_stop  # lazy: tasks import the agents

        identifier = str(assignment.pk)
        transaction.on_commit(lambda: settle_stop.delay(identifier), robust=True)
    return assignment


@transaction.atomic
def resume(assignment, *, request_key, instructions, max_model_calls=None, renewal_budget=None):
    from overbae.services import research_science  # Scientific admission imports Research.

    assignment = ResearchAssignment.objects.select_related("experiment_revision").get(
        pk=assignment.pk
    )
    experiment = research_science.experiment_for(assignment, lock=True)
    assignment = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
    amendment = {"instructions": instructions, "max_model_calls": max_model_calls}
    renewal = ResearchBudget.model_validate(renewal_budget) if renewal_budget is not None else None
    if renewal is not None:
        amendment["renewal_budget"] = renewal.model_dump(mode="json")
    identity = context_graph.fingerprint(amendment)
    if not authorized(assignment):
        raise InputValidationError("Research requires active project membership")
    if not isinstance(request_key, str) or not request_key.strip() or len(request_key) > 100:
        raise InputValidationError("Supply a continuation request key of up to 100 characters")
    prior = assignment.events.filter(kind="resumed", payload__request_key=request_key).first()
    if prior:
        if prior.payload["fingerprint"] != identity:
            raise InputValidationError("This continuation request key has different arguments")
        return assignment
    if (
        experiment is not None
        and research_requests.flow_bound(assignment)
        and ResearchAssignment.objects.filter(
            experiment_revision__experiment=experiment, execution__isnull=True
        )
        .exclude(pk=assignment.pk)
        .exclude(state__in=TERMINAL)
        .exists()
    ):
        raise InputValidationError("This experiment already has an active run")
    if assignment.execution_mandate.get("constraints", {}).get("historical_no_resume"):
        raise InputValidationError(
            "Historical assignments are retained for reporting; start a new execution window"
        )
    if assignment.state not in {
        "completed",
        "blocked",
        "unmet",
        "cancelled",
        "exhausted",
    } or not authorized(assignment):
        raise InputValidationError(
            "Only an authorized stopped investigation with remaining resources can resume"
        )
    if not instructions.strip() or len(instructions) > 8000:
        raise InputValidationError(
            "Supply a concise explanation of the resolved blocker or follow-up"
        )
    allowance_now = allowance(assignment)
    if renewal is None and (allowance_now["remaining_seconds"] < 60):
        raise InputValidationError(
            "The execution deadline has expired; start a new execution window"
        )
    previous_limit = assignment.specification["budget"]["max_model_calls"]
    previous_budget = assignment.specification["budget"]
    previous_deadline = assignment.deadline
    count = model_calls(assignment)
    limit = previous_limit if max_model_calls is None else max_model_calls
    if renewal is not None:
        if max_model_calls is not None:
            raise InputValidationError("Choose a renewed execution window or a call ceiling")
        require_credits(assignment.project_id)
        limit = max(previous_limit, count + renewal.max_model_calls)
        assignment.specification = {
            **assignment.specification,
            "budget": {**previous_budget, "max_seconds": renewal.max_seconds},
        }
        assignment.deadline = timezone.now() + timedelta(seconds=renewal.max_seconds)
    elif type(limit) is not int or not max(previous_limit, count + 1) <= limit <= 1000:
        raise InputValidationError("Supply a call ceiling above retained calls, up to 1000")
    assignment.specification = {
        **assignment.specification,
        "budget": {**assignment.specification["budget"], "max_model_calls": limit},
    }
    event(
        assignment,
        "resumed",
        {
            **amendment,
            "request_key": request_key,
            "fingerprint": identity,
            "previous_result": assignment.result,
            "previous_call_limit": previous_limit,
            "call_limit": limit,
            "retained_calls": count,
            "previous_budget": previous_budget,
            "previous_deadline": previous_deadline.isoformat(),
            "deadline": assignment.deadline.isoformat(),
        },
    )
    from overbae.services import research_qualification  # Qualification retains terminal owners.

    if research_qualification.pending_actions([assignment.pk]).exists():
        raise InputValidationError(
            "Settle independent qualification before resuming the investigation"
        )
    owner = assignment.agents.select_for_update().get(parent__isnull=True)
    if owner.actions.filter(state="running", tool__in=TOOLS).exists():
        raise InputValidationError("Settle in-flight actions before resuming the investigation")
    event(
        assignment,
        "executor_recovery",
        {
            "epoch": owner.execution_epoch,
            "launch": owner.checkpoint_manifest.get("launch"),
            "consecutive_failures": owner.checkpoint_manifest.get("consecutive_failures", 0),
        },
        owner,
    )
    owner.execution_epoch += 1
    owner.checkpoint_manifest = {
        **owner.checkpoint_manifest,
        "consecutive_failures": 0,
        "retired_launch": (owner.checkpoint_manifest.get("launch") or {}).get("name"),
    }
    research_team.discard_pending_tools(owner)
    research_notes.write(owner, "\nContinuation request: " + instructions, append=True)
    owner.state = "ready"
    owner.completed_at = None
    owner.lease = None
    owner.lease_expires_at = None
    owner.save(
        update_fields=[
            "state",
            "completed_at",
            "lease",
            "lease_expires_at",
            "execution_epoch",
            "checkpoint_manifest",
        ]
    )
    assignment.state = "running"
    assignment.completed_at = None
    assignment.result = {
        key: value
        for key, value in assignment.result.items()
        if key
        in {"selection_locked", "scientific_lock", "selected_trials", "qualification_artifact"}
    }
    assignment.save(update_fields=["state", "completed_at", "result", "specification", "deadline"])
    return assignment