test_phase_one_e2e.py 21 KB

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