test_phase_one_e2e.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. from __future__ import annotations
  2. import json
  3. from dataclasses import replace
  4. from datetime import UTC, datetime
  5. from types import SimpleNamespace
  6. import pytest
  7. from agent import AgentRunner, FileSystemArtifactStore, FileSystemTaskStore, FileSystemTraceStore
  8. from agent.orchestration import ArtifactRef, TaskStatus, ValidationVerdict
  9. from script_build_host.composition import HostDependencies, compose_host
  10. from script_build_host.domain.artifacts import (
  11. ArtifactKind,
  12. ArtifactState,
  13. ArtifactVersion,
  14. EvidenceRecordV1,
  15. )
  16. from script_build_host.domain.errors import ArtifactNotFound
  17. from script_build_host.domain.input_snapshot import ScriptBuildInputSnapshotV1
  18. from script_build_host.domain.records import (
  19. BuildStatus,
  20. MissionBinding,
  21. Principal,
  22. PublicationState,
  23. )
  24. from script_build_host.infrastructure.canonical_json import canonical_sha256
  25. from script_build_host.tools.gateway import RetrievalResult
  26. def _tool(call_id: str, name: str, arguments: dict[str, object]) -> dict[str, object]:
  27. return {
  28. "content": "",
  29. "tool_calls": [
  30. {
  31. "id": call_id,
  32. "type": "function",
  33. "function": {"name": name, "arguments": json.dumps(arguments)},
  34. }
  35. ],
  36. "finish_reason": "tool_calls",
  37. }
  38. def _prompt(messages: list[dict[str, object]]) -> dict[str, object]:
  39. for message in reversed(messages):
  40. if message.get("role") != "user" or not isinstance(message.get("content"), str):
  41. continue
  42. try:
  43. value = json.loads(message["content"])
  44. except ValueError:
  45. continue
  46. if isinstance(value, dict) and "task_spec" in value:
  47. return value
  48. raise AssertionError("missing role prompt")
  49. def _last_tool_json(messages: list[dict[str, object]]) -> dict[str, object] | None:
  50. for message in reversed(messages):
  51. if message.get("role") != "tool":
  52. continue
  53. content = message.get("content")
  54. if isinstance(content, str):
  55. try:
  56. value = json.loads(content)
  57. return value if isinstance(value, dict) else None
  58. except ValueError:
  59. return None
  60. return None
  61. def _contract(
  62. kind: str,
  63. objective: str,
  64. criterion_id: str,
  65. description: str,
  66. *,
  67. scope: str,
  68. ) -> dict[str, object]:
  69. return {
  70. "task_kind": kind,
  71. "scope_selector": {
  72. "anchor": "mission",
  73. "path": scope.removeprefix("script-build://scopes/").split("/")[:4],
  74. },
  75. "intent_class": "explore",
  76. "objective": objective,
  77. "input_decision_ids": [],
  78. "base_decision_id": None,
  79. "gap_key": None,
  80. "criteria": [
  81. {
  82. "client_key": criterion_id,
  83. "description": description,
  84. "hard": True,
  85. }
  86. ],
  87. "goal_ids": [],
  88. "supersedes_decision_ids": [],
  89. "comparison_decision_ids": [],
  90. }
  91. class _ScriptedLLM:
  92. def __init__(self, store: FileSystemTaskStore, root: str) -> None:
  93. self.store = store
  94. self.root = root
  95. self.calls = 0
  96. self.decode_versions: list[int] = []
  97. self.validated_artifact_kinds: list[str] = []
  98. self.replayed_dispatch = False
  99. def call(self, name: str, arguments: dict[str, object]) -> dict[str, object]:
  100. self.calls += 1
  101. return _tool(f"call-{self.calls}", name, arguments)
  102. def call_with_id(
  103. self,
  104. call_id: str,
  105. name: str,
  106. arguments: dict[str, object],
  107. ) -> dict[str, object]:
  108. self.calls += 1
  109. return _tool(call_id, name, arguments)
  110. async def __call__(self, messages, tools, **_kwargs):
  111. names = {item["function"]["name"] for item in tools or []}
  112. if "plan_script_tasks" in names:
  113. return await self._planner()
  114. if "submit_validation" in names:
  115. return self._validator(messages)
  116. if "submit_attempt" in names:
  117. return self._worker(messages, names)
  118. raise AssertionError(sorted(names))
  119. async def _planner(self):
  120. ledger = await self.store.load(self.root)
  121. root = ledger.tasks[ledger.root_task_id]
  122. direction = next(
  123. (
  124. item
  125. for item in ledger.tasks.values()
  126. if "script-build://task-kinds/direction" in item.current_spec.context_refs
  127. ),
  128. None,
  129. )
  130. if direction is None:
  131. return self.call(
  132. "plan_script_tasks",
  133. {
  134. "contracts": [
  135. _contract(
  136. "direction",
  137. "build direction",
  138. "direction-ready",
  139. "direction is grounded",
  140. scope="script-build://scopes/direction",
  141. )
  142. ],
  143. },
  144. )
  145. retrieval = next(
  146. (
  147. item
  148. for item in ledger.tasks.values()
  149. if "script-build://task-kinds/decode-retrieval" in item.current_spec.context_refs
  150. ),
  151. None,
  152. )
  153. if retrieval is None:
  154. return self.call(
  155. "plan_script_tasks",
  156. {
  157. "parent_task_id": direction.task_id,
  158. "contracts": [
  159. _contract(
  160. "decode-retrieval",
  161. "decode evidence",
  162. "evidence-ready",
  163. "evidence is relevant",
  164. scope="script-build://scopes/direction/decode",
  165. )
  166. ],
  167. },
  168. )
  169. if retrieval.status in {TaskStatus.PENDING, TaskStatus.NEEDS_REPLAN}:
  170. return self.call_with_id(
  171. f"decode-dispatch-v{retrieval.current_spec_version}",
  172. "dispatch_script_tasks",
  173. {"task_ids": [retrieval.task_id]},
  174. )
  175. if retrieval.status == TaskStatus.AWAITING_DECISION:
  176. if retrieval.current_spec_version == 1 and not self.replayed_dispatch:
  177. self.replayed_dispatch = True
  178. return self.call_with_id(
  179. "decode-dispatch-v1",
  180. "dispatch_script_tasks",
  181. {"task_ids": [retrieval.task_id]},
  182. )
  183. validation = ledger.validations[retrieval.validation_ids[-1]]
  184. if validation.verdict == ValidationVerdict.FAILED:
  185. return self.call(
  186. "decide_script_task",
  187. {
  188. "task_id": retrieval.task_id,
  189. "validation_id": validation.validation_id,
  190. "action": "revise",
  191. "reason": "make decode query precise",
  192. "replacement_contract": _contract(
  193. "decode-retrieval",
  194. "decode evidence revised",
  195. "evidence-ready",
  196. "evidence is relevant",
  197. scope="script-build://scopes/direction/decode",
  198. ),
  199. },
  200. )
  201. return self.call(
  202. "decide_script_task",
  203. {
  204. "task_id": retrieval.task_id,
  205. "validation_id": validation.validation_id,
  206. "action": "accept",
  207. "reason": "decode evidence passed",
  208. },
  209. )
  210. if direction.status in {TaskStatus.PENDING, TaskStatus.NEEDS_REPLAN}:
  211. return self.call("dispatch_script_tasks", {"task_ids": [direction.task_id]})
  212. if direction.status == TaskStatus.AWAITING_DECISION:
  213. validation = ledger.validations[direction.validation_ids[-1]]
  214. return self.call(
  215. "decide_script_task",
  216. {
  217. "task_id": direction.task_id,
  218. "validation_id": validation.validation_id,
  219. "action": "accept",
  220. "reason": "direction passed",
  221. },
  222. )
  223. assert direction.status == TaskStatus.COMPLETED
  224. if root.current_spec_version == 1:
  225. return self.call(
  226. "decide_script_task",
  227. {
  228. "task_id": root.task_id,
  229. "action": "revise",
  230. "reason": "record accepted direction in root objective",
  231. "replacement_contract": {
  232. "objective": root.current_spec.objective + " using accepted direction",
  233. },
  234. },
  235. )
  236. return self.call(
  237. "decide_script_task",
  238. {
  239. "task_id": root.task_id,
  240. "action": "block",
  241. "reason": "PHASE_ONE_CAPABILITY_BOUNDARY",
  242. },
  243. )
  244. def _worker(self, messages, names):
  245. prompt = _prompt(messages)
  246. spec = prompt["task_spec"]
  247. last = _last_tool_json(messages)
  248. if "search_script_decode_case" in names:
  249. if last is None or "artifact_ref" not in last:
  250. self.decode_versions.append(spec["version"])
  251. return self.call(
  252. "search_script_decode_case",
  253. {"return_field": "主脉络", "keyword": "focus", "top_k": 3},
  254. )
  255. return self.call(
  256. "submit_attempt",
  257. {},
  258. )
  259. if last is None or "artifact_ref" not in last:
  260. accepted = prompt["role_context"]["accepted_inputs"]
  261. return self.call(
  262. "save_direction_candidate",
  263. {
  264. "goals": [
  265. {
  266. "client_key": "grounded-direction",
  267. "statement": "make one grounded direction",
  268. "rationale": "accepted evidence",
  269. "success_criteria": ["the direction remains grounded"],
  270. }
  271. ],
  272. "constraints": [
  273. {
  274. "client_key": "c1",
  275. "statement": "remain grounded",
  276. "rationale": "accepted evidence is mandatory",
  277. }
  278. ],
  279. "preferences": [],
  280. "strategy_handles": [],
  281. "evidence_decision_ids": [accepted[0]["decision_id"]],
  282. },
  283. )
  284. return self.call(
  285. "submit_attempt",
  286. {},
  287. )
  288. def _validator(self, messages):
  289. prompt = _prompt(messages)
  290. spec = prompt["task_spec"]
  291. kind = (
  292. "direction"
  293. if "script-build://task-kinds/direction" in spec["context_refs"]
  294. else "evidence"
  295. )
  296. role_context = prompt["role_context"]
  297. assert role_context["artifact"]["items"], "validator must receive the frozen artifact body"
  298. artifact = role_context["artifact"]["items"][0]["content"]
  299. assert isinstance(artifact, dict)
  300. self.validated_artifact_kinds.append(kind)
  301. failed = spec["objective"] == "decode evidence" and spec["version"] == 1
  302. verdict = "failed" if failed else "passed"
  303. evidence_handle = role_context["evidence_handles"][0]["evidence_handle"]
  304. return self.call(
  305. "submit_validation",
  306. {
  307. "verdict": verdict,
  308. "criterion_results": [
  309. {
  310. "criterion_id": item["criterion_id"],
  311. "verdict": verdict,
  312. "reason": "checked frozen snapshot",
  313. "evidence_handle_ids": [] if failed else [evidence_handle],
  314. }
  315. for item in spec["acceptance_criteria"]
  316. ],
  317. "defects": (
  318. [
  319. {
  320. "defect_code": "DECODE_QUERY_TOO_BROAD",
  321. "criterion_id": spec["acceptance_criteria"][0]["criterion_id"],
  322. "scope_selector": {
  323. "anchor": "mission",
  324. "path": ["direction", "decode"],
  325. },
  326. "observed_excerpt": "v1 decode evidence was too broad",
  327. "evidence_handle_ids": [],
  328. "severity": "hard",
  329. "invalidated_inputs": [],
  330. "recommended_action_class": "revise",
  331. }
  332. ]
  333. if failed
  334. else []
  335. ),
  336. "recommendation": "revise" if failed else "accept",
  337. },
  338. )
  339. class _Bindings:
  340. def __init__(self, binding: MissionBinding) -> None:
  341. self.binding = binding
  342. self.active = None
  343. async def get_by_build(self, _: int) -> MissionBinding:
  344. return self.binding
  345. async def get_by_root(self, _: str) -> MissionBinding:
  346. return self.binding
  347. async def set_active_direction(self, **values) -> MissionBinding:
  348. self.active = values["artifact_version_id"]
  349. return replace(self.binding, active_direction_artifact_version_id=self.active)
  350. class _Snapshots:
  351. def __init__(self, snapshot: ScriptBuildInputSnapshotV1) -> None:
  352. self.snapshot = snapshot
  353. async def get(self, *_args, **_kwargs) -> ScriptBuildInputSnapshotV1:
  354. return self.snapshot
  355. class _Artifacts:
  356. def __init__(self) -> None:
  357. self.values = {}
  358. self.next_id = 1
  359. async def freeze(self, *, artifact, script_build_id, task_id, attempt_id, spec_version):
  360. payload = artifact.content_payload()
  361. digest = canonical_sha256(payload).wire
  362. if isinstance(artifact, EvidenceRecordV1):
  363. artifact = replace(artifact, content_sha256=digest)
  364. kind = ArtifactKind.EVIDENCE
  365. else:
  366. artifact = replace(artifact, canonical_sha256=digest)
  367. kind = ArtifactKind.DIRECTION
  368. value = ArtifactVersion(
  369. self.next_id,
  370. script_build_id,
  371. task_id,
  372. attempt_id,
  373. spec_version,
  374. kind,
  375. digest,
  376. ArtifactState.FROZEN,
  377. artifact,
  378. datetime.now(UTC),
  379. datetime.now(UTC),
  380. )
  381. ref = ArtifactRef(
  382. uri=f"script-build://artifact-versions/{self.next_id}",
  383. kind=kind.value,
  384. version=str(self.next_id),
  385. digest=digest,
  386. metadata={
  387. "script_build_id": script_build_id,
  388. "task_id": task_id,
  389. "attempt_id": attempt_id,
  390. },
  391. )
  392. self.values[self.next_id] = (value, ref)
  393. self.next_id += 1
  394. return value, ref
  395. async def read_by_ref(self, ref, **_kwargs):
  396. return self.values[int(ref.version)][0]
  397. async def get_by_attempt(self, *, script_build_id, task_id, attempt_id):
  398. try:
  399. return next(
  400. value
  401. for value, _ref in self.values.values()
  402. if value.script_build_id == script_build_id
  403. and value.task_id == task_id
  404. and value.attempt_id == attempt_id
  405. )
  406. except StopIteration as exc:
  407. raise ArtifactNotFound() from exc
  408. class _Legacy:
  409. def __init__(self) -> None:
  410. self.status = BuildStatus.RUNNING
  411. self.direction = None
  412. async def get_status(self, _: int) -> BuildStatus:
  413. return self.status
  414. async def set_status(self, _id, status, **_kwargs):
  415. self.status = status
  416. async def project_direction(self, _id, value):
  417. assert self.status != BuildStatus.STOPPING
  418. self.direction = value
  419. class _Publications:
  420. def __init__(self) -> None:
  421. self.state = PublicationState.PENDING
  422. async def prepare(self, **values):
  423. return SimpleNamespace(publication_id=1, state=self.state, **values)
  424. async def mark_published(self, _id):
  425. self.state = PublicationState.PUBLISHED
  426. async def mark_failed(self, _id, **_values):
  427. self.state = PublicationState.FAILED
  428. class _Decode:
  429. async def retrieve(self, *, query, snapshot):
  430. del snapshot
  431. return RetrievalResult(
  432. source_refs=(f"decode:{query['keyword']}",),
  433. summary="evidence",
  434. supports=("direction",),
  435. confidence="high",
  436. metadata={"index_sha256": "sha256:" + "1" * 64, "ranks": [1]},
  437. )
  438. class _PrincipalProvider:
  439. async def current(self, request_context=None):
  440. del request_context
  441. return Principal("owner")
  442. class _Authorizer:
  443. async def require_source_access(self, _principal, **_source):
  444. return None
  445. async def require_access(self, _principal, _build):
  446. return None
  447. @pytest.mark.asyncio
  448. async def test_real_runner_phase_one_fail_revise_pass_direction_accept_then_root_block(tmp_path):
  449. now = datetime.now(UTC)
  450. binding = MissionBinding(1, 7, "phase-one-root", 11, None, None, "test", "v1", now, now)
  451. model_presets = {
  452. name: {"model": "fake-model", "temperature": 0, "max_iterations": 50}
  453. for name in (
  454. "script_decode_retrieval_worker",
  455. "script_direction_worker",
  456. "script_retrieval_validator",
  457. "script_candidate_validator",
  458. )
  459. }
  460. snapshot = ScriptBuildInputSnapshotV1(
  461. "11",
  462. 7,
  463. 1,
  464. 2,
  465. 3,
  466. {"topic": {"id": 3, "result": "topic"}},
  467. {"account_name": "acct"},
  468. (),
  469. (),
  470. (),
  471. (),
  472. {},
  473. {"presets": model_presets},
  474. "sha256:" + "a" * 64,
  475. now,
  476. )
  477. task_store = FileSystemTaskStore(str(tmp_path / "ledger"))
  478. llm = _ScriptedLLM(task_store, binding.root_trace_id)
  479. runner = AgentRunner(trace_store=FileSystemTraceStore(str(tmp_path / "trace")), llm_call=llm)
  480. bindings = _Bindings(binding)
  481. snapshots = _Snapshots(snapshot)
  482. artifacts = _Artifacts()
  483. legacy = _Legacy()
  484. publications = _Publications()
  485. composition = compose_host(
  486. HostDependencies(
  487. runner=runner,
  488. task_store=task_store,
  489. framework_artifact_store=FileSystemArtifactStore(str(tmp_path / "artifacts")),
  490. input_snapshot_service=SimpleNamespace(get=snapshots.get),
  491. input_snapshots=snapshots,
  492. bindings=bindings,
  493. business_artifacts=artifacts,
  494. publications=publications,
  495. legacy_state=legacy,
  496. principal_provider=_PrincipalProvider(),
  497. build_authorizer=_Authorizer(),
  498. retrieval_adapters={"decode": _Decode()},
  499. )
  500. )
  501. await composition.mission_service.run(7)
  502. ledger = await task_store.load(binding.root_trace_id)
  503. root = ledger.tasks[ledger.root_task_id]
  504. assert root.status == TaskStatus.BLOCKED
  505. assert root.blocked_reason == "PHASE_ONE_CAPABILITY_BOUNDARY"
  506. assert root.current_spec_version == 2
  507. assert llm.decode_versions == [1, 2]
  508. assert llm.replayed_dispatch
  509. assert len(ledger.operations) == 3
  510. assert llm.validated_artifact_kinds == ["evidence", "evidence", "direction"]
  511. assert legacy.status == BuildStatus.PARTIAL
  512. assert legacy.direction.startswith("# Direction\n\n## Goals")
  513. assert "### goal-" in legacy.direction
  514. assert ": make one grounded direction" in legacy.direction
  515. assert "## Constraints" in legacy.direction
  516. assert publications.state == PublicationState.PUBLISHED
  517. assert bindings.active is not None
  518. assert not hasattr(bindings.binding, "branch_id")
  519. model_calls = llm.calls
  520. reloaded_ledger = await FileSystemTaskStore(str(tmp_path / "ledger")).load(
  521. binding.root_trace_id
  522. )
  523. assert reloaded_ledger.tasks[reloaded_ledger.root_task_id].status == TaskStatus.BLOCKED
  524. reloaded_traces = FileSystemTraceStore(str(tmp_path / "trace"))
  525. reloaded_trace = await reloaded_traces.get_trace(binding.root_trace_id)
  526. assert reloaded_trace is not None
  527. assert await reloaded_traces.get_goal_tree(binding.root_trace_id) is None
  528. submitted = next(
  529. attempt for attempt in reloaded_ledger.attempts.values() if attempt.snapshot_id
  530. )
  531. assert await FileSystemArtifactStore(str(tmp_path / "artifacts")).get(
  532. binding.root_trace_id,
  533. submitted.snapshot_id,
  534. )
  535. assert llm.calls == model_calls