From b81475d99f90e9e54e2a6e365a36af96fc79bccd Mon Sep 17 00:00:00 2001 From: Nivas Date: Wed, 2 Dec 2026 15:18:27 +0000 Subject: [PATCH] Add wait_for_plan_implementation to sync and async knowledge clients --- README.md | 18 + proofline/__init__.py | 12 +- proofline/_mcp.py | 6 +- proofline/knowledge.py | 376 +++++++++++++++ tests/test_plan_implementation.py | 762 ++++++++++++++++++++++++++++++ 5 files changed, 1172 insertions(+), 2 deletions(-) create mode 100644 tests/test_plan_implementation.py diff --git a/README.md b/README.md index 250fb32e..f4f3ff3d 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,7 @@ Both clients expose typed methods under `client.knowledge` over Proofline's stat - `get_plan(plan_id)` - `start_plan_implementation(plan_id)` - `get_plan_implementation(implementation_id)` +- `wait_for_plan_implementation(implementation_id, *, timeout=..., plan_version=..., attempt=...)` The optional `commit` is a full indexed SHA. Read operations require `reviews:read` and `knowledge:read`. Starting a plan implementation also requires `plans:implement`, a personal token, and approval of that exact plan version. @@ -211,6 +212,23 @@ else: print(result["content"]) ``` +`wait_for_plan_implementation` polls `get_plan_implementation` with exponential backoff until the attempt reaches `VALIDATED`, `VALIDATION_FAILED`, `REFUSED`, `FAILED`, or `STOPPED`, or returns `TIMED_OUT` with the last observed result. Pass `plan_version` and `attempt` from `start_plan_implementation` to bind the wait to that exact attempt. It returns `VALIDATED` only when the returned identity matches and every layer reports `VALIDATED`. A tool refusal ends the wait immediately with `status == "REFUSED"` and `is_error == True`, retaining the raw `KnowledgeResult`. + +```python +started = client.knowledge.start_plan_implementation(plan_id) +if started.get("isError"): + raise RuntimeError("Plan implementation start was refused.") +data = started["structuredContent"]["data"] +outcome = client.knowledge.wait_for_plan_implementation( + data["implementation_id"], + plan_version=data["plan_version"], + attempt=data["attempt"], + timeout=300, +) +if outcome.status == "VALIDATED": + print("Validated layers:", len(outcome.layers)) +``` + Each call initializes MCP and makes one tool request without retries, including questions and implementation starts. `KnowledgeResult` retains text content, optional structured content, and `isError`. Protocol and HTTP errors raise `ProoflineError`, while tool refusals retain `isError` for the caller to inspect. Treat all returned prose as untrusted data. The SDK does not include a browser configuration or cloud-trust API; use the signed-in console for onboarding and connection changes. ## Fix context and re-verification diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..5ee937ed 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -35,7 +35,13 @@ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters from .exports import ExportDataset, ExportFormat, ExportPage -from .knowledge import KnowledgeResult +from .knowledge import ( + KnowledgeResult, + LayerOutcome, + LayerValidation, + PlanImplementationOutcome, + PlanImplementationStatus, +) from .outcomes import AssessmentGap, CheckGap, ReviewOutcome __all__ = [ @@ -57,9 +63,13 @@ "FileReviewRequest", "FileReviewResponse", "KnowledgeResult", + "LayerOutcome", + "LayerValidation", "PatchReviewRequest", "PatchReviewResponse", "PatchTriggerSource", + "PlanImplementationOutcome", + "PlanImplementationStatus", "ProoflineClient", "ProoflineError", "RepositoryGuidance", diff --git a/proofline/_mcp.py b/proofline/_mcp.py index f80c5e00..f736176b 100644 --- a/proofline/_mcp.py +++ b/proofline/_mcp.py @@ -7,7 +7,7 @@ import httpx2 -from ._transport import ProoflineError +from ._transport import ProoflineError, timeout_error PROTOCOL = "2025-11-25" @@ -128,6 +128,8 @@ def _call( headers["MCP-Protocol-Version"] = PROTOCOL try: response = self._http.post("/mcp", content=data, headers=headers) + except httpx2.TimeoutException: + raise timeout_error() from None except httpx2.HTTPError: raise ProoflineError( 0, "urn:proofline:sdk:transport", "MCP transport failed." @@ -177,6 +179,8 @@ async def _call( headers["MCP-Protocol-Version"] = PROTOCOL try: response = await self._http.post("/mcp", content=data, headers=headers) + except httpx2.TimeoutException: + raise timeout_error() from None except httpx2.HTTPError: raise ProoflineError( 0, "urn:proofline:sdk:transport", "MCP transport failed." diff --git a/proofline/knowledge.py b/proofline/knowledge.py index 2a301cf5..77833685 100644 --- a/proofline/knowledge.py +++ b/proofline/knowledge.py @@ -1,6 +1,260 @@ """Published knowledge operations through the scoped MCP server.""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from time import sleep +from typing import Literal, cast +from uuid import UUID + +from anyio import sleep as async_sleep + +from . import _transport from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools, _repository +from ._transport import ProoflineError + +PlanImplementationStatus = Literal[ + "VALIDATED", + "VALIDATION_FAILED", + "REFUSED", + "FAILED", + "STOPPED", + "INCOMPLETE", + "TIMED_OUT", +] + +_PENDING_STATUSES = frozenset(("PENDING", "RUNNING")) +_TERMINAL_FAILURE_STATUSES = frozenset(("VALIDATION_FAILED", "REFUSED", "FAILED", "STOPPED")) + + +@dataclass(frozen=True) +class LayerValidation: + step: str = field(repr=False) + status: str + + +@dataclass(frozen=True) +class LayerOutcome: + layer: int | str = field(repr=False) + status: str + validations: tuple[LayerValidation, ...] = field(default=(), repr=False) + + +@dataclass(frozen=True) +class PlanImplementationOutcome: + status: PlanImplementationStatus + implementation_id: UUID + plan_version: int | None = None + attempt: int | None = None + recorded_status: str | None = None + layers: tuple[LayerOutcome, ...] = field(default=(), repr=False) + result: KnowledgeResult | None = field(default=None, repr=False) + is_error: bool = False + error_code: str | None = field(default=None, repr=False) + reason: str | None = None + + +def _parse_implementation_id(value: str | UUID) -> UUID: + if isinstance(value, UUID): + return value + if isinstance(value, str) and value == value.strip(): + try: + return UUID(value) + except ValueError: + pass + raise ValueError("The implementation_id must be a valid UUID.") + + +def _validate_wait_args( + timeout: float, + plan_version: int | None, + attempt: int | None, +) -> None: + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout < 0 + ): + raise ValueError( + "The plan implementation timeout must be a finite nonnegative number of seconds." + ) + if plan_version is not None and ( + isinstance(plan_version, bool) or not isinstance(plan_version, int) or plan_version < 1 + ): + raise ValueError("plan_version must be a positive integer.") + if attempt is not None and ( + isinstance(attempt, bool) or not isinstance(attempt, int) or attempt < 1 + ): + raise ValueError("attempt must be a positive integer.") + + +def _invalid_implementation() -> ProoflineError: + return ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "The plan implementation has invalid identity or layer metadata.", + ) + + +def _optional_positive_int(value: object) -> int | None: + if value is None: + return None + if type(value) is not int or value < 1: + raise _invalid_implementation() + return value + + +def _parse_layers(raw_layers: object) -> tuple[LayerOutcome, ...]: + if not isinstance(raw_layers, list): + raise _invalid_implementation() + parsed: list[LayerOutcome] = [] + for item in raw_layers: + if not isinstance(item, dict): + raise _invalid_implementation() + layer_id = item.get("layer") + if not (type(layer_id) is int or (isinstance(layer_id, str) and bool(layer_id))): + raise _invalid_implementation() + layer_status = item.get("status") + if not isinstance(layer_status, str) or not layer_status: + raise _invalid_implementation() + raw_validations = item.get("validations") + validations: list[LayerValidation] = [] + if raw_validations is not None: + if not isinstance(raw_validations, list): + raise _invalid_implementation() + for entry in raw_validations: + if not isinstance(entry, dict): + raise _invalid_implementation() + step = entry.get("step") + step_status = entry.get("status") + if ( + not isinstance(step, str) + or not step + or not isinstance(step_status, str) + or not step_status + ): + raise _invalid_implementation() + validations.append(LayerValidation(step=step, status=step_status)) + parsed.append( + LayerOutcome(layer=layer_id, status=layer_status, validations=tuple(validations)) + ) + return tuple(parsed) + + +def _plan_implementation_outcome( + result: KnowledgeResult | None, + implementation_id: UUID, + forced: PlanImplementationStatus | None = None, + *, + plan_version: int | None = None, + attempt: int | None = None, +) -> PlanImplementationOutcome | None: + if result is None: + return PlanImplementationOutcome( + forced or "INCOMPLETE", + implementation_id, + reason="No plan implementation result is available.", + ) + if result.get("isError") is True: + error_code: str | None = None + structured = result.get("structuredContent") + if isinstance(structured, dict): + err = structured.get("error") + if isinstance(err, dict) and isinstance(err.get("code"), str) and err["code"]: + error_code = err["code"] + return PlanImplementationOutcome( + status="REFUSED", + implementation_id=implementation_id, + result=result, + is_error=True, + error_code=error_code, + reason="The plan implementation read was refused.", + ) + structured = result.get("structuredContent") + if ( + not isinstance(structured, dict) + or structured.get("ok") is not True + or not isinstance(structured.get("data"), dict) + ): + raise _invalid_implementation() + data = structured["data"] + raw_id = data.get("id") + if not isinstance(raw_id, str) or raw_id != raw_id.strip(): + raise _invalid_implementation() + try: + recorded_id = UUID(raw_id) + except ValueError: + raise _invalid_implementation() from None + if recorded_id != implementation_id: + raise _invalid_implementation() + raw_status = data.get("status") + if not isinstance(raw_status, str) or not raw_status: + raise _invalid_implementation() + recorded_version = _optional_positive_int(data.get("plan_version")) + recorded_attempt = _optional_positive_int(data.get("attempt")) + raw_layers = data.get("layers") + layers_present = "layers" in data and raw_layers is not None + layers = _parse_layers(raw_layers) if layers_present else () + + mismatch_reason: str | None = None + if ( + plan_version is not None + and recorded_version is not None + and recorded_version != plan_version + ): + mismatch_reason = "The implementation belongs to another plan version." + elif attempt is not None and recorded_attempt is not None and recorded_attempt != attempt: + mismatch_reason = "The implementation belongs to another attempt." + + unavailable_reason: str | None = None + if plan_version is not None and recorded_version is None: + unavailable_reason = "The implementation names no plan version." + elif attempt is not None and recorded_attempt is None: + unavailable_reason = "The implementation names no attempt number." + + reason: str | None = None + if forced is not None: + status: PlanImplementationStatus = forced + reason = mismatch_reason or unavailable_reason + elif mismatch_reason is not None: + # Plan version and attempt number are immutable on a recorded attempt. + status = "INCOMPLETE" + reason = mismatch_reason + elif raw_status in _PENDING_STATUSES: + return None + elif raw_status in _TERMINAL_FAILURE_STATUSES: + status = cast(PlanImplementationStatus, raw_status) + reason = unavailable_reason + elif raw_status == "VALIDATED": + if unavailable_reason is not None: + status = "INCOMPLETE" + reason = unavailable_reason + elif not layers_present: + status = "INCOMPLETE" + reason = "Implementation layer metadata is unavailable." + elif not layers or any(layer.status != "VALIDATED" for layer in layers): + status = "INCOMPLETE" + reason = "Not every implementation layer is validated." + else: + status = "VALIDATED" + else: + status = "INCOMPLETE" + reason = unavailable_reason or "The implementation reported an unrecognized status." + + return PlanImplementationOutcome( + status=status, + implementation_id=implementation_id, + plan_version=recorded_version, + attempt=recorded_attempt, + recorded_status=raw_status, + layers=layers, + result=result, + is_error=False, + error_code=None, + reason=reason, + ) class KnowledgeClient(McpTools): @@ -67,6 +321,67 @@ def get_plan_implementation( organization_id=organization_id, ) + def wait_for_plan_implementation( + self, + implementation_id: str | UUID, + *, + timeout: float = 300, + plan_version: int | None = None, + attempt: int | None = None, + organization_id: str | None = None, + ) -> PlanImplementationOutcome: + """Wait for a plan implementation attempt to end or return TIMED_OUT. + + Each poll makes one MCP read without retries. Tool refusals end the wait + with status="REFUSED" and is_error=True while retaining the raw result. + plan_version and attempt hold the outcome to the started attempt; a + mismatch ends the wait on that read and is never VALIDATED. + """ + parsed_id = _parse_implementation_id(implementation_id) + _validate_wait_args(timeout, plan_version, attempt) + last: KnowledgeResult | None = None + interval = 5.0 + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + last = self.get_plan_implementation( + str(parsed_id), organization_id=organization_id + ) + except ProoflineError as error: + if ( + timeout > 0 + and error.status == 0 + and error.type == "urn:proofline:sdk:timeout" + and (_transport.remaining() or 0) <= 0 + ): + break + raise + evaluated = _plan_implementation_outcome( + last, + parsed_id, + plan_version=plan_version, + attempt=attempt, + ) + if evaluated is not None: + return evaluated + budget = _transport.remaining() + if timeout == 0 or not budget: + break + sleep(min(interval, budget)) + interval = min(60.0, interval * 2) + timed_out = _plan_implementation_outcome( + last, + parsed_id, + "TIMED_OUT", + plan_version=plan_version, + attempt=attempt, + ) + return timed_out or PlanImplementationOutcome( + "TIMED_OUT", + parsed_id, + reason="No plan implementation result is available.", + ) + class AsyncKnowledgeClient(AsyncMcpTools): async def list_wiki_pages( @@ -133,3 +448,64 @@ async def get_plan_implementation( {"implementation_id": implementation_id}, organization_id=organization_id, ) + + async def wait_for_plan_implementation( + self, + implementation_id: str | UUID, + *, + timeout: float = 300, + plan_version: int | None = None, + attempt: int | None = None, + organization_id: str | None = None, + ) -> PlanImplementationOutcome: + """Wait for a plan implementation attempt to end or return TIMED_OUT. + + Each poll makes one MCP read without retries. Tool refusals end the wait + with status="REFUSED" and is_error=True while retaining the raw result. + plan_version and attempt hold the outcome to the started attempt; a + mismatch ends the wait on that read and is never VALIDATED. + """ + parsed_id = _parse_implementation_id(implementation_id) + _validate_wait_args(timeout, plan_version, attempt) + last: KnowledgeResult | None = None + interval = 5.0 + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + last = await self.get_plan_implementation( + str(parsed_id), organization_id=organization_id + ) + except ProoflineError as error: + if ( + timeout > 0 + and error.status == 0 + and error.type == "urn:proofline:sdk:timeout" + and (_transport.remaining() or 0) <= 0 + ): + break + raise + evaluated = _plan_implementation_outcome( + last, + parsed_id, + plan_version=plan_version, + attempt=attempt, + ) + if evaluated is not None: + return evaluated + budget = _transport.remaining() + if timeout == 0 or not budget: + break + await async_sleep(min(interval, budget)) + interval = min(60.0, interval * 2) + timed_out = _plan_implementation_outcome( + last, + parsed_id, + "TIMED_OUT", + plan_version=plan_version, + attempt=attempt, + ) + return timed_out or PlanImplementationOutcome( + "TIMED_OUT", + parsed_id, + reason="No plan implementation result is available.", + ) diff --git a/tests/test_plan_implementation.py b/tests/test_plan_implementation.py new file mode 100644 index 00000000..2e9dd548 --- /dev/null +++ b/tests/test_plan_implementation.py @@ -0,0 +1,762 @@ +from __future__ import annotations + +import asyncio +import inspect +import json +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from typing import Any +from uuid import UUID + +import anyio +import pytest +from pydantic import SecretStr + +from proofline import ( + AsyncProoflineClient, + LayerOutcome, + LayerValidation, + PlanImplementationOutcome, + ProoflineClient, + ProoflineError, + _sync_http, + _transport, +) +from proofline import knowledge as knowledge_module + +from .fixtures import ORG, PRIVATE, REVIEW, TOKEN +from .http_server import Reply, Request, Server + +Client = ProoflineClient | AsyncProoflineClient +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) +IMPLEMENTATION = UUID("00000000-0000-4000-8000-000000000010") +OTHER_IMPLEMENTATION = UUID("00000000-0000-4000-8000-000000000011") + + +@asynccontextmanager +async def session(mode: str, url: str, **kwargs: Any) -> AsyncIterator[Client]: + if mode == "sync": + with ProoflineClient(SecretStr(TOKEN), base_url=url, **kwargs) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url, **kwargs) as async_client: + yield async_client + + +async def wait_call( + client: Client, + implementation_id: str | UUID, + **kwargs: Any, +) -> PlanImplementationOutcome: + result = client.knowledge.wait_for_plan_implementation(implementation_id, **kwargs) + return await result if inspect.isawaitable(result) else result + + +class Clock: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.now = 100.0 + self.delays: list[float] = [] + monkeypatch.setattr(_transport, "monotonic", lambda: self.now) + monkeypatch.setattr(_sync_http, "monotonic", lambda: self.now) + monkeypatch.setattr(knowledge_module, "sleep", self.sleep) + monkeypatch.setattr(_transport, "sleep", self.sleep) + monkeypatch.setattr(knowledge_module, "async_sleep", self.async_sleep) + monkeypatch.setattr(_transport, "async_sleep", self.async_sleep) + + def sleep(self, delay: float) -> None: + self.delays.append(delay) + self.now += delay + + async def async_sleep(self, delay: float) -> None: + self.sleep(delay) + await asyncio.sleep(0) + + +def implementation_result( + status: str = "VALIDATED", + *, + implementation_id: str = str(IMPLEMENTATION), + plan_version: int | None = 2, + attempt: int | None = 1, + layers: list[dict[str, Any]] | None = None, + include_layers: bool = True, +) -> dict[str, Any]: + data: dict[str, Any] = { + "id": implementation_id, + "status": status, + } + if plan_version is not None: + data["plan_version"] = plan_version + if attempt is not None: + data["attempt"] = attempt + if include_layers: + data["layers"] = ( + layers + if layers is not None + else [ + { + "layer": 1, + "status": "VALIDATED" if status == "VALIDATED" else status, + "validations": [ + {"step": "build", "status": "PASSED"}, + {"step": "test", "status": "PASSED"}, + ], + } + ] + ) + return { + "isError": False, + "content": [{"type": "text", "text": json.dumps({"ok": True, "data": data})}], + "structuredContent": {"ok": True, "data": data}, + } + + +def mcp_responder( + handler: Callable[[dict[str, Any], int], Reply], +) -> Callable[[Request, int], Reply]: + tool_calls = 0 + + def respond(request: Request, index: int) -> Reply: + nonlocal tool_calls + body = json.loads(request.body) + assert request.path == "/mcp" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + if body["method"] == "initialize": + return Reply( + body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} + ) + assert request.headers["MCP-Protocol-Version"] == "2025-11-25" + if body["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + call_index = tool_calls + tool_calls += 1 + return handler(body["params"], call_index) + + return respond + + +@MODES +async def test_wait_polls_through_pending_and_running_to_validated( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + seen_params: list[dict[str, Any]] = [] + responses = [ + implementation_result("PENDING", layers=[]), + implementation_result( + "RUNNING", + layers=[{"layer": 1, "status": "VALIDATED", "validations": []}], + ), + implementation_result( + "VALIDATED", + layers=[ + { + "layer": 1, + "status": "VALIDATED", + "validations": [{"step": "build", "status": "PASSED"}], + }, + { + "layer": "Layer 2: Application", + "status": "VALIDATED", + "validations": [{"step": "pytest", "status": "PASSED"}], + }, + ], + ), + ] + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + seen_params.append(params) + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": responses[call_index]}) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + result = await wait_call( + client, + str(IMPLEMENTATION).upper(), + plan_version=2, + attempt=1, + organization_id=str(ORG), + ) + assert result.status == "VALIDATED" + assert result.implementation_id == IMPLEMENTATION + assert result.plan_version == 2 + assert result.attempt == 1 + assert result.recorded_status == "VALIDATED" + assert result.is_error is False + assert result.error_code is None + assert result.reason is None + assert result.result == responses[2] + assert result.layers == ( + LayerOutcome( + layer=1, + status="VALIDATED", + validations=(LayerValidation(step="build", status="PASSED"),), + ), + LayerOutcome( + layer="Layer 2: Application", + status="VALIDATED", + validations=(LayerValidation(step="pytest", status="PASSED"),), + ), + ) + assert clock.delays == [5.0, 10.0] + expected_call = { + "name": "get_plan_implementation", + "arguments": { + "implementation_id": str(IMPLEMENTATION), + "organization_id": str(ORG), + }, + } + assert seen_params == [expected_call, expected_call, expected_call] + + +@MODES +@pytest.mark.parametrize("terminal", ["VALIDATION_FAILED", "REFUSED", "FAILED", "STOPPED"]) +async def test_wait_returns_terminal_non_validated_statuses_without_repolling( + mode: str, terminal: str +) -> None: + calls = 0 + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + nonlocal calls + calls += 1 + return Reply( + body={ + "jsonrpc": "2.0", + "id": 2, + "result": implementation_result( + terminal, + layers=[ + { + "layer": 1, + "status": terminal, + "validations": [{"step": "test", "status": "FAILED"}], + } + ], + ), + } + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION) + assert calls == 1 + assert result.status == terminal + assert result.recorded_status == terminal + assert result.is_error is False + assert result.reason is None + assert len(result.layers) == 1 + assert result.layers[0].status == terminal + + +@MODES +@pytest.mark.parametrize( + ("kwargs", "expected_reason"), + [ + ({"include_layers": False}, "Implementation layer metadata is unavailable."), + ({"layers": []}, "Not every implementation layer is validated."), + ( + { + "layers": [ + {"layer": 1, "status": "VALIDATED", "validations": []}, + {"layer": 2, "status": "VALIDATION_FAILED", "validations": []}, + ] + }, + "Not every implementation layer is validated.", + ), + ( + { + "layers": [ + {"layer": 1, "status": "RUNNING", "validations": []}, + ] + }, + "Not every implementation layer is validated.", + ), + ], +) +async def test_validated_requires_every_layer_to_be_validated( + mode: str, kwargs: dict[str, Any], expected_reason: str +) -> None: + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + return Reply( + body={"jsonrpc": "2.0", "id": 2, "result": implementation_result("VALIDATED", **kwargs)} + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION) + assert result.status == "INCOMPLETE" + assert result.recorded_status == "VALIDATED" + assert result.reason == expected_reason + + +@MODES +async def test_unrecognized_status_fails_closed_as_incomplete(mode: str) -> None: + calls = 0 + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + nonlocal calls + calls += 1 + return Reply( + body={"jsonrpc": "2.0", "id": 2, "result": implementation_result("SUPERSEDED")} + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION) + assert calls == 1 + assert result.status == "INCOMPLETE" + assert result.recorded_status == "SUPERSEDED" + assert result.reason == "The implementation reported an unrecognized status." + + +@MODES +@pytest.mark.parametrize("recorded_status", ["PENDING", "RUNNING", "VALIDATED", "FAILED"]) +async def test_pinned_plan_version_or_attempt_mismatch_ends_wait_immediately( + mode: str, recorded_status: str +) -> None: + calls = 0 + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + nonlocal calls + calls += 1 + return Reply( + body={ + "jsonrpc": "2.0", + "id": 2, + "result": implementation_result(recorded_status, plan_version=3, attempt=2), + } + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + version_mismatch = await wait_call(client, IMPLEMENTATION, plan_version=2) + attempt_mismatch = await wait_call(client, IMPLEMENTATION, plan_version=3, attempt=1) + assert calls == 2 + assert version_mismatch.status == "INCOMPLETE" + assert version_mismatch.plan_version == 3 + assert version_mismatch.reason == "The implementation belongs to another plan version." + assert attempt_mismatch.status == "INCOMPLETE" + assert attempt_mismatch.attempt == 2 + assert attempt_mismatch.reason == "The implementation belongs to another attempt." + + +@MODES +async def test_pinned_plan_version_or_attempt_missing_never_validates( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + responses = [ + implementation_result("RUNNING", plan_version=None, attempt=1), + implementation_result("VALIDATED", plan_version=None, attempt=1), + ] + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": responses[call_index]}) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION, plan_version=2) + assert result.status == "INCOMPLETE" + assert result.recorded_status == "VALIDATED" + assert result.reason == "The implementation names no plan version." + + with Server( + mcp_responder( + lambda params, idx: Reply( + body={ + "jsonrpc": "2.0", + "id": 2, + "result": implementation_result("VALIDATED", plan_version=2, attempt=None), + } + ) + ) + ) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION, plan_version=2, attempt=1) + assert result.status == "INCOMPLETE" + assert result.reason == "The implementation names no attempt number." + + +@MODES +@pytest.mark.parametrize( + ("tool_reply", "expected_code"), + [ + ( + { + "isError": True, + "content": [{"type": "text", "text": "NOT_AUTHORIZED"}], + "structuredContent": { + "ok": False, + "error": { + "code": "NOT_AUTHORIZED", + "message": "Missing knowledge:read scope.", + "retryable": False, + }, + }, + }, + "NOT_AUTHORIZED", + ), + ( + { + "isError": True, + "content": [{"type": "text", "text": "RESOURCE_NOT_FOUND"}], + }, + None, + ), + ], +) +async def test_tool_refusal_stops_immediately_and_preserves_is_error( + mode: str, tool_reply: dict[str, Any], expected_code: str | None +) -> None: + calls = 0 + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + nonlocal calls + calls += 1 + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": tool_reply}) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION) + assert calls == 1 + assert result.status == "REFUSED" + assert result.is_error is True + assert result.error_code == expected_code + assert result.result == tool_reply + assert result.reason == "The plan implementation read was refused." + + +@MODES +@pytest.mark.parametrize("status_code", [429, 503]) +async def test_http_errors_propagate_without_retry(mode: str, status_code: int) -> None: + calls = 0 + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + nonlocal calls + calls += 1 + return Reply( + status=status_code, + body={"detail": "temporarily unavailable"}, + headers={"Retry-After": "0"}, + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as caught: + await wait_call(client, IMPLEMENTATION) + assert caught.value.status == status_code + assert calls == 1 + + +@MODES +async def test_polling_backoff_cap_and_timeout_retain_last_result( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + pending = implementation_result("RUNNING", layers=[{"layer": 1, "status": "RUNNING"}]) + + with Server( + mcp_responder( + lambda params, idx: Reply(body={"jsonrpc": "2.0", "id": 2, "result": pending}) + ) + ) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION, timeout=200) + assert result.status == "TIMED_OUT" + assert result.recorded_status == "RUNNING" + assert result.result == pending + assert result.layers == (LayerOutcome(layer=1, status="RUNNING"),) + assert clock.delays == [5.0, 10.0, 20.0, 40.0, 60.0, 60.0, 5.0] + + +@MODES +async def test_zero_timeout_reads_once(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + calls = 0 + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + nonlocal calls + calls += 1 + status = "PENDING" if call_index == 0 else "VALIDATED" + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": implementation_result(status)}) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + first = await wait_call(client, IMPLEMENTATION, timeout=0) + second = await wait_call(client, IMPLEMENTATION, timeout=0) + assert calls == 2 + assert clock.delays == [] + assert first.status == "TIMED_OUT" + assert first.recorded_status == "PENDING" + assert second.status == "VALIDATED" + + +@MODES +@pytest.mark.parametrize("wrong_id", [False, True]) +async def test_wait_evaluates_result_decoded_at_the_deadline( + mode: str, wrong_id: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + payload = implementation_result( + "RUNNING" if wrong_id else "VALIDATED", + implementation_id=str(OTHER_IMPLEMENTATION if wrong_id else IMPLEMENTATION), + ) + sync_get = knowledge_module.KnowledgeClient.get_plan_implementation + async_get = knowledge_module.AsyncKnowledgeClient.get_plan_implementation + + def finish_sync( + client: knowledge_module.KnowledgeClient, + implementation_id: str, + *, + organization_id: str | None = None, + ) -> knowledge_module.KnowledgeResult: + decoded = sync_get(client, implementation_id, organization_id=organization_id) + clock.now += 10.0 + return decoded + + async def finish_async( + client: knowledge_module.AsyncKnowledgeClient, + implementation_id: str, + *, + organization_id: str | None = None, + ) -> knowledge_module.KnowledgeResult: + decoded = await async_get(client, implementation_id, organization_id=organization_id) + clock.now += 10.0 + return decoded + + monkeypatch.setattr(knowledge_module.KnowledgeClient, "get_plan_implementation", finish_sync) + monkeypatch.setattr( + knowledge_module.AsyncKnowledgeClient, "get_plan_implementation", finish_async + ) + + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": payload}) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url) as client: + if wrong_id: + with pytest.raises(ProoflineError) as raised: + await wait_call(client, IMPLEMENTATION, timeout=10) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + else: + result = await wait_call(client, IMPLEMENTATION, timeout=10) + assert result.status == "VALIDATED" + assert clock.delays == [] + + +@MODES +async def test_wait_deadline_expiring_in_flight_returns_timed_out(mode: str) -> None: + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + return Reply( + body={"jsonrpc": "2.0", "id": 2, "result": implementation_result("RUNNING")}, + header_pause=0.25, + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url, timeout=5) as client: + result = await wait_call(client, IMPLEMENTATION, timeout=0.08) + assert result.status == "TIMED_OUT" + assert result.result is None + assert result.reason == "No plan implementation result is available." + + +@MODES +async def test_per_request_timeout_before_wait_deadline_raises_proofline_error(mode: str) -> None: + def on_tool(params: dict[str, Any], call_index: int) -> Reply: + return Reply( + body={"jsonrpc": "2.0", "id": 2, "result": implementation_result("RUNNING")}, + header_pause=0.25, + ) + + with Server(mcp_responder(on_tool)) as server: + async with session(mode, server.url, timeout=0.06) as client: + with pytest.raises(ProoflineError) as caught: + await wait_call(client, IMPLEMENTATION, timeout=10) + assert caught.value.status == 0 + assert caught.value.type == "urn:proofline:sdk:timeout" + + +@pytest.mark.parametrize("backend", ["asyncio", "trio"]) +def test_async_wait_runs_on_asyncio_and_trio(backend: str, monkeypatch: pytest.MonkeyPatch) -> None: + delays: list[float] = [] + now = 100.0 + monkeypatch.setattr(_transport, "monotonic", lambda: now) + + async def fake_async_sleep(delay: float) -> None: + nonlocal now + delays.append(delay) + now += delay + await anyio.lowlevel.checkpoint() + + monkeypatch.setattr(knowledge_module, "async_sleep", fake_async_sleep) + responses = [ + implementation_result("PENDING", layers=[]), + implementation_result("VALIDATED"), + ] + + async def run() -> PlanImplementationOutcome: + def on_tool(params: dict[str, Any], idx: int) -> Reply: + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": responses[idx]}) + + with Server(mcp_responder(on_tool)) as server: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=server.url) as client: + return await client.knowledge.wait_for_plan_implementation( + IMPLEMENTATION, plan_version=2, attempt=1 + ) + + result = anyio.run(run, backend=backend) + assert result.status == "VALIDATED" + assert delays == [5.0] + + +@MODES +@pytest.mark.parametrize( + ("impl_id", "kwargs"), + [ + ("", {}), + ("not-a-uuid", {}), + (f" {IMPLEMENTATION}", {}), + (IMPLEMENTATION, {"timeout": -1}), + (IMPLEMENTATION, {"timeout": float("nan")}), + (IMPLEMENTATION, {"timeout": float("inf")}), + (IMPLEMENTATION, {"timeout": True}), + (IMPLEMENTATION, {"timeout": False}), + (IMPLEMENTATION, {"plan_version": 0}), + (IMPLEMENTATION, {"plan_version": -1}), + (IMPLEMENTATION, {"plan_version": True}), + (IMPLEMENTATION, {"attempt": 0}), + (IMPLEMENTATION, {"attempt": False}), + ], +) +async def test_invalid_arguments_fail_before_any_request( + mode: str, impl_id: Any, kwargs: dict[str, Any] +) -> None: + with Server(lambda request, index: Reply(body={})) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError): + await wait_call(client, impl_id, **kwargs) + assert server.requests == [] + + +@MODES +@pytest.mark.parametrize( + "bad_result", + [ + {"content": [{"type": "text", "text": "missing structured"}]}, + { + "isError": False, + "content": [{"type": "text", "text": "ok false"}], + "structuredContent": {"ok": False, "error": {"code": "INTERNAL"}}, + }, + { + "isError": False, + "content": [{"type": "text", "text": "wrong id"}], + "structuredContent": { + "ok": True, + "data": {"id": str(OTHER_IMPLEMENTATION), "status": "VALIDATED", "layers": []}, + }, + }, + { + "isError": False, + "content": [{"type": "text", "text": "bad id"}], + "structuredContent": { + "ok": True, + "data": {"id": "not-a-uuid", "status": "VALIDATED", "layers": []}, + }, + }, + { + "isError": False, + "content": [{"type": "text", "text": "missing status"}], + "structuredContent": { + "ok": True, + "data": {"id": str(IMPLEMENTATION), "status": ""}, + }, + }, + { + "isError": False, + "content": [{"type": "text", "text": "bool plan_version"}], + "structuredContent": { + "ok": True, + "data": {"id": str(IMPLEMENTATION), "status": "RUNNING", "plan_version": True}, + }, + }, + { + "isError": False, + "content": [{"type": "text", "text": "non-list layers"}], + "structuredContent": { + "ok": True, + "data": {"id": str(IMPLEMENTATION), "status": "VALIDATED", "layers": "bad"}, + }, + }, + { + "isError": False, + "content": [{"type": "text", "text": "bool layer id"}], + "structuredContent": { + "ok": True, + "data": { + "id": str(IMPLEMENTATION), + "status": "VALIDATED", + "layers": [{"layer": True, "status": "VALIDATED"}], + }, + }, + }, + { + "isError": False, + "content": [{"type": "text", "text": "bad validations"}], + "structuredContent": { + "ok": True, + "data": { + "id": str(IMPLEMENTATION), + "status": "VALIDATED", + "layers": [ + { + "layer": 1, + "status": "VALIDATED", + "validations": [{"step": "", "status": "PASSED"}], + } + ], + }, + }, + }, + ], +) +async def test_malformed_implementation_payloads_raise_invalid_response( + mode: str, bad_result: dict[str, Any] +) -> None: + with Server( + mcp_responder( + lambda params, idx: Reply(body={"jsonrpc": "2.0", "id": 2, "result": bad_result}) + ) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as caught: + await wait_call(client, IMPLEMENTATION) + assert caught.value.status == 0 + assert caught.value.type == "urn:proofline:sdk:invalid-response" + + +@MODES +async def test_outcome_repr_omits_untrusted_text_and_tokens(mode: str) -> None: + payload = implementation_result( + "VALIDATED", + layers=[ + { + "layer": f"untrusted-layer-{PRIVATE}", + "status": "VALIDATED", + "validations": [{"step": f"untrusted-step-{TOKEN}", "status": "PASSED"}], + } + ], + ) + with Server( + mcp_responder( + lambda params, idx: Reply(body={"jsonrpc": "2.0", "id": 2, "result": payload}) + ) + ) as server: + async with session(mode, server.url) as client: + result = await wait_call(client, IMPLEMENTATION) + rendered = repr(result) + assert PRIVATE not in rendered + assert TOKEN not in rendered + assert repr(result.layers[0]).find(PRIVATE) == -1 + assert repr(result.layers[0].validations[0]).find(TOKEN) == -1 + assert str(REVIEW) not in rendered