test_phase_one_e2e.py 21 KB

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