feat: build on kept work by reference with sources_from (ADR-0004 phase 2)

A request names work the Orchestration engine kept instead of carrying its
files: a record or latest link from an earlier document of links (checked,
and of the request's tenant and Customer case), latest/<work>, or an
Execution's id. The kept files and the record that the work completed are
the agent's sources. Nothing starts, and the caller is told why, when the
reference does not resolve to completed work it may use.

A sequence's next agent is given what was kept of the one before, the same
way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 21:00:26 +01:00
parent 6d32bc696d
commit 1ec939f4fd
8 changed files with 430 additions and 19 deletions

View File

@@ -3,11 +3,12 @@ signer and the address a caller reaches them at, together."""
from __future__ import annotations
import json
import logging
import re
from collections.abc import Mapping
from typing import Any
from urllib.parse import quote
from urllib.parse import parse_qs, quote, unquote, urlsplit
from orchestration.links import Signer
from orchestration.store import Store
@@ -16,7 +17,11 @@ logger = logging.getLogger(__name__)
LOCAL_TENANT = "local" # what is kept for a caller that names no tenant
UNASSIGNED = "unassigned" # for a request that names no Customer case
# The Orchestration engine's own record that an Execution completed, sent with its
# files to the agent that builds on them.
RECORD = "execution.json"
_NOT_SLUG = re.compile(r"[^A-Za-z0-9._-]+")
_KEPT_PATH = re.compile(r"^/tenants/([^/]+)/cases/([^/]+)/(executions|latest)/([^/]+)$")
def _slug(value: Any, default: str) -> str:
@@ -68,6 +73,76 @@ class Delivery:
logger.exception("Could not keep %s Execution %s", work, execution_id)
return None
# --- building on what was kept (phase 2) ---------------------------------------
def resolve(self, reference: str, fields: Mapping[str, Any]) -> dict[str, Any]:
"""The kept Execution a request names in `sources_from`: a link from an
earlier document, `latest/<work>`, or an Execution's id in the request's
Customer case. Raises ValueError, saying why, for anything else."""
tenant, case = self.place(fields)
named_case = fields.get("customer_case")
if reference.startswith(("http://", "https://", "/")):
url = urlsplit(reference)
query = parse_qs(url.query)
exp, sig = (query.get(key, [None])[0] for key in ("exp", "sig"))
if not self.signer.verify(url.path, exp, sig):
raise ValueError("The link in sources_from is not valid.")
match = _KEPT_PATH.match(url.path)
if not match:
raise ValueError("The link in sources_from is not to kept work.")
tenant_of, case, kind, ident = match.groups()
if fields.get("tenant_id") and tenant_of != tenant:
raise ValueError("The link in sources_from is of another tenant.")
tenant = tenant_of
if named_case and _slug(named_case, UNASSIGNED) != case:
raise ValueError(
f"The work in sources_from is of the Customer case {case}, "
f"not {named_case}."
)
ident = unquote(ident)
record = (
self.store.record(tenant, case, ident)
if kind == "executions"
else self.store.latest(tenant, case, ident)
)
elif reference.startswith("latest/"):
work = reference.removeprefix("latest/")
record = self.store.latest(tenant, case, work)
if record is None:
raise ValueError(
f"No {work} work has completed in the Customer case {case}."
)
else:
record = self.store.record(tenant, case, reference)
if record is None:
raise ValueError(
f"Nothing is kept for {reference!r} in the Customer case {case}."
)
if record["status"] != "completed":
raise ValueError(
f"The {record['work']} work {record['execution_id']} ended "
f"{record['status']}; only work that completed is built on."
)
return record
def sources(self, record: Mapping[str, Any]) -> dict[str, str]:
"""A kept Execution as an agent's sources: its files, with the record that
it completed."""
files = self.store.files(
record["tenant"], record["customer_case"], record["execution_id"]
)
completion = {
"status": record["status"],
"customer_case": record["customer_case"]
if record["customer_case"] != UNASSIGNED
else None,
"execution_id": record["execution_id"],
"workflow_request": record["request"],
"work": record["work"],
}
files[RECORD] = json.dumps({k: v for k, v in completion.items() if v})
return files
# --- addresses -------------------------------------------------------------
@staticmethod