pact-harness 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. pact_harness-0.1.3/.gitignore +26 -0
  2. pact_harness-0.1.3/PKG-INFO +12 -0
  3. pact_harness-0.1.3/bin/pact +38 -0
  4. pact_harness-0.1.3/pyproject.toml +29 -0
  5. pact_harness-0.1.3/src/pact_harness/__init__.py +10 -0
  6. pact_harness-0.1.3/src/pact_harness/__main__.py +8 -0
  7. pact_harness-0.1.3/src/pact_harness/adapters/__init__.py +16 -0
  8. pact_harness-0.1.3/src/pact_harness/adapters/base.py +73 -0
  9. pact_harness-0.1.3/src/pact_harness/adapters/claude_code.py +303 -0
  10. pact_harness-0.1.3/src/pact_harness/adapters/dsh.py +175 -0
  11. pact_harness-0.1.3/src/pact_harness/adapters/portable.py +26 -0
  12. pact_harness-0.1.3/src/pact_harness/adapters/registry.py +59 -0
  13. pact_harness-0.1.3/src/pact_harness/capabilities.py +266 -0
  14. pact_harness-0.1.3/src/pact_harness/cli.py +1513 -0
  15. pact_harness-0.1.3/src/pact_harness/conformance/__init__.py +26 -0
  16. pact_harness-0.1.3/src/pact_harness/conformance/corpus.py +291 -0
  17. pact_harness-0.1.3/src/pact_harness/conformance/harvest.py +241 -0
  18. pact_harness-0.1.3/src/pact_harness/conformance/parity.py +309 -0
  19. pact_harness-0.1.3/src/pact_harness/conformance/suite.py +263 -0
  20. pact_harness-0.1.3/src/pact_harness/contract/__init__.py +65 -0
  21. pact_harness-0.1.3/src/pact_harness/contract/_util.py +113 -0
  22. pact_harness-0.1.3/src/pact_harness/contract/codec.py +83 -0
  23. pact_harness-0.1.3/src/pact_harness/contract/directives.py +438 -0
  24. pact_harness-0.1.3/src/pact_harness/contract/events.py +429 -0
  25. pact_harness-0.1.3/src/pact_harness/contract/schema/directive.v1.json +147 -0
  26. pact_harness-0.1.3/src/pact_harness/contract/schema/event.v1.json +169 -0
  27. pact_harness-0.1.3/src/pact_harness/dev.py +157 -0
  28. pact_harness-0.1.3/src/pact_harness/engine.py +267 -0
  29. pact_harness-0.1.3/src/pact_harness/errors.py +20 -0
  30. pact_harness-0.1.3/src/pact_harness/install/__init__.py +23 -0
  31. pact_harness-0.1.3/src/pact_harness/install/claude_code.py +189 -0
  32. pact_harness-0.1.3/src/pact_harness/install/dsh.py +408 -0
  33. pact_harness-0.1.3/src/pact_harness/install/generic.py +225 -0
  34. pact_harness-0.1.3/src/pact_harness/install/venv.py +121 -0
  35. pact_harness-0.1.3/src/pact_harness/journal.py +145 -0
  36. pact_harness-0.1.3/src/pact_harness/mcp/__init__.py +14 -0
  37. pact_harness-0.1.3/src/pact_harness/mcp/server.py +128 -0
  38. pact_harness-0.1.3/src/pact_harness/mcp/tools.py +373 -0
  39. pact_harness-0.1.3/src/pact_harness/memory.py +176 -0
  40. pact_harness-0.1.3/src/pact_harness/paths.py +324 -0
  41. pact_harness-0.1.3/src/pact_harness/playbook/__init__.py +24 -0
  42. pact_harness-0.1.3/src/pact_harness/playbook/compile.py +246 -0
  43. pact_harness-0.1.3/src/pact_harness/playbook/model.py +108 -0
  44. pact_harness-0.1.3/src/pact_harness/runtime/__init__.py +24 -0
  45. pact_harness-0.1.3/src/pact_harness/runtime/abi.py +148 -0
  46. pact_harness-0.1.3/src/pact_harness/runtime/decode.py +186 -0
  47. pact_harness-0.1.3/src/pact_harness/runtime/env.py +70 -0
  48. pact_harness-0.1.3/src/pact_harness/runtime/launch.py +96 -0
  49. pact_harness-0.1.3/src/pact_harness/runtime/registry.py +234 -0
  50. pact_harness-0.1.3/src/pact_harness/runtime/transport.py +92 -0
  51. pact_harness-0.1.3/src/pact_harness/runtime/vocabulary.py +83 -0
  52. pact_harness-0.1.3/src/pact_harness/runtime/warm.py +689 -0
  53. pact_harness-0.1.3/src/pact_harness/upstream/__init__.py +30 -0
  54. pact_harness-0.1.3/src/pact_harness/upstream/check.py +159 -0
  55. pact_harness-0.1.3/src/pact_harness/upstream/diff.py +272 -0
  56. pact_harness-0.1.3/src/pact_harness/upstream/inspect.py +320 -0
  57. pact_harness-0.1.3/src/pact_harness/upstream/verify.py +183 -0
  58. pact_harness-0.1.3/src/pact_harness/vendor.py +184 -0
  59. pact_harness-0.1.3/tests/conftest.py +10 -0
  60. pact_harness-0.1.3/tests/test_abi.py +197 -0
  61. pact_harness-0.1.3/tests/test_applicability.py +51 -0
  62. pact_harness-0.1.3/tests/test_capabilities.py +74 -0
  63. pact_harness-0.1.3/tests/test_claude_adapter.py +149 -0
  64. pact_harness-0.1.3/tests/test_claude_code_bridged.py +158 -0
  65. pact_harness-0.1.3/tests/test_cli.py +232 -0
  66. pact_harness-0.1.3/tests/test_cli_extra.py +180 -0
  67. pact_harness-0.1.3/tests/test_codec.py +47 -0
  68. pact_harness-0.1.3/tests/test_conformance.py +134 -0
  69. pact_harness-0.1.3/tests/test_contract_directives.py +105 -0
  70. pact_harness-0.1.3/tests/test_contract_events.py +121 -0
  71. pact_harness-0.1.3/tests/test_decode.py +213 -0
  72. pact_harness-0.1.3/tests/test_dev.py +141 -0
  73. pact_harness-0.1.3/tests/test_dsh_adapter.py +125 -0
  74. pact_harness-0.1.3/tests/test_engine.py +187 -0
  75. pact_harness-0.1.3/tests/test_harvest.py +137 -0
  76. pact_harness-0.1.3/tests/test_install_dsh.py +263 -0
  77. pact_harness-0.1.3/tests/test_install_generic.py +138 -0
  78. pact_harness-0.1.3/tests/test_install_venv.py +57 -0
  79. pact_harness-0.1.3/tests/test_journal.py +130 -0
  80. pact_harness-0.1.3/tests/test_mcp.py +218 -0
  81. pact_harness-0.1.3/tests/test_memory.py +142 -0
  82. pact_harness-0.1.3/tests/test_paths.py +143 -0
  83. pact_harness-0.1.3/tests/test_playbook.py +131 -0
  84. pact_harness-0.1.3/tests/test_registry.py +99 -0
  85. pact_harness-0.1.3/tests/test_upstream.py +453 -0
  86. pact_harness-0.1.3/tests/test_upstream_e2e.py +124 -0
  87. pact_harness-0.1.3/tests/test_vendor.py +78 -0
  88. pact_harness-0.1.3/tests/test_version.py +40 -0
  89. pact_harness-0.1.3/tests/test_warm.py +194 -0
@@ -0,0 +1,26 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ htmlcov/
12
+
13
+ # Node
14
+ node_modules/
15
+
16
+ # Local state
17
+ .pact/
18
+ *.log
19
+ .DS_Store
20
+
21
+ # The harness's own documentation is part of the repository. A global
22
+ # excludes file that ignores docs/ must not swallow the plan, the progress
23
+ # handover, or the measurements these decisions rest on.
24
+ !docs/
25
+ !docs/**
26
+ .model-lane/
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.5
2
+ Name: pact-harness
3
+ Version: 0.1.3
4
+ Summary: Platform-neutral harness that runs PACT on any agentic coding platform
5
+ Author: Michael Wojcik
6
+ License: MIT
7
+ Keywords: agents,claude-code,deepseek-harness,harness,orchestration,pact
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Requires-Python: >=3.12
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env bash
2
+ # pact: launch the harness with a suitable interpreter.
3
+ #
4
+ # The package requires Python 3.12. Resolving that here, before importing
5
+ # anything, is what keeps a machine whose default python3 is older from failing
6
+ # with a traceback instead of a clear message. Order matches the harness policy:
7
+ # PACT_PYTHON, then python3.12, then python3, then the interpreter DeepSeek
8
+ # Harness ships. Installed distributions use the console script generated by the
9
+ # package manager instead of this launcher.
10
+ set -euo pipefail
11
+
12
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ PKG_ROOT="$(dirname "$HERE")"
14
+ DSH_PYTHON="/Applications/DeepSeek Harness.app/Contents/Resources/runtime/primary-runtime/dependencies/python/bin/python3"
15
+
16
+ suitable() {
17
+ [ -n "$1" ] || return 1
18
+ command -v "$1" >/dev/null 2>&1 || [ -x "$1" ] || return 1
19
+ "$1" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] >= (3, 12) else 1)' >/dev/null 2>&1
20
+ }
21
+
22
+ PYTHON=""
23
+ for candidate in "${PACT_PYTHON:-}" "python3.12" "python3" "$DSH_PYTHON"; do
24
+ if suitable "$candidate"; then
25
+ PYTHON="$candidate"
26
+ break
27
+ fi
28
+ done
29
+
30
+ if [ -z "$PYTHON" ]; then
31
+ echo "pact: no Python 3.12 or later found." >&2
32
+ echo " Set PACT_PYTHON to a 3.12+ interpreter and retry." >&2
33
+ echo " Checked: PACT_PYTHON, python3.12, python3, the DeepSeek Harness interpreter." >&2
34
+ exit 127
35
+ fi
36
+
37
+ export PYTHONPATH="$PKG_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
38
+ exec "$PYTHON" -m pact_harness "$@"
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pact-harness"
7
+ version = "0.1.3"
8
+ description = "Platform-neutral harness that runs PACT on any agentic coding platform"
9
+ requires-python = ">=3.12"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Michael Wojcik" }]
12
+ keywords = ["pact", "agents", "orchestration", "harness", "claude-code", "deepseek-harness"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.12",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = []
20
+
21
+ [project.scripts]
22
+ pact = "pact_harness.cli:main"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/pact_harness"]
26
+
27
+ [tool.pytest.ini_options]
28
+ testpaths = ["tests"]
29
+ addopts = "-p no:cacheprovider"
@@ -0,0 +1,10 @@
1
+ """pact-harness: run PACT on any agentic coding platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.3"
6
+
7
+ #: Version of the harness contract this build speaks.
8
+ CONTRACT_VERSION = 1
9
+
10
+ __all__ = ["__version__", "CONTRACT_VERSION"]
@@ -0,0 +1,8 @@
1
+ """Allow python -m pact_harness."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
@@ -0,0 +1,16 @@
1
+ """Platform adapters: the only platform-specific code in the harness."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .base import AdapterContext, LegacyFrame, PlatformAdapter
6
+ from .registry import NotImplementedAdapterError, available_adapters, detect_adapter, get_adapter
7
+
8
+ __all__ = [
9
+ "AdapterContext",
10
+ "LegacyFrame",
11
+ "NotImplementedAdapterError",
12
+ "PlatformAdapter",
13
+ "available_adapters",
14
+ "detect_adapter",
15
+ "get_adapter",
16
+ ]
@@ -0,0 +1,73 @@
1
+ """The adapter contract.
2
+
3
+ An adapter does four things and nothing else:
4
+
5
+ normalize native event -> pact.event.v1
6
+ legacy_stdin pact.event.v1 -> the bytes a vendored hook reads on stdin
7
+ hook_env pact.event.v1 -> the child environment that hook runs under
8
+ render directives -> the platform's own decision shape
9
+
10
+ Everything a platform needs to know about PACT lives behind those four calls.
11
+ Everything PACT needs to know about a platform is its capability declaration and
12
+ its applicability table, both of which are data.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any, Mapping, Protocol, Sequence, runtime_checkable
21
+
22
+ from ..capabilities import CapabilitySet
23
+ from ..contract import Directive, EventV1
24
+ from ..runtime.env import HookEnv
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class AdapterContext:
29
+ """Everything an adapter needs that is not in the event itself."""
30
+
31
+ plugin_root: Path
32
+ state_root: Path
33
+ python: str = "python3"
34
+ harness_pid: int = field(default_factory=os.getpid)
35
+ base_env: Mapping[str, str] = field(default_factory=dict)
36
+
37
+ def env_values(self) -> Mapping[str, str]:
38
+ """The base environment to build a hook environment from."""
39
+ return self.base_env if self.base_env else os.environ
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class LegacyFrame:
44
+ """The stdin a vendored hook will read, plus how it was produced."""
45
+
46
+ data: bytes
47
+ source: str
48
+
49
+
50
+ @runtime_checkable
51
+ class PlatformAdapter(Protocol):
52
+ """One platform's translation layer."""
53
+
54
+ id: str
55
+ capabilities: CapabilitySet
56
+
57
+ def normalize(self, native: Mapping[str, Any]) -> EventV1:
58
+ """Turn one native event into the harness contract."""
59
+ ...
60
+
61
+ def legacy_stdin(self, event: EventV1) -> LegacyFrame:
62
+ """Produce the bytes the vendored hooks read."""
63
+ ...
64
+
65
+ def hook_env(self, event: EventV1, context: AdapterContext) -> HookEnv:
66
+ """Produce the child environment the hooks run under."""
67
+ ...
68
+
69
+ def render(
70
+ self, directives: Sequence[Directive], event: EventV1
71
+ ) -> list[Directive]:
72
+ """Adjust directives for this platform's decision model."""
73
+ ...
@@ -0,0 +1,303 @@
1
+ """The Claude Code adapter.
2
+
3
+ Claude Code is the platform PACT was written for, so this adapter is close to
4
+ an identity map. Its raw frame is preserved on the event and re-serialised for
5
+ the child: the hooks parse JSON, so semantic identity is what they depend on,
6
+ and keeping the original frame means a field this adapter does not understand
7
+ still reaches the hook that does.
8
+
9
+ The adapter claims the full capability set because it is the reference platform
10
+ -- PACT runs natively here today. The harness still reports what it can prove;
11
+ claiming T3 is not a claim about this build's testing, it is a statement that
12
+ the platform supplies every extension point.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime as _datetime
18
+ import hashlib
19
+ import json
20
+ from typing import Any, Mapping, Sequence
21
+
22
+ from ..capabilities import Capability, CapabilitySet
23
+ from ..contract import ActorRef, Directive, EventV1, SessionRef, TaskRef, TeamRef, ToolRef
24
+ from ..runtime.env import HookEnv, build_hook_env
25
+ from ..runtime.vocabulary import canonicalize, inject_target_for
26
+ from .base import AdapterContext, LegacyFrame
27
+
28
+ #: Claude's hook event names, mapped to harness kinds.
29
+ _EVENT_KIND: dict[str, str] = {
30
+ "SessionStart": "session.start",
31
+ "SessionEnd": "session.end",
32
+ "UserPromptSubmit": "prompt.submit",
33
+ "PreToolUse": "tool.pre",
34
+ "PostToolUse": "tool.post",
35
+ "PostToolUseFailure": "tool.fail",
36
+ "SubagentStart": "agent.start",
37
+ "SubagentStop": "agent.stop",
38
+ "TaskCompleted": "task.completed",
39
+ "PreCompact": "compact.pre",
40
+ "PostCompact": "compact.post",
41
+ "Stop": "turn.stop",
42
+ "TeammateIdle": "agent.idle",
43
+ }
44
+
45
+ #: The exact agent_type values that mean "team lead".
46
+ LEAD_AGENT_TYPES: frozenset[str] = frozenset(
47
+ {"PACT:pact-orchestrator", "pact-orchestrator"}
48
+ )
49
+
50
+ #: Frame fields copied into the event payload untouched.
51
+ _PAYLOAD_FIELDS = (
52
+ "source",
53
+ "compact_summary",
54
+ "last_assistant_message",
55
+ "background_tasks",
56
+ "session_crons",
57
+ "stop_hook_active",
58
+ "prompt",
59
+ )
60
+
61
+ _ID_ALLOWED = frozenset(
62
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
63
+ )
64
+
65
+
66
+ def sanitize_id(value: str, fallback: str = "unknown") -> str:
67
+ """Force a platform identifier into the contract's id alphabet."""
68
+ text = "".join(character if character in _ID_ALLOWED else "_" for character in value)
69
+ if not text:
70
+ text = fallback
71
+ if text[0] not in _ID_ALLOWED or not text[0].isalnum():
72
+ text = "x" + text
73
+ return text[:64]
74
+
75
+
76
+ def _now() -> str:
77
+ return _datetime.datetime.now(_datetime.timezone.utc).isoformat()
78
+
79
+
80
+ def _string(value: Any) -> str | None:
81
+ return value if isinstance(value, str) and value.strip() else None
82
+
83
+
84
+ def _object(value: Any) -> Mapping[str, Any] | None:
85
+ return value if isinstance(value, Mapping) else None
86
+
87
+
88
+ class ClaudeCodeAdapter:
89
+ """Translate Claude Code hook frames into the harness contract."""
90
+
91
+ id = "claude-code"
92
+
93
+ capabilities = CapabilitySet(
94
+ frozenset(
95
+ {
96
+ Capability.EVENT_SESSION_START,
97
+ Capability.EVENT_SESSION_END,
98
+ Capability.EVENT_PROMPT_SUBMIT,
99
+ Capability.EVENT_TOOL_PRE,
100
+ Capability.EVENT_TOOL_POST,
101
+ Capability.EVENT_TOOL_FAIL,
102
+ Capability.EVENT_AGENT_SPAWN_PRE,
103
+ Capability.EVENT_AGENT_START,
104
+ Capability.EVENT_AGENT_STOP,
105
+ Capability.EVENT_AGENT_IDLE,
106
+ Capability.EVENT_TASK_COMPLETED,
107
+ Capability.EVENT_COMPACT_PRE,
108
+ Capability.EVENT_COMPACT_POST,
109
+ Capability.EVENT_TURN_STOP,
110
+ Capability.CONTROL_TOOL_VETO,
111
+ Capability.CONTROL_TOOL_ASK,
112
+ Capability.CONTROL_TURN_BLOCK,
113
+ Capability.UI_CONTEXT_INJECT,
114
+ Capability.UI_NOTIFY,
115
+ Capability.UI_COMPACT_INSTRUCTIONS,
116
+ Capability.NATIVE_TASK_BOARD,
117
+ Capability.NATIVE_MESSAGING,
118
+ Capability.NATIVE_SKILLS,
119
+ Capability.NATIVE_COMMANDS,
120
+ Capability.NATIVE_SUBAGENTS_NAMED,
121
+ Capability.NATIVE_TRANSCRIPT,
122
+ Capability.NATIVE_INSTRUCTION_FILE,
123
+ }
124
+ )
125
+ )
126
+
127
+ # -- normalize --------------------------------------------------------
128
+
129
+ def normalize(self, native: Mapping[str, Any]) -> EventV1:
130
+ """Turn one Claude Code hook frame into an event."""
131
+ frame = dict(native)
132
+ hook_event = _string(frame.get("hook_event_name"))
133
+ if hook_event is None or hook_event not in _EVENT_KIND:
134
+ raise ValueError(f"unknown Claude Code hook_event_name: {hook_event!r}")
135
+
136
+ tool_name = _string(frame.get("tool_name"))
137
+ kind = _EVENT_KIND[hook_event]
138
+ payload: dict[str, Any] = {}
139
+ tool: ToolRef | None = None
140
+
141
+ if kind == "tool.pre" and tool_name == "Agent":
142
+ # A spawn request is its own kind: the gates distinguish "delegate
143
+ # to a specialist" from "run a tool", and collapsing them would
144
+ # apply tool gates to delegation.
145
+ kind = "agent.spawn.pre"
146
+ tool_input = _object(frame.get("tool_input")) or {}
147
+ for field in ("subagent_type", "name", "prompt", "description", "run_in_background"):
148
+ if field in tool_input:
149
+ payload[field] = tool_input[field]
150
+ elif kind in ("tool.pre", "tool.post", "tool.fail"):
151
+ tool_input = _object(frame.get("tool_input")) or {}
152
+ tool = ToolRef(
153
+ canonical=canonicalize(tool_name) or "Unknown",
154
+ native=tool_name or "Unknown",
155
+ input=tool_input,
156
+ result=_object(frame.get("tool_response")),
157
+ error=_object(frame.get("error")),
158
+ call_id=sanitize_id(frame["tool_use_id"]) if _string(frame.get("tool_use_id")) else None,
159
+ )
160
+
161
+ for field in _PAYLOAD_FIELDS:
162
+ if field in frame:
163
+ payload[field] = frame[field]
164
+
165
+ session = SessionRef(
166
+ id=sanitize_id(_string(frame.get("session_id")) or "session"),
167
+ cwd=_string(frame.get("cwd")) or ".",
168
+ project_dir=_string(frame.get("project_dir")),
169
+ transcript_path=_string(frame.get("transcript_path")),
170
+ )
171
+
172
+ agent_type = _string(frame.get("agent_type"))
173
+ if agent_type in LEAD_AGENT_TYPES:
174
+ role = "lead"
175
+ elif agent_type:
176
+ role = "teammate"
177
+ else:
178
+ role = "unknown"
179
+ actor = ActorRef(
180
+ role=role,
181
+ name=_string(frame.get("agent_name")),
182
+ id=sanitize_id(frame["agent_id"]) if _string(frame.get("agent_id")) else None,
183
+ type=agent_type,
184
+ )
185
+
186
+ team = TeamRef(name=_string(frame.get("team_name"))) if _string(frame.get("team_name")) else None
187
+
188
+ task: TaskRef | None = None
189
+ task_id = _string(frame.get("task_id"))
190
+ if kind == "task.completed":
191
+ task = TaskRef(
192
+ id=task_id or "task",
193
+ subject=_string(frame.get("task_subject")),
194
+ team_name=_string(frame.get("team_name")),
195
+ teammate_name=_string(frame.get("teammate_name")),
196
+ status=_string(frame.get("task_status")),
197
+ owner=_string(frame.get("task_owner")),
198
+ )
199
+
200
+ return EventV1(
201
+ id=self._event_id(frame, kind, session.id),
202
+ kind=kind,
203
+ at=_now(),
204
+ adapter=self.id,
205
+ session=session,
206
+ actor=actor,
207
+ team=team,
208
+ tool=tool,
209
+ task=task,
210
+ payload=payload,
211
+ raw=frame,
212
+ )
213
+
214
+ @staticmethod
215
+ def _event_id(frame: Mapping[str, Any], kind: str, session_id: str) -> str:
216
+ for field in ("tool_use_id", "prompt_id", "agent_id"):
217
+ value = _string(frame.get(field))
218
+ if value:
219
+ return sanitize_id(value)
220
+ digest = hashlib.sha256(
221
+ json.dumps(
222
+ [session_id, kind, frame.get("tool_name"), frame.get("tool_input")],
223
+ sort_keys=True,
224
+ default=str,
225
+ ).encode("utf-8")
226
+ ).hexdigest()[:16]
227
+ return "evt_" + digest
228
+
229
+ # -- legacy ABI -------------------------------------------------------
230
+
231
+ def legacy_stdin(self, event: EventV1) -> LegacyFrame:
232
+ """Re-emit the frame the hooks expect.
233
+
234
+ The raw frame is used whenever it is present. A synthetic event (one
235
+ built by a test or another adapter) falls back to synthesising the
236
+ fields the hooks read from the normalised event.
237
+ """
238
+ if event.raw:
239
+ data = json.dumps(event.raw, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
240
+ return LegacyFrame(data=data, source="raw-frame")
241
+ frame: dict[str, Any] = {
242
+ "hook_event_name": _KIND_TO_EVENT[event.kind],
243
+ "session_id": event.session.id,
244
+ "cwd": event.session.cwd,
245
+ "agent_type": event.actor.type,
246
+ "agent_name": event.actor.name,
247
+ "agent_id": event.actor.id,
248
+ "team_name": event.team.name if event.team else None,
249
+ "transcript_path": event.session.transcript_path,
250
+ }
251
+ if event.tool is not None:
252
+ frame["tool_name"] = event.tool.native
253
+ frame["tool_input"] = dict(event.tool.input)
254
+ if event.tool.result is not None:
255
+ frame["tool_response"] = dict(event.tool.result)
256
+ if event.tool.error is not None:
257
+ frame["error"] = dict(event.tool.error)
258
+ frame["tool_use_id"] = event.tool.call_id
259
+ if event.task is not None:
260
+ frame["task_id"] = event.task.id
261
+ frame["task_subject"] = event.task.subject
262
+ frame["team_name"] = event.task.team_name
263
+ frame["teammate_name"] = event.task.teammate_name
264
+ frame.update(dict(event.payload))
265
+ clean = {key: value for key, value in frame.items() if value is not None}
266
+ data = json.dumps(clean, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
267
+ return LegacyFrame(data=data, source="synthesized")
268
+
269
+ def hook_env(self, event: EventV1, context: AdapterContext) -> HookEnv:
270
+ """Build the child environment for one hook invocation."""
271
+ raw_session = _string((event.raw or {}).get("session_id")) or event.session.id
272
+ project_dir = _string((event.raw or {}).get("cwd")) or event.session.cwd
273
+ return build_hook_env(
274
+ state_root=context.state_root,
275
+ plugin_root=context.plugin_root,
276
+ session_id=raw_session,
277
+ project_dir=project_dir,
278
+ harness_pid=context.harness_pid,
279
+ base_env=context.env_values(),
280
+ )
281
+
282
+ def render(self, directives: Sequence[Directive], event: EventV1) -> list[Directive]:
283
+ """Claude Code accepts the decoded directives unchanged."""
284
+ return list(directives)
285
+
286
+
287
+ #: The inverse mapping, for synthesising a frame from an event.
288
+ _KIND_TO_EVENT: dict[str, str] = {
289
+ "session.start": "SessionStart",
290
+ "session.end": "SessionEnd",
291
+ "prompt.submit": "UserPromptSubmit",
292
+ "tool.pre": "PreToolUse",
293
+ "tool.post": "PostToolUse",
294
+ "tool.fail": "PostToolUseFailure",
295
+ "agent.spawn.pre": "PreToolUse",
296
+ "agent.start": "SubagentStart",
297
+ "agent.stop": "SubagentStop",
298
+ "agent.idle": "TeammateIdle",
299
+ "task.completed": "TaskCompleted",
300
+ "compact.pre": "PreCompact",
301
+ "compact.post": "PostCompact",
302
+ "turn.stop": "Stop",
303
+ }