Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1 @@
| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, signed (A2A 1.0 section 8.4, EdDSA JWS by the Seal key that signs receipts; no server if the key can't be opened), JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c, 2026-11-30, sandbox server with `--a2a-tck-scenarios`): 121 automated checks passed, 0 failed, 142 skipped (gRPC, push, cancel, auth scenarios), MUST 78.7% because the TCK counts skipped and manual checks as not passed ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)); a second implementation, the A2A JavaScript SDK 1.3.0, ran a workflow and verified a second key's handoff over JSON-RPC and HTTP+JSON and checked the card signature with independent JWS and RFC 8785 libraries, all on one computer ([benchmark/a2a_interop](packages/flow/benchmark/a2a_interop/README.md)); the card signature verified by the `a2a-sdk` verifier and refused when changed, unpinned or relabelled (the TCK leaves signing to manual checks) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) |
| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, signed (A2A 1.0 section 8.4, EdDSA JWS by the Seal key that signs receipts; no server if the key can't be opened), JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, the card opened through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a strict-mode sealed run folder (stubbed Flow process, real sealed set and receipt hook) whose receipt and card go through the bridge's `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c, 2026-11-30, sandbox server with `--a2a-tck-scenarios`): 121 automated checks passed, 0 failed, 142 skipped (gRPC, push, cancel, auth scenarios), MUST 78.7% because the TCK counts skipped and manual checks as not passed ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)); a second implementation, the A2A JavaScript SDK 1.3.0, ran a workflow and verified a second key's handoff over JSON-RPC and HTTP+JSON and checked the card signature with independent JWS and RFC 8785 libraries, all on one computer ([benchmark/a2a_interop](packages/flow/benchmark/a2a_interop/README.md)); the card signature verified by the `a2a-sdk` verifier and refused when changed, unpinned or relabelled (the TCK leaves signing to manual checks) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) |
105 changes: 105 additions & 0 deletions packages/agent/tests/test_handoff_at_rest_bridge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""``get_handoff`` through the bridge for a run encrypted at rest (strict mode).

The Flow process is stubbed, but it leaves what a strict run leaves: a sealed
run folder whose report is ciphertext on disk, and the receipt written by the
same hook the CLI calls after a run (``receipt_after_run``).
"""

from __future__ import annotations

import json
from pathlib import Path

import pytest

pytest.importorskip("cryptography")

from conftest import FlowCliStub # noqa: E402
from test_handoff_e2e import WRITE_REPORT_RESULTS, _registry # noqa: E402

import openadapt_agent.runner as runner_mod # noqa: E402
from openadapt_flow import at_rest, crypto, sealed_set # noqa: E402
from openadapt_flow import handoff as h # noqa: E402
from openadapt_flow.agent.bridge import AgentBridge # noqa: E402
from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402
from openadapt_flow.offline_seal import signer_for # noqa: E402
from openadapt_flow.receipt_record import receipt_after_run # noqa: E402


class SealedRunStub(FlowCliStub):
"""`openadapt-flow run` under strict at rest, stubbed: a sealed run folder."""

def __init__(self, env: dict[str, str], **kwargs):
super().__init__(**kwargs)
self.env = env
self.notes: list[str | None] = []

def __call__(self, cmd, *args, **kwargs):
import subprocess

self.calls.append(list(cmd))
run_dir = Path(cmd[cmd.index("--run-dir") + 1])
with sealed_set.writing(run_dir, "run", crypto.resolve_key(None)):
sealed_set.write_text(run_dir / "report.json", json.dumps(self.report))
self.notes.append(receipt_after_run(run_dir, env=self.env))
return subprocess.CompletedProcess(cmd, self.exit_code, stdout="", stderr="")


@pytest.fixture()
def strict_env(tmp_path, monkeypatch):
for name in (
at_rest.OPT_OUT_ENV,
at_rest.ENCRYPT_ENV,
crypto.ENV_KEY,
sealed_set.RECORDING_ENV_KEY,
"OPENADAPT_POLICY",
"OPENADAPT_RECEIPT",
"OPENADAPT_SEAL_KEY",
):
monkeypatch.delenv(name, raising=False)
env = {
"OPENADAPT_SEAL_HOME": str(tmp_path / "seal-home"),
at_rest.HOME_ENV: str(tmp_path / "at-rest-home"),
at_rest.MODE_ENV: "strict",
}
for key, value in env.items():
monkeypatch.setenv(key, value)
at_rest._reset_for_tests()
yield env
at_rest._reset_for_tests()


@pytest.mark.parametrize("public", [False, True])
def test_a_strict_run_hands_off_its_receipt_through_the_bridge(
monkeypatch, bundles_root, runner_config, success_report, strict_env, public
):
signer = signer_for(Path(strict_env["OPENADAPT_SEAL_HOME"]))
report = dict(
success_report,
results=WRITE_REPORT_RESULTS,
started_at="2026-11-21T01:02:03Z",
change_ledger=[],
)
stub = SealedRunStub(strict_env, exit_code=0, report=report)
monkeypatch.setattr(runner_mod, "_run_flow_process", stub)
bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production")
bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer)

workflow = next(iter(bridge.catalog))
result = bridge.dispatch(
"run_workflow",
{"workflow": workflow, "inputs": {"note": "x"}, "request_id": "strict-0001"},
)
assert stub.notes and str(stub.notes[0]).startswith("receipt:"), stub.notes
run_dir = Path(runner_config.runs_dir) / result["run_id"]
assert sealed_set.is_sealed(run_dir)
assert not (run_dir / "report.json").exists()

doc = bridge.dispatch("get_handoff", {"run_id": result["run_id"], "public": public})
verdict = h.verify_handoff(doc, _registry(signer))
assert verdict.ok, verdict.to_dict()
assert verdict.payload["bound"] is True
# The receipt says what the run's report says; never upgraded.
assert verdict.outcome == "VERIFIED"
assert doc["payload"]["content"]["outcome"] == result["outcome"]
sealed_set.open_set(run_dir).verify_all()
37 changes: 30 additions & 7 deletions packages/agent/tests/test_handoff_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import asyncio
import base64
import contextlib
import hashlib
import json
import socket
Expand Down Expand Up @@ -56,6 +57,20 @@
"ok": True,
"effect_verified": True,
"postconditions_ok": True,
# A write is confirmed only with a declared effect contract and its
# evidence (as in Flow's tests/test_handoff.py); without them the
# receipt says UNKNOWN (effect_not_declared).
"effect_contract_hashes": ["sha256:" + "a" * 64],
"effect_evidence": [
{
"effect_contract_hash": "sha256:" + "a" * 64,
"substrate": "api",
"initial_verdict": "confirmed",
"final_verdict": "confirmed",
"observed_effect": "present",
"verification_tier": 1,
}
],
},
]

Expand Down Expand Up @@ -91,7 +106,13 @@ def signer():

@pytest.fixture()
def bridge(monkeypatch, bundles_root, runner_config, success_report, signer):
report = dict(success_report, results=WRITE_REPORT_RESULTS, started_at="2026-11-21T01:02:03Z")
report = dict(
success_report,
results=WRITE_REPORT_RESULTS,
started_at="2026-11-21T01:02:03Z",
# No change ledger means unknown write coverage: the receipt says UNKNOWN.
change_ledger=[],
)
monkeypatch.setattr(
runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=0, report=report)
)
Expand All @@ -108,6 +129,13 @@ def _free_port() -> int:

@pytest.fixture()
def a2a_url(bridge):
with _serve_a2a(bridge) as url:
yield url


@contextlib.contextmanager
def _serve_a2a(bridge):
"""Serve ``bridge`` over A2A on a free local port; yield its base URL."""
config = a2a_server.A2AConfig(port=_free_port())
server = uvicorn.Server(
uvicorn.Config(
Expand Down Expand Up @@ -241,12 +269,7 @@ async def scenario():
handoff, good, tampered, swapped = asyncio.run(scenario())
assert good["integrity"] == "intact"
assert good["signer_roles"] == ["this_computer"]
# The stubbed run has no read-back, so its receipt says UNKNOWN (receipts
# say VERIFIED only on a level 3 or 4 read). The verdict copies the
# receipt's outcome and never upgrades it.
statement = json.loads(base64.b64decode(handoff["receipt"]["payload"]))
assert statement["predicate"]["outcome"] == "UNKNOWN"
assert good["outcome"] == "UNKNOWN"
assert good["outcome"] == "VERIFIED"
assert good["what_this_proves"][0] == h.WHAT_A_SIGNATURE_PROVES
assert tampered["integrity"] == "refused" and tampered["reason"] == "bad_signature"
assert good["payload"]["bound"] is True
Expand Down
218 changes: 218 additions & 0 deletions packages/agent/tests/test_handoff_sandbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
"""Sandbox runs never carry a receipt, over MCP or A2A, and say why.

A ``record/run/v1`` receipt has no field that marks a run as synthetic, and a
receiver's own key registry, not the signed statement, decides what a key
means. A receipt for a sandbox run, signed with this computer's key, would
read like proof about a real system, so ``get_handoff`` refuses sandbox runs
before it reads any run folder.
"""

from __future__ import annotations

import asyncio
import json
from pathlib import Path

import pytest

pytest.importorskip("a2a.server.routes")
pytest.importorskip("uvicorn")
pytest.importorskip("cryptography")

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402
from openadapt_types import receipt as r # noqa: E402
from test_handoff_e2e import ( # noqa: E402
WRITE_REPORT_RESULTS,
_registry,
_result_from,
_send,
_serve_a2a,
)

from openadapt_agent.bridge import AgentBridge, BridgeError # noqa: E402
from openadapt_agent.runner import RunnerConfig # noqa: E402
from openadapt_agent.sandbox import SANDBOX_WORKFLOW, SandboxEngine # noqa: E402
from openadapt_flow import handoff as h # noqa: E402
from openadapt_flow.agent.handoff_tools import ( # noqa: E402
NO_PROVENANCE,
SANDBOX_NO_RECEIPT,
HandoffTools,
)
from openadapt_flow.receipt_record import write_receipt_record # noqa: E402
from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402


@pytest.fixture()
def signer():
return SoftwareSigner(Ed25519PrivateKey.generate(), "generated")


@pytest.fixture()
def sandbox_bridge(tmp_path, signer):
runs = tmp_path / "sandbox"
engine = SandboxEngine(runs, engine="simulated")
bridge = AgentBridge(None, RunnerConfig(runs_dir=runs), sandbox=engine, mode="sandbox")
bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer)
yield bridge
engine.close()


def _run(bridge, request_id):
return bridge.dispatch(
"run_workflow",
{
"workflow": SANDBOX_WORKFLOW,
"inputs": {"note": "Synthetic follow-up"},
"request_id": request_id,
},
)


def _plant_receipt(run_dir: Path, signer) -> None:
"""A real signed receipt in a sandbox run's folder (no sandbox path writes one)."""
run_dir.mkdir(parents=True, exist_ok=True)
report = {
"workflow_name": SANDBOX_WORKFLOW,
"execution_outcome": "VERIFIED",
"run_id": run_dir.name,
"started_at": "2026-11-21T01:02:03Z",
"change_ledger": [],
"results": WRITE_REPORT_RESULTS,
}
(run_dir / "report.json").write_text(json.dumps(report))
write_receipt_record(run_dir, signer=signer, flow_version="3.4.0")
assert (run_dir / r.RECEIPT_FILE).is_file()


@pytest.mark.parametrize("public", [False, True])
def test_a_sandbox_run_never_carries_a_receipt_and_says_why(sandbox_bridge, signer, public):
result = _run(sandbox_bridge, "sandbox-handoff-1")
assert result["mode"] == "sandbox" and result["outcome"] == "done"
# Even with a real signed receipt in the run's folder, the result never
# travels with one.
_plant_receipt(Path(sandbox_bridge.runner_config.runs_dir) / result["run_id"], signer)
assert "get_handoff" in [spec.name for spec in sandbox_bridge.list_tool_specs()]
with pytest.raises(BridgeError) as caught:
sandbox_bridge.dispatch("get_handoff", {"run_id": result["run_id"], "public": public})
assert SANDBOX_NO_RECEIPT in str(caught.value)


def test_a2a_sandbox_artifact_says_why_it_has_no_receipt(sandbox_bridge):
with _serve_a2a(sandbox_bridge) as url:
task = asyncio.run(
_send(
url,
{
"skill": SANDBOX_WORKFLOW,
"inputs": {"note": "Synthetic follow-up"},
"request_id": "sandbox-a2a-0001",
},
)
)
assert _result_from(task)["mode"] == "sandbox"
parts = [part for artifact in task.artifacts for part in artifact.parts]
assert not [p for p in parts if p.HasField("raw") and p.media_type == h.MEDIA_TYPE]
texts = [p.text for p in parts if p.HasField("text")]
assert any(SANDBOX_NO_RECEIPT in text for text in texts), texts


# -- provenance comes from the stored record, not the server's current mode --


def _production_bridge(bundles_root, runs, signer):
bridge = AgentBridge(
bundles_root, RunnerConfig(runs_dir=runs), allow_run=True, mode="production"
)
bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer)
return bridge


def _orphan(bridge, run_id, mode):
"""A run record left running by a process that is gone (pid None)."""
store = bridge.service.store
record = store.new_record(
request_id=f"req-{run_id}", workflow=SANDBOX_WORKFLOW, mode="sandbox", run_id=run_id
)
if mode is None:
del record["mode"]
else:
record["mode"] = mode
record["pid"] = None
store.write(record)
return record


@pytest.mark.parametrize("public", [False, True])
def test_a_finished_sandbox_run_reopened_under_production_never_carries_a_receipt(
sandbox_bridge, bundles_root, signer, public
):
result = _run(sandbox_bridge, "sandbox-restart-1")
runs = Path(sandbox_bridge.runner_config.runs_dir)
_plant_receipt(runs / result["run_id"], signer)
production = _production_bridge(bundles_root, runs, signer)
reopened = production.dispatch("get_run", {"run_id": result["run_id"], "wait_seconds": 0})
assert reopened["mode"] == "sandbox"
with pytest.raises(BridgeError) as caught:
production.dispatch("get_handoff", {"run_id": result["run_id"], "public": public})
assert SANDBOX_NO_RECEIPT in str(caught.value)


def test_an_interrupted_sandbox_run_recovered_under_production_keeps_its_mode(
bundles_root, tmp_path, signer
):
runs = tmp_path / "runs"
production = _production_bridge(bundles_root, runs, signer)
run_id = "run-sandbox-orphan-1"
_orphan(production, run_id, "sandbox")
# A genuine receipt for this run's own report sits in its folder.
_plant_receipt(runs / run_id, signer)
# Restarted under production: get_run rebuilds the interrupted result
# from the stored record, which ran in sandbox mode.
result = production.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0})
assert result["reason"] == "interrupted" and result["mode"] == "sandbox"
stored = production.service.store.read(run_id)
assert stored["state"] == "finished" and stored["mode"] == "sandbox"
assert stored["result"]["mode"] == "sandbox"
with pytest.raises(BridgeError) as caught:
production.dispatch("get_handoff", {"run_id": run_id})
assert SANDBOX_NO_RECEIPT in str(caught.value)


@pytest.mark.parametrize("mode", [None, "staging"])
def test_a_run_record_without_a_known_mode_never_carries_a_receipt(
bundles_root, tmp_path, signer, mode
):
runs = tmp_path / "runs"
production = _production_bridge(bundles_root, runs, signer)
run_id = "run-no-provenance-1"
_orphan(production, run_id, mode)
_plant_receipt(runs / run_id, signer)
production.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0})
stored = production.service.store.read(run_id)
assert stored["state"] == "finished" and stored.get("mode") == mode
with pytest.raises(BridgeError) as caught:
production.dispatch("get_handoff", {"run_id": run_id})
assert NO_PROVENANCE in str(caught.value)


@pytest.mark.parametrize(
"record",
[
None,
{"state": "running", "mode": "production"},
{"state": "finished", "mode": "attended"}, # disagrees with the result
{"state": "finished"},
],
)
def test_get_handoff_needs_a_finished_record_whose_mode_matches(tmp_path, signer, record):
run = tmp_path / "run-direct-1"
_plant_receipt(run, signer)
with pytest.raises(BridgeError) as caught:
HandoffTools(registry=_registry(signer), signer=signer).get(
run.name,
public=False,
result_for=lambda _run_id: {"outcome": "done", "mode": "production"},
run_dir_for=lambda _run_id: run,
record_for=lambda _run_id: record,
)
assert NO_PROVENANCE in str(caught.value)
Loading
Loading