Coverage for src/governed_harness/plugins/client.py: 81%

44 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1from __future__ import annotations 

2 

3import json 

4import os 

5from dataclasses import dataclass 

6from pathlib import Path 

7 

8from governed_harness.domain.enums import ActorType, ResultStatus 

9from governed_harness.domain.models import Actor, CapabilityGrant 

10from governed_harness.plugins.protocol import PluginRequest, PluginResponse 

11from governed_harness.runtime import CancellationToken, CommandSpec, SafeProcessRunner 

12 

13 

14class PluginProtocolError(RuntimeError): 

15 pass 

16 

17 

18@dataclass(frozen=True) 

19class PluginInvocation: 

20 response: PluginResponse 

21 stdout: bytes 

22 stderr: bytes 

23 exit_code: int | None 

24 

25 

26class ExternalPluginClient: 

27 def __init__(self, workspace: Path, command: tuple[str, ...]) -> None: 

28 self.workspace = workspace.resolve(strict=True) 

29 self.command = command 

30 self.runner = SafeProcessRunner(self.workspace) 

31 

32 def invoke( 

33 self, 

34 request: PluginRequest, 

35 *, 

36 grants: list[CapabilityGrant], 

37 timeout_seconds: float = 60, 

38 cancellation: CancellationToken | None = None, 

39 ) -> PluginInvocation: 

40 actor = Actor(actor_type=ActorType.PLUGIN, actor_id="plugin.external") 

41 # Source-tree executions (tests, editable checkouts) need the package root 

42 # available to a Python plugin launched from an arbitrary workspace. The 

43 # variable is passed explicitly through the runner's allowlist rather than 

44 # inheriting the parent environment wholesale. Installed distributions do 

45 # not depend on this, but the additional path remains harmless. 

46 package_root = str(Path(__file__).resolve().parents[2]) 

47 existing_pythonpath = os.environ.get("PYTHONPATH") 

48 pythonpath = os.pathsep.join(part for part in (package_root, existing_pythonpath) if part) 

49 result = self.runner.run( 

50 CommandSpec( 

51 argv=self.command, 

52 cwd=self.workspace, 

53 timeout_seconds=timeout_seconds, 

54 allowed_environment=("PYTHONPATH",), 

55 stdin=(json.dumps(request.model_dump(mode="json", by_alias=True)) + "\n").encode( 

56 "utf-8" 

57 ), 

58 ), 

59 actor=actor, 

60 grants=grants, 

61 extra_env={"PYTHONPATH": pythonpath}, 

62 cancellation=cancellation, 

63 ) 

64 if result.status is ResultStatus.TIMED_OUT: 64 ↛ 65line 64 didn't jump to line 65 because the condition on line 64 was never true

65 raise PluginProtocolError("plugin timed out") 

66 if result.status is ResultStatus.CANCELLED: 66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true

67 raise PluginProtocolError("plugin was cancelled") 

68 if result.exit_code != 0: 68 ↛ 69line 68 didn't jump to line 69 because the condition on line 68 was never true

69 raise PluginProtocolError( 

70 f"plugin process failed with exit code {result.exit_code}: " 

71 f"{result.stderr.decode('utf-8', 'replace')[:500]}" 

72 ) 

73 lines = [ 

74 line for line in result.stdout.decode("utf-8", "replace").splitlines() if line.strip() 

75 ] 

76 if len(lines) != 1: 76 ↛ 77line 76 didn't jump to line 77 because the condition on line 76 was never true

77 raise PluginProtocolError("plugin stdout must contain exactly one JSON response line") 

78 try: 

79 response = PluginResponse.model_validate(json.loads(lines[0])) 

80 except Exception as error: 

81 raise PluginProtocolError(f"invalid plugin response: {error}") from error 

82 if response.request_id != request.request_id: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true

83 raise PluginProtocolError("plugin response requestId does not match request") 

84 return PluginInvocation(response, result.stdout, result.stderr, result.exit_code)