test_phase_two_agent_tools.py 18 KB

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