test_phase_two_agent_tools.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. from __future__ import annotations
  2. import base64
  3. from collections.abc import Mapping
  4. from types import SimpleNamespace
  5. from typing import Any
  6. import pytest
  7. from agent import ToolRegistry
  8. from agent.orchestration import ArtifactRef, ValidationVerdict
  9. from script_build_host.domain.artifacts import ArtifactState
  10. from script_build_host.domain.errors import ArtifactNotFound, ProtocolViolation
  11. from script_build_host.tools.contracts import AttemptManifest
  12. from script_build_host.tools.gateway import LegacyScriptToolGateway, RetrievalResult
  13. from script_build_host.tools.registry import register_script_tools
  14. class _CandidateTools:
  15. def __init__(self, artifact_ref: ArtifactRef) -> None:
  16. self.artifact_ref = artifact_ref
  17. self.last_payload: dict[str, Any] | None = None
  18. self.last_context: dict[str, Any] | None = None
  19. self.images: list[dict[str, Any]] = []
  20. async def resolve_attempt_manifest(self, *, context: Mapping[str, Any]) -> AttemptManifest:
  21. self.last_context = dict(context)
  22. return AttemptManifest(
  23. artifact_ref=self.artifact_ref,
  24. scope_ref="script-build://scopes/body",
  25. )
  26. async def create_script_paragraph(
  27. self, *, payload: Mapping[str, Any], context: Mapping[str, Any]
  28. ) -> dict[str, int]:
  29. self.last_payload = dict(payload)
  30. self.last_context = dict(context)
  31. return {"paragraph_id": 7}
  32. async def view_frozen_images(
  33. self,
  34. *,
  35. raw_artifact_refs: list[str],
  36. context: Mapping[str, Any],
  37. ) -> list[dict[str, Any]]:
  38. self.last_payload = {"raw_artifact_refs": raw_artifact_refs}
  39. self.last_context = dict(context)
  40. return self.images
  41. class _TaskStore:
  42. def __init__(self, task: Any) -> None:
  43. self.task = task
  44. async def load(self, _root_trace_id: str) -> Any:
  45. return SimpleNamespace(
  46. tasks={"task-1": self.task},
  47. attempts={"attempt-a": SimpleNamespace(attempt_id="attempt-a", task_id="task-1")},
  48. )
  49. class _ArtifactStore:
  50. def __init__(self, ref: ArtifactRef) -> None:
  51. self.ref = ref
  52. async def get(self, _root_trace_id: str, _snapshot_id: str) -> Any:
  53. return SimpleNamespace(attempt_id="attempt-a", artifact_refs=[self.ref], evidence_refs=[])
  54. class _Bindings:
  55. async def get_by_root(self, _root_trace_id: str) -> Any:
  56. return SimpleNamespace(script_build_id=9, input_snapshot_id=3)
  57. class _BudgetGuard:
  58. def __init__(self, error: Exception | None = None) -> None:
  59. self.error = error
  60. self.calls: list[tuple[str, str, str]] = []
  61. async def ensure_tool_budget(self, *, root_trace_id: str, task_id: str, entry: str) -> None:
  62. self.calls.append((root_trace_id, task_id, entry))
  63. if self.error is not None:
  64. raise self.error
  65. class _BusinessArtifacts:
  66. def __init__(self, ref: ArtifactRef) -> None:
  67. self.ref = ref
  68. async def read_by_ref(
  69. self,
  70. ref: ArtifactRef,
  71. *,
  72. script_build_id: int,
  73. task_id: str,
  74. attempt_id: str,
  75. ) -> Any:
  76. assert (ref, script_build_id, task_id, attempt_id) == (
  77. self.ref,
  78. 9,
  79. "task-1",
  80. "attempt-a",
  81. )
  82. return SimpleNamespace(
  83. artifact_type=SimpleNamespace(value=ref.kind),
  84. canonical_sha256=ref.digest,
  85. state=SimpleNamespace(value="frozen"),
  86. )
  87. class _RetrievalArtifacts:
  88. def __init__(self) -> None:
  89. self.version: Any | None = None
  90. async def get_by_attempt(self, **_owners: Any) -> Any:
  91. if self.version is None:
  92. raise ArtifactNotFound()
  93. return self.version
  94. async def freeze(self, *, artifact: Any, **owners: Any) -> tuple[Any, ArtifactRef]:
  95. ref = ArtifactRef(
  96. "script-build://artifact-versions/8",
  97. "evidence",
  98. "8",
  99. "sha256:" + "b" * 64,
  100. )
  101. self.version = SimpleNamespace(
  102. artifact_version_id=8,
  103. state=ArtifactState.FROZEN,
  104. artifact=artifact,
  105. )
  106. return self.version, ref
  107. class _CountingRetrievalAdapter:
  108. def __init__(self) -> None:
  109. self.calls = 0
  110. async def retrieve(self, **_kwargs: Any) -> RetrievalResult:
  111. self.calls += 1
  112. return RetrievalResult(
  113. source_refs=("decode://case/1",),
  114. summary="one immutable result",
  115. )
  116. class _Coordinator:
  117. def __init__(self, ref: ArtifactRef) -> None:
  118. criterion = SimpleNamespace(criterion_id="criterion-a", hard=True)
  119. task = SimpleNamespace(
  120. task_id="task-1",
  121. validation_ids=(),
  122. current_spec=SimpleNamespace(
  123. acceptance_criteria=(criterion,),
  124. context_refs=("script-build://task-kinds/paragraph",),
  125. ),
  126. )
  127. self.task_store = _TaskStore(task)
  128. self.artifact_store = _ArtifactStore(ref)
  129. self.attempt_submission: tuple[dict[str, Any], Any] | None = None
  130. self.validation_submission: tuple[dict[str, Any], tuple[Any, ...]] | None = None
  131. async def submit_attempt(self, context: Mapping[str, Any], submission: Any) -> dict[str, Any]:
  132. self.attempt_submission = (dict(context), submission)
  133. return {
  134. "attempt_id": context["attempt_id"],
  135. "snapshot_id": "snapshot-a",
  136. "status": "awaiting_validation",
  137. }
  138. async def submit_validation(self, context: Mapping[str, Any], *values: Any) -> dict[str, Any]:
  139. self.validation_submission = (dict(context), values)
  140. return {
  141. "validation_id": context["validation_id"],
  142. "verdict": values[0].value,
  143. "status": "awaiting_decision",
  144. }
  145. def _gateway(ref: ArtifactRef) -> tuple[LegacyScriptToolGateway, _Coordinator, _CandidateTools]:
  146. coordinator = _Coordinator(ref)
  147. candidates = _CandidateTools(ref)
  148. gateway = LegacyScriptToolGateway(
  149. bindings=_Bindings(), # type: ignore[arg-type]
  150. snapshots=SimpleNamespace(),
  151. artifacts=_BusinessArtifacts(ref), # type: ignore[arg-type]
  152. coordinator=coordinator,
  153. candidate_tools=candidates, # type: ignore[arg-type]
  154. )
  155. return gateway, coordinator, candidates
  156. @pytest.mark.asyncio
  157. async def test_attempt_submission_is_derived_from_protected_attempt_artifact() -> None:
  158. ref = ArtifactRef(
  159. uri="script-build://artifact-versions/7",
  160. kind="paragraph",
  161. version="7",
  162. digest="sha256:" + "a" * 64,
  163. )
  164. gateway, coordinator, candidates = _gateway(ref)
  165. budget = _BudgetGuard()
  166. gateway.budget_guard = budget
  167. context = {
  168. "root_trace_id": "root-a",
  169. "task_id": "task-1",
  170. "attempt_id": "attempt-a",
  171. "spec_version": 1,
  172. }
  173. await gateway.submit_current_attempt(context)
  174. assert coordinator.attempt_submission is not None
  175. submitted_context, submission = coordinator.attempt_submission
  176. assert submitted_context == context
  177. assert submission.artifact_refs == [ref]
  178. assert submission.evidence_refs == []
  179. assert "paragraph" in submission.summary
  180. assert "sha256:" in submission.summary
  181. assert candidates.last_context == context
  182. assert budget.calls == [("root-a", "task-1", "submit")]
  183. @pytest.mark.asyncio
  184. async def test_retrieval_budget_is_checked_before_adapter_or_snapshot_access() -> None:
  185. ref = ArtifactRef(
  186. uri="script-build://artifact-versions/7",
  187. kind="evidence",
  188. version="7",
  189. digest="sha256:" + "a" * 64,
  190. )
  191. gateway, _, _ = _gateway(ref)
  192. budget = _BudgetGuard(ProtocolViolation("retrieval budget exhausted"))
  193. gateway.budget_guard = budget
  194. with pytest.raises(ProtocolViolation, match="budget exhausted"):
  195. await gateway.retrieve(
  196. "decode",
  197. "search_script_decode_case",
  198. {"query": "opening"},
  199. {
  200. "root_trace_id": "root-a",
  201. "task_id": "task-1",
  202. "attempt_id": "attempt-a",
  203. },
  204. )
  205. assert budget.calls == [("root-a", "task-1", "retrieval")]
  206. @pytest.mark.asyncio
  207. async def test_one_retrieval_attempt_never_calls_adapter_twice() -> None:
  208. artifacts = _RetrievalArtifacts()
  209. adapter = _CountingRetrievalAdapter()
  210. class Snapshots:
  211. async def get(self, snapshot_id: str, *, script_build_id: int) -> Any:
  212. assert (snapshot_id, script_build_id) == ("3", 9)
  213. return SimpleNamespace(account={})
  214. gateway = LegacyScriptToolGateway(
  215. bindings=_Bindings(), # type: ignore[arg-type]
  216. snapshots=Snapshots(), # type: ignore[arg-type]
  217. artifacts=artifacts, # type: ignore[arg-type]
  218. coordinator=SimpleNamespace(),
  219. retrieval_adapters={"decode": adapter},
  220. )
  221. context = {
  222. "root_trace_id": "root-a",
  223. "task_id": "task-1",
  224. "attempt_id": "attempt-a",
  225. "spec_version": 1,
  226. }
  227. await gateway.retrieve("decode", "search_script_decode_case", {"query": "opening"}, context)
  228. with pytest.raises(ProtocolViolation, match="only one Evidence"):
  229. await gateway.retrieve(
  230. "decode", "search_script_decode_case", {"query": "different"}, context
  231. )
  232. assert adapter.calls == 1
  233. @pytest.mark.asyncio
  234. async def test_candidate_write_receives_identity_only_from_protected_context() -> None:
  235. ref = ArtifactRef(
  236. uri="script-build://artifact-versions/7",
  237. kind="paragraph",
  238. version="7",
  239. digest="sha256:" + "a" * 64,
  240. )
  241. gateway, _, candidates = _gateway(ref)
  242. context = {
  243. "root_trace_id": "root-a",
  244. "task_id": "task-1",
  245. "attempt_id": "attempt-a",
  246. "spec_version": 1,
  247. }
  248. await gateway.candidate_command(
  249. "create_script_paragraph",
  250. {"paragraph_index": 1, "name": "opening", "content_range": {}},
  251. context,
  252. )
  253. assert candidates.last_context == context
  254. assert candidates.last_payload == {
  255. "paragraph_index": 1,
  256. "name": "opening",
  257. "content_range": {},
  258. }
  259. @pytest.mark.asyncio
  260. async def test_structured_validation_keeps_excerpt_out_of_framework_summary() -> None:
  261. ref = ArtifactRef(
  262. uri="script-build://artifact-versions/7",
  263. kind="paragraph",
  264. version="7",
  265. digest="sha256:" + "a" * 64,
  266. )
  267. gateway, coordinator, _ = _gateway(ref)
  268. context = {
  269. "root_trace_id": "root-a",
  270. "task_id": "task-1",
  271. "attempt_id": "attempt-a",
  272. "snapshot_id": "snapshot-a",
  273. "validation_id": "validation-a",
  274. }
  275. excerpt = "this exact candidate passage must not enter the bounded summary"
  276. await gateway.submit_structured_validation(
  277. verdict="failed",
  278. criterion_results=[
  279. {"criterion_id": "criterion-a", "verdict": "failed", "reason": "not realized"}
  280. ],
  281. defects=[
  282. {
  283. "defect_code": "REALIZATION_PLACEHOLDER",
  284. "criterion_id": "criterion-a",
  285. "scope_ref": "script-build://scopes/body/end",
  286. "observed_excerpt": excerpt,
  287. "evidence_refs": [
  288. {
  289. "uri": ref.uri,
  290. "kind": ref.kind,
  291. "version": ref.version,
  292. "digest": ref.digest,
  293. }
  294. ],
  295. "severity": "hard",
  296. "invalidated_inputs": ["decision-a"],
  297. "recommended_action_class": "split",
  298. }
  299. ],
  300. recommendation="split",
  301. context=context,
  302. )
  303. assert coordinator.validation_submission is not None
  304. _, values = coordinator.validation_submission
  305. verdict, results, summary, evidence_refs, unverified, risks, recommendation = values
  306. assert verdict is ValidationVerdict.FAILED
  307. assert results[0].reason.endswith("defect_codes=REALIZATION_PLACEHOLDER")
  308. assert excerpt not in summary
  309. assert len(summary) <= 500
  310. assert evidence_refs == (ref,)
  311. assert unverified == ()
  312. assert risks == ("REALIZATION_PLACEHOLDER",)
  313. assert recommendation == "split"
  314. @pytest.mark.asyncio
  315. async def test_passed_validation_rejects_blocking_defect_and_unfrozen_evidence() -> None:
  316. ref = ArtifactRef(
  317. uri="script-build://artifact-versions/7",
  318. kind="paragraph",
  319. version="7",
  320. digest="sha256:" + "a" * 64,
  321. )
  322. gateway, _, _ = _gateway(ref)
  323. context = {
  324. "root_trace_id": "root-a",
  325. "task_id": "task-1",
  326. "attempt_id": "attempt-a",
  327. "snapshot_id": "snapshot-a",
  328. "validation_id": "validation-a",
  329. }
  330. defect: dict[str, Any] = {
  331. "defect_code": "WRITE_SCOPE_CONFLICT",
  332. "criterion_id": "criterion-a",
  333. "scope_ref": "script-build://scopes/body",
  334. "observed_excerpt": "overlapping body",
  335. "evidence_refs": [],
  336. "severity": "hard",
  337. "invalidated_inputs": [],
  338. "recommended_action_class": "replace",
  339. }
  340. with pytest.raises(ProtocolViolation, match="cannot contain hard"):
  341. await gateway.submit_structured_validation(
  342. verdict="passed",
  343. criterion_results=[
  344. {"criterion_id": "criterion-a", "verdict": "passed", "reason": "ok"}
  345. ],
  346. defects=[defect],
  347. recommendation="replace",
  348. context=context,
  349. )
  350. defect["severity"] = "warning"
  351. defect["evidence_refs"] = [
  352. {
  353. "uri": "script-build://artifact-versions/8",
  354. "kind": "paragraph",
  355. "version": "8",
  356. "digest": "sha256:" + "b" * 64,
  357. }
  358. ]
  359. with pytest.raises(ProtocolViolation, match="fixed validation snapshot"):
  360. await gateway.submit_structured_validation(
  361. verdict="passed",
  362. criterion_results=[
  363. {"criterion_id": "criterion-a", "verdict": "passed", "reason": "ok"}
  364. ],
  365. defects=[defect],
  366. recommendation="accept",
  367. context=context,
  368. )
  369. @pytest.mark.asyncio
  370. async def test_view_frozen_images_returns_multimodal_without_url_or_data_in_text() -> None:
  371. ref = ArtifactRef(
  372. uri="script-build://artifact-versions/7",
  373. kind="paragraph",
  374. version="7",
  375. digest="sha256:" + "a" * 64,
  376. )
  377. gateway, _, candidates = _gateway(ref)
  378. encoded = base64.b64encode(b"safe-image-bytes").decode("ascii")
  379. candidates.images = [
  380. {
  381. "type": "base64",
  382. "media_type": "image/png",
  383. "data": encoded,
  384. "raw_artifact_ref": "script-build://raw-artifacts/sha256/abc",
  385. }
  386. ]
  387. registry = ToolRegistry()
  388. register_script_tools(registry, gateway)
  389. result = await registry.execute(
  390. "view_frozen_images",
  391. {"raw_artifact_refs": ["script-build://raw-artifacts/sha256/abc"]},
  392. context={"root_trace_id": "root-a", "task_id": "task-1"},
  393. )
  394. assert isinstance(result, dict)
  395. assert result["images"] == [{"type": "base64", "media_type": "image/png", "data": encoded}]
  396. assert encoded not in result["text"]
  397. assert "http" not in result["text"]
  398. candidates.images = [
  399. {
  400. "type": "base64",
  401. "media_type": "image/png",
  402. "data": encoded,
  403. "url": "https://forbidden.invalid/image.png",
  404. }
  405. ]
  406. rejected = await registry.execute(
  407. "view_frozen_images",
  408. {"raw_artifact_refs": ["script-build://raw-artifacts/sha256/abc"]},
  409. context={"root_trace_id": "root-a", "task_id": "task-1"},
  410. )
  411. assert isinstance(rejected, str)
  412. assert "must not contain network URLs" in rejected