test_phase_one_e2e.py 21 KB

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