test_phase_two_agent_tools.py 18 KB

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