test_phase_two_contracts.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. from __future__ import annotations
  2. import asyncio
  3. from dataclasses import replace
  4. from datetime import UTC, datetime
  5. from hashlib import sha256
  6. from pathlib import Path
  7. from types import SimpleNamespace
  8. from typing import Any, cast
  9. import pytest
  10. from agent import AgentRunner, FileSystemArtifactStore, FileSystemTaskStore, FileSystemTraceStore
  11. from agent.orchestration import (
  12. AgentRole,
  13. ArtifactRef,
  14. AttemptSubmission,
  15. CriterionResult,
  16. DecisionAction,
  17. OperationStatus,
  18. OrchestrationConfig,
  19. TaskCoordinator,
  20. TaskStatus,
  21. ValidationVerdict,
  22. )
  23. from agent.orchestration.protocols import ValidatorRunResult, WorkerRunResult
  24. from script_build_host.application.mission_factory import ScriptMissionFactory
  25. from script_build_host.application.mission_service import ScriptMissionService
  26. from script_build_host.application.phase_two_planning import PhaseTwoPlanningService
  27. from script_build_host.domain.errors import ProtocolViolation
  28. from script_build_host.domain.records import BuildStatus, MissionBinding, Principal
  29. from script_build_host.domain.task_contracts import (
  30. PhaseTwoLimits,
  31. ScriptTaskContractV1,
  32. TaskContractError,
  33. )
  34. from script_build_host.infrastructure.task_contract_store import FileScriptTaskContractStore
  35. def _contract(
  36. kind: str,
  37. *,
  38. scope: str = "script-build://scopes/full",
  39. execution_ready: bool = True,
  40. ) -> dict[str, object]:
  41. output = {
  42. "direction": "script-direction/v1",
  43. "candidate-portfolio": "candidate-portfolio/v1",
  44. "compose": "structured-script/v1",
  45. "paragraph": "paragraph-artifact/v1",
  46. "element-set": "element-set-artifact/v1",
  47. "structure": "structure-artifact/v1",
  48. "compare": "comparison-artifact/v1",
  49. "decode-retrieval": "evidence-record/v1",
  50. }[kind]
  51. payload: dict[str, object] = {
  52. "schema_version": "script-task-contract/v1",
  53. "task_kind": kind,
  54. "scope_ref": scope,
  55. "intent_class": (
  56. "portfolio"
  57. if kind == "candidate-portfolio"
  58. else "compose"
  59. if kind == "compose"
  60. else "explore"
  61. ),
  62. "objective": f"produce one bounded {kind} increment",
  63. "input_decision_refs": [],
  64. "base_artifact_ref": None,
  65. "write_scope": [scope],
  66. "gap_ref": None,
  67. "output_schema": output,
  68. "criteria": [
  69. {
  70. "criterion_id": "closed",
  71. "description": "the bounded increment is independently verifiable",
  72. "hard": True,
  73. }
  74. ],
  75. "budget": {
  76. "max_attempts": 4,
  77. "max_tokens": 32000,
  78. "max_seconds": 900,
  79. "max_external_queries": 40,
  80. "max_no_improvement": 3,
  81. },
  82. "supersedes_decision_ids": [],
  83. "candidate_closure_decision_refs": [],
  84. "adopted_decision_ids": [],
  85. "held_or_rejected_decision_ids": [],
  86. "compose_order": [],
  87. "comparison_decision_refs": [],
  88. }
  89. if execution_ready and kind in {"compose", "candidate-portfolio"}:
  90. ref = {
  91. "decision_id": "decision-1",
  92. "artifact_ref": {
  93. "uri": "script-build://artifact-versions/1",
  94. "kind": "structured_script" if kind == "candidate-portfolio" else "paragraph",
  95. "version": "1",
  96. "digest": "sha256:" + "a" * 64,
  97. },
  98. "scope_ref": scope,
  99. "expected_task_kind": "compose" if kind == "candidate-portfolio" else "paragraph",
  100. }
  101. payload["candidate_closure_decision_refs"] = [ref]
  102. payload["adopted_decision_ids"] = ["decision-1"]
  103. payload["compose_order"] = ["decision-1"]
  104. return payload
  105. class _Bindings:
  106. def __init__(self, root: str) -> None:
  107. self.binding = MissionBinding(
  108. binding_id=1,
  109. script_build_id=7,
  110. root_trace_id=root,
  111. input_snapshot_id=11,
  112. active_direction_artifact_version_id=None,
  113. accepted_root_artifact_version_id=None,
  114. engine_version="test",
  115. schema_version="v1",
  116. created_at=datetime.now(UTC),
  117. updated_at=datetime.now(UTC),
  118. )
  119. async def get_by_root(self, root: str) -> MissionBinding:
  120. assert root == self.binding.root_trace_id
  121. return self.binding
  122. async def get_by_build(self, script_build_id: int) -> MissionBinding:
  123. assert script_build_id == self.binding.script_build_id
  124. return self.binding
  125. class _PlaceholderThenReplacementExecutor:
  126. """Exercise Coordinator state transitions without bypassing durable operations."""
  127. def __init__(self, coordinator: TaskCoordinator) -> None:
  128. self.coordinator = coordinator
  129. self.artifact_version = 100
  130. async def run_worker(self, context: dict[str, Any]) -> WorkerRunResult:
  131. refs = cast(dict[str, Any], context["task_spec"])["context_refs"]
  132. kind = next(item.rsplit("/", 1)[-1] for item in refs if "/task-kinds/" in item)
  133. artifact_kind = {
  134. "compose": "structured_script",
  135. "structure": "structure",
  136. "paragraph": "paragraph",
  137. "element-set": "element_set",
  138. }[kind]
  139. digest = "sha256:" + sha256(context["attempt_id"].encode()).hexdigest()
  140. version = str(self.artifact_version)
  141. self.artifact_version += 1
  142. ref = ArtifactRef(
  143. f"script-build://artifact-versions/{version}",
  144. artifact_kind,
  145. version,
  146. digest,
  147. )
  148. await self.coordinator.submit_attempt(
  149. {
  150. "role": AgentRole.WORKER.value,
  151. "root_trace_id": context["root_trace_id"],
  152. "task_id": context["task_id"],
  153. "attempt_id": context["attempt_id"],
  154. "spec_version": context["spec_version"],
  155. "trace_id": context["worker_trace_id"],
  156. "tool_call_id": f"submit:{context['attempt_id']}",
  157. "operation_id": context["operation_id"],
  158. "execution_epoch": context["execution_epoch"],
  159. },
  160. AttemptSubmission(
  161. summary=f"kind={artifact_kind};status=frozen",
  162. artifact_refs=[ref],
  163. ),
  164. )
  165. return WorkerRunResult(context["worker_trace_id"], "completed")
  166. async def run_validator(self, context: dict[str, Any]) -> ValidatorRunResult:
  167. refs = cast(dict[str, Any], context["task_spec"])["context_refs"]
  168. kind = next(item.rsplit("/", 1)[-1] for item in refs if "/task-kinds/" in item)
  169. placeholder = kind == "compose" and context["spec_version"] == 1
  170. verdict = ValidationVerdict.FAILED if placeholder else ValidationVerdict.PASSED
  171. criterion = cast(dict[str, Any], context["task_spec"])["acceptance_criteria"][0]
  172. await self.coordinator.submit_validation(
  173. {
  174. "role": AgentRole.VALIDATOR.value,
  175. "root_trace_id": context["root_trace_id"],
  176. "task_id": context["task_id"],
  177. "attempt_id": context["attempt_id"],
  178. "validation_id": context["validation_id"],
  179. "snapshot_id": context["snapshot_id"],
  180. "trace_id": context["validator_trace_id"],
  181. "tool_call_id": f"validate:{context['validation_id']}",
  182. "operation_id": context["operation_id"],
  183. "execution_epoch": context["execution_epoch"],
  184. },
  185. verdict,
  186. [
  187. CriterionResult(
  188. criterion_id=criterion["criterion_id"],
  189. verdict=verdict,
  190. reason=(
  191. "REALIZATION_PLACEHOLDER at artifact.paragraphs[0].description"
  192. if placeholder
  193. else "the replacement is concretely rendered"
  194. ),
  195. )
  196. ],
  197. (
  198. "hard_defects=1;defect_codes=REALIZATION_PLACEHOLDER"
  199. if placeholder
  200. else "hard_defects=0"
  201. ),
  202. (),
  203. ("artifact.paragraphs[0].description",) if placeholder else (),
  204. ("REALIZATION_PLACEHOLDER",) if placeholder else (),
  205. "split" if placeholder else "accept",
  206. )
  207. return ValidatorRunResult(context["validator_trace_id"], "completed")
  208. async def stop(self, trace_id: str) -> bool:
  209. del trace_id
  210. return True
  211. async def _service(tmp_path: Path) -> tuple[PhaseTwoPlanningService, TaskCoordinator, str]:
  212. root = "root-contracts"
  213. coordinator = TaskCoordinator(
  214. FileSystemTaskStore(str(tmp_path / "ledger")),
  215. FileSystemArtifactStore(str(tmp_path / "snapshots")),
  216. FileSystemTraceStore(str(tmp_path / "traces")),
  217. )
  218. await coordinator.ensure_ledger(
  219. root,
  220. {
  221. "objective": "build a script",
  222. "acceptance_criteria": [
  223. {"criterion_id": "ready", "description": "ready", "hard": True}
  224. ],
  225. "context_refs": ["script-build://inputs/11"],
  226. },
  227. )
  228. service = PhaseTwoPlanningService(
  229. coordinator=coordinator,
  230. bindings=_Bindings(root),
  231. contracts=FileScriptTaskContractStore(tmp_path / "data"),
  232. )
  233. return service, coordinator, root
  234. class _BlockingExecutor:
  235. def __init__(self) -> None:
  236. self.started = asyncio.Event()
  237. self.stopped_trace_ids: list[str] = []
  238. async def run_worker(self, context: dict[str, Any]) -> WorkerRunResult:
  239. self.started.set()
  240. await asyncio.Event().wait()
  241. raise AssertionError(f"worker unexpectedly resumed: {context['attempt_id']}")
  242. async def run_validator(self, context: dict[str, Any]) -> ValidatorRunResult:
  243. raise AssertionError(f"validator must not start: {context['validation_id']}")
  244. async def stop(self, trace_id: str) -> bool:
  245. self.stopped_trace_ids.append(trace_id)
  246. return True
  247. class _StopState:
  248. def __init__(self) -> None:
  249. self.status = BuildStatus.RUNNING
  250. self.error_summary: str | None = None
  251. async def get_status(self, script_build_id: int) -> BuildStatus:
  252. assert script_build_id == 7
  253. return self.status
  254. async def set_status(
  255. self,
  256. script_build_id: int,
  257. status: BuildStatus,
  258. *,
  259. error_summary: str | None = None,
  260. ) -> None:
  261. assert script_build_id == 7
  262. self.status = status
  263. self.error_summary = error_summary
  264. @pytest.mark.asyncio
  265. async def test_real_operation_stop_converges_and_forbids_new_dispatch(tmp_path: Path) -> None:
  266. root = "root-stop-operation"
  267. trace_store = FileSystemTraceStore(str(tmp_path / "stop-traces"))
  268. coordinator = TaskCoordinator(
  269. FileSystemTaskStore(str(tmp_path / "stop-ledger")),
  270. FileSystemArtifactStore(str(tmp_path / "stop-artifacts")),
  271. trace_store,
  272. config=OrchestrationConfig(stop_grace_seconds=0.01),
  273. )
  274. await coordinator.ensure_ledger(
  275. root,
  276. {
  277. "objective": "build a script",
  278. "acceptance_criteria": [
  279. {"criterion_id": "ready", "description": "ready", "hard": True}
  280. ],
  281. "context_refs": ["script-build://inputs/11"],
  282. },
  283. )
  284. bindings = _Bindings(root)
  285. planning = PhaseTwoPlanningService(
  286. coordinator=coordinator,
  287. bindings=bindings,
  288. contracts=FileScriptTaskContractStore(tmp_path / "stop-contracts"),
  289. )
  290. portfolio = await planning.plan_script_tasks(
  291. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  292. parent_task_id=None,
  293. context={"root_trace_id": root, "tool_call_id": "stop:portfolio"},
  294. )
  295. compose = await planning.plan_script_tasks(
  296. contract_payloads=[_contract("compose", execution_ready=False)],
  297. parent_task_id=portfolio["task_ids"][0],
  298. context={"root_trace_id": root, "tool_call_id": "stop:compose"},
  299. )
  300. paragraph = await planning.plan_script_tasks(
  301. contract_payloads=[_contract("paragraph")],
  302. parent_task_id=compose["task_ids"][0],
  303. context={"root_trace_id": root, "tool_call_id": "stop:paragraph"},
  304. )
  305. executor = _BlockingExecutor()
  306. coordinator.set_executor(executor)
  307. async def unused_llm(**_kwargs: Any) -> Any:
  308. raise AssertionError("Planner LLM must not run during operation stop")
  309. runner = AgentRunner(trace_store=trace_store, llm_call=unused_llm)
  310. state = _StopState()
  311. class Authorizer:
  312. async def require_access(self, principal: Principal, script_build_id: int) -> None:
  313. assert principal.subject == "owner" and script_build_id == 7
  314. mission = ScriptMissionService(
  315. runner=runner,
  316. coordinator=coordinator,
  317. factory=ScriptMissionFactory(),
  318. input_snapshots=SimpleNamespace(),
  319. bindings=bindings,
  320. legacy_state=state,
  321. authorizer=Authorizer(),
  322. direction_reconciler=SimpleNamespace(),
  323. stop_timeout_seconds=1,
  324. )
  325. planning.dispatch_guard = mission
  326. dispatch = asyncio.create_task(
  327. planning.dispatch_script_tasks(
  328. task_ids=paragraph["task_ids"],
  329. context={"root_trace_id": root, "tool_call_id": "stop:dispatch"},
  330. )
  331. )
  332. await asyncio.wait_for(executor.started.wait(), timeout=1)
  333. stopped = await mission.stop(7, Principal("owner"))
  334. dispatch_result = await asyncio.gather(dispatch, return_exceptions=True)
  335. assert stopped.status is BuildStatus.STOPPED
  336. assert len(stopped.stopped_operation_ids) == 1
  337. assert executor.stopped_trace_ids
  338. assert not isinstance(dispatch_result[0], asyncio.CancelledError)
  339. ledger = await coordinator.task_store.load(root)
  340. operation = ledger.operations[stopped.stopped_operation_ids[0]]
  341. assert operation.status is OperationStatus.STOPPED
  342. assert ledger.tasks[paragraph["task_ids"][0]].status is TaskStatus.NEEDS_REPLAN
  343. assert (await mission.stop(7, Principal("owner"))).status is BuildStatus.STOPPED
  344. with pytest.raises(ProtocolViolation, match="forbidden after stop intent"):
  345. await planning.dispatch_script_tasks(
  346. task_ids=paragraph["task_ids"],
  347. context={"root_trace_id": root, "tool_call_id": "stop:late-dispatch"},
  348. )
  349. @pytest.mark.asyncio
  350. async def test_contract_store_is_content_addressed_and_detects_tampering(tmp_path: Path) -> None:
  351. store = FileScriptTaskContractStore(tmp_path)
  352. from script_build_host.domain.task_contracts import ScriptTaskContractV1
  353. contract = ScriptTaskContractV1.from_payload(_contract("paragraph"))
  354. first = await store.freeze("root-a", contract)
  355. second = await store.freeze("root-a", contract)
  356. assert first == second
  357. path = tmp_path / "script-task-contracts" / "root-a" / "sha256" / first.uri.rsplit("/", 1)[-1]
  358. path.write_bytes(b"{}")
  359. with pytest.raises(TaskContractError, match="TASK_CONTRACT_DIGEST_MISMATCH"):
  360. await store.read("root-a", first.uri)
  361. assert not await store.verify("root-a", first.uri, first.digest)
  362. @pytest.mark.asyncio
  363. async def test_orphan_contract_reclamation_uses_only_ledger_references(tmp_path: Path) -> None:
  364. service, _, root = await _service(tmp_path)
  365. referenced = await service.plan_script_tasks(
  366. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  367. parent_task_id=None,
  368. context={"root_trace_id": root, "tool_call_id": "portfolio"},
  369. )
  370. orphan = await service.contracts.freeze(
  371. root, ScriptTaskContractV1.from_payload(_contract("paragraph"))
  372. )
  373. removed = await service.reclaim_orphan_contracts(root_trace_id=root)
  374. assert removed == (orphan.uri,)
  375. assert await service.contracts.verify(
  376. root,
  377. referenced["contracts"][0]["contract_ref"],
  378. referenced["contracts"][0]["contract_digest"],
  379. )
  380. assert not await service.contracts.verify(root, orphan.uri, orphan.digest)
  381. @pytest.mark.asyncio
  382. async def test_failed_operation_discards_workspace_but_recovery_required_preserves_it(
  383. tmp_path: Path,
  384. ) -> None:
  385. service, _, root = await _service(tmp_path)
  386. class Lifecycle:
  387. def __init__(self) -> None:
  388. self.calls: list[dict[str, str]] = []
  389. async def discard_attempt(self, **values: str) -> None:
  390. self.calls.append(values)
  391. lifecycle = Lifecycle()
  392. service.workspace_lifecycle = lifecycle
  393. attempts = {
  394. "failed-attempt": SimpleNamespace(attempt_id="failed-attempt", task_id="paragraph-task"),
  395. "recovery-attempt": SimpleNamespace(
  396. attempt_id="recovery-attempt", task_id="paragraph-task"
  397. ),
  398. }
  399. ledger = SimpleNamespace(
  400. attempts=attempts,
  401. operations={
  402. "failed": SimpleNamespace(
  403. status=OperationStatus.FAILED,
  404. error="worker failed before submit",
  405. attempt_ids=["failed-attempt"],
  406. ),
  407. "recovery": SimpleNamespace(
  408. status=OperationStatus.FAILED,
  409. error="MISSION_RECOVERY_REQUIRED",
  410. attempt_ids=["recovery-attempt"],
  411. ),
  412. },
  413. )
  414. await service._reconcile_terminal_workspaces(root, ledger)
  415. assert lifecycle.calls == [
  416. {
  417. "root_trace_id": root,
  418. "task_id": "paragraph-task",
  419. "attempt_id": "failed-attempt",
  420. "reason": "worker failed before submit",
  421. }
  422. ]
  423. def test_comparison_refs_are_kind_specific_and_limits_cannot_be_raised() -> None:
  424. candidate_refs = []
  425. for index, kind in ((1, "paragraph"), (2, "structure")):
  426. candidate_refs.append(
  427. {
  428. "decision_id": f"decision-{index}",
  429. "artifact_ref": {
  430. "uri": f"script-build://artifact-versions/{index}",
  431. "kind": kind,
  432. "version": str(index),
  433. "digest": "sha256:" + str(index) * 64,
  434. },
  435. "scope_ref": "script-build://scopes/full",
  436. "expected_task_kind": kind,
  437. }
  438. )
  439. compare = _contract("compare")
  440. compare["comparison_decision_refs"] = candidate_refs
  441. assert ScriptTaskContractV1.from_payload(compare).task_kind.value == "compare"
  442. comparison_ref = {
  443. "decision_id": "decision-compare",
  444. "artifact_ref": {
  445. "uri": "script-build://artifact-versions/3",
  446. "kind": "comparison",
  447. "version": "3",
  448. "digest": "sha256:" + "3" * 64,
  449. },
  450. "scope_ref": "script-build://scopes/full",
  451. "expected_task_kind": "compare",
  452. }
  453. compose = _contract("compose")
  454. compose["comparison_decision_refs"] = [comparison_ref]
  455. ScriptTaskContractV1.from_payload(compose)
  456. portfolio = _contract("candidate-portfolio")
  457. portfolio["comparison_decision_refs"] = [comparison_ref]
  458. with pytest.raises(TaskContractError, match="comparison_decision_refs"):
  459. ScriptTaskContractV1.from_payload(portfolio)
  460. with pytest.raises(TaskContractError, match="TASK_BUDGET_EXCEEDED"):
  461. PhaseTwoLimits(max_tasks=65)
  462. @pytest.mark.asyncio
  463. async def test_planning_freezes_contract_and_creates_only_one_portfolio(tmp_path: Path) -> None:
  464. service, coordinator, root = await _service(tmp_path)
  465. result = await service.plan_script_tasks(
  466. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  467. parent_task_id=None,
  468. context={"root_trace_id": root, "tool_call_id": "plan-portfolio"},
  469. )
  470. task_id = result["task_ids"][0]
  471. ledger = await coordinator.task_store.load(root)
  472. task = ledger.tasks[task_id]
  473. assert task.current_spec.context_refs[0].endswith("candidate-portfolio")
  474. assert task.current_spec.context_refs[1].startswith("script-build://task-contracts/sha256/")
  475. assert task.current_spec.context_refs[2] == "script-build://inputs/11"
  476. frozen = await service.contract_for_task(root, task)
  477. assert frozen.contract.scope_ref == "script-build://scopes/full"
  478. with pytest.raises(TaskContractError, match="one Portfolio"):
  479. await service.plan_script_tasks(
  480. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  481. parent_task_id=None,
  482. context={"root_trace_id": root, "tool_call_id": "plan-portfolio-2"},
  483. )
  484. @pytest.mark.asyncio
  485. async def test_invalid_contract_batch_creates_zero_tasks(tmp_path: Path) -> None:
  486. service, coordinator, root = await _service(tmp_path)
  487. invalid = _contract("paragraph")
  488. invalid["output_schema"] = "structured-script/v1"
  489. with pytest.raises(TaskContractError, match="output_schema"):
  490. await service.plan_script_tasks(
  491. contract_payloads=[_contract("candidate-portfolio"), invalid],
  492. parent_task_id=None,
  493. context={"root_trace_id": root},
  494. )
  495. ledger = await coordinator.task_store.load(root)
  496. assert list(ledger.tasks) == [ledger.root_task_id]
  497. @pytest.mark.asyncio
  498. async def test_planning_rejects_unresolved_supersession_before_freeze(tmp_path: Path) -> None:
  499. service, coordinator, root = await _service(tmp_path)
  500. portfolio = await service.plan_script_tasks(
  501. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  502. parent_task_id=None,
  503. context={"root_trace_id": root, "tool_call_id": "portfolio"},
  504. )
  505. compose = await service.plan_script_tasks(
  506. contract_payloads=[_contract("compose", execution_ready=False)],
  507. parent_task_id=portfolio["task_ids"][0],
  508. context={"root_trace_id": root, "tool_call_id": "compose"},
  509. )
  510. replacement = _contract("paragraph")
  511. replacement["supersedes_decision_ids"] = ["missing-accept"]
  512. with pytest.raises(TaskContractError, match="import every superseded"):
  513. await service.plan_script_tasks(
  514. contract_payloads=[replacement],
  515. parent_task_id=compose["task_ids"][0],
  516. context={"root_trace_id": root, "tool_call_id": "invalid-replacement"},
  517. )
  518. ledger = await coordinator.task_store.load(root)
  519. assert set(ledger.tasks) == {
  520. ledger.root_task_id,
  521. portfolio["task_ids"][0],
  522. compose["task_ids"][0],
  523. }
  524. @pytest.mark.asyncio
  525. async def test_open_compose_container_cannot_dispatch(tmp_path: Path) -> None:
  526. service, coordinator, root = await _service(tmp_path)
  527. portfolio = await service.plan_script_tasks(
  528. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  529. parent_task_id=None,
  530. context={"root_trace_id": root, "tool_call_id": "p"},
  531. )
  532. compose = await service.plan_script_tasks(
  533. contract_payloads=[_contract("compose", execution_ready=False)],
  534. parent_task_id=portfolio["task_ids"][0],
  535. context={"root_trace_id": root, "tool_call_id": "c"},
  536. )
  537. with pytest.raises(TaskContractError, match="not closed"):
  538. await service.dispatch_script_tasks(
  539. task_ids=compose["task_ids"], context={"root_trace_id": root}
  540. )
  541. ledger = await coordinator.task_store.load(root)
  542. assert not ledger.operations
  543. @pytest.mark.asyncio
  544. async def test_compose_placeholder_split_replacement_then_revised_v2_passes(
  545. tmp_path: Path,
  546. ) -> None:
  547. service, coordinator, root = await _service(tmp_path)
  548. coordinator.set_executor(_PlaceholderThenReplacementExecutor(coordinator))
  549. portfolio = await service.plan_script_tasks(
  550. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  551. parent_task_id=None,
  552. context={"root_trace_id": root, "tool_call_id": "portfolio"},
  553. )
  554. compose = await service.plan_script_tasks(
  555. contract_payloads=[_contract("compose")],
  556. parent_task_id=portfolio["task_ids"][0],
  557. context={"root_trace_id": root, "tool_call_id": "compose-v1"},
  558. )
  559. compose_id = compose["task_ids"][0]
  560. first_cycle = (
  561. await service.dispatch_script_tasks(
  562. task_ids=(compose_id,),
  563. context={"root_trace_id": root, "tool_call_id": "dispatch-compose-v1"},
  564. )
  565. )[0]
  566. assert first_cycle["error"] is None
  567. ledger = await coordinator.task_store.load(root)
  568. first_validation = ledger.validations[first_cycle["validation_id"]]
  569. assert first_validation.verdict is ValidationVerdict.FAILED
  570. assert first_validation.unverified_claims == ["artifact.paragraphs[0].description"]
  571. assert first_validation.risks == ["REALIZATION_PLACEHOLDER"]
  572. split = await service.decide_script_task(
  573. task_id=compose_id,
  574. action=DecisionAction.SPLIT.value,
  575. reason="replace only the unrealized opening scope",
  576. validation_id=first_validation.validation_id,
  577. replacement_contract=None,
  578. child_contracts=(_contract("paragraph"),),
  579. context={"root_trace_id": root, "tool_call_id": "split-placeholder"},
  580. )
  581. replacement_id = split["payload"]["child_task_ids"][0]
  582. replacement_cycle = (
  583. await service.dispatch_script_tasks(
  584. task_ids=(replacement_id,),
  585. context={"root_trace_id": root, "tool_call_id": "dispatch-replacement"},
  586. )
  587. )[0]
  588. replacement_accept = await service.decide_script_task(
  589. task_id=replacement_id,
  590. action=DecisionAction.ACCEPT.value,
  591. reason="the local replacement passed independent validation",
  592. validation_id=replacement_cycle["validation_id"],
  593. replacement_contract=None,
  594. child_contracts=(),
  595. context={"root_trace_id": root, "tool_call_id": "accept-replacement"},
  596. )
  597. ledger = await coordinator.task_store.load(root)
  598. assert ledger.tasks[compose_id].status is TaskStatus.NEEDS_REPLAN
  599. replacement_decision_id = replacement_accept["decision_id"]
  600. replacement_attempt = ledger.attempts[
  601. cast(str, ledger.decisions[replacement_decision_id].attempt_id)
  602. ]
  603. assert replacement_attempt.submission is not None
  604. replacement_ref = replacement_attempt.submission.artifact_refs[0]
  605. frozen_replacement = {
  606. "decision_id": replacement_decision_id,
  607. "artifact_ref": {
  608. "uri": replacement_ref.uri,
  609. "kind": replacement_ref.kind,
  610. "version": replacement_ref.version,
  611. "digest": replacement_ref.digest,
  612. },
  613. "scope_ref": "script-build://scopes/full",
  614. "expected_task_kind": "paragraph",
  615. }
  616. compose_v2 = _contract("compose", execution_ready=False)
  617. compose_v2["candidate_closure_decision_refs"] = [frozen_replacement]
  618. compose_v2["adopted_decision_ids"] = [replacement_decision_id]
  619. compose_v2["compose_order"] = [replacement_decision_id]
  620. await service.decide_script_task(
  621. task_id=compose_id,
  622. action=DecisionAction.REVISE.value,
  623. reason="pin the accepted replacement and retry the complete render",
  624. validation_id=None,
  625. replacement_contract=compose_v2,
  626. child_contracts=(),
  627. context={"root_trace_id": root, "tool_call_id": "revise-compose-v2"},
  628. )
  629. second_cycle = (
  630. await service.dispatch_script_tasks(
  631. task_ids=(compose_id,),
  632. context={"root_trace_id": root, "tool_call_id": "dispatch-compose-v2"},
  633. )
  634. )[0]
  635. compose_accept = await service.decide_script_task(
  636. task_id=compose_id,
  637. action=DecisionAction.ACCEPT.value,
  638. reason="the revised full render passed independent validation",
  639. validation_id=second_cycle["validation_id"],
  640. replacement_contract=None,
  641. child_contracts=(),
  642. context={"root_trace_id": root, "tool_call_id": "accept-compose-v2"},
  643. )
  644. reloaded = await FileSystemTaskStore(str(tmp_path / "ledger")).load(root)
  645. compose_task = reloaded.tasks[compose_id]
  646. assert compose_task.status is TaskStatus.COMPLETED
  647. assert compose_task.current_spec_version == 2
  648. assert len(compose_task.attempt_ids) == 2
  649. assert [
  650. reloaded.validations[validation_id].verdict for validation_id in compose_task.validation_ids
  651. ] == [ValidationVerdict.FAILED, ValidationVerdict.PASSED]
  652. assert [reloaded.decisions[item].action for item in compose_task.decision_ids] == [
  653. DecisionAction.SPLIT,
  654. DecisionAction.REVISE,
  655. DecisionAction.ACCEPT,
  656. ]
  657. assert compose_accept["status"] == TaskStatus.COMPLETED.value
  658. assert reloaded.tasks[replacement_id].status is TaskStatus.COMPLETED
  659. @pytest.mark.asyncio
  660. @pytest.mark.parametrize(
  661. "creation_order",
  662. [
  663. ("element-set", "paragraph", "structure"),
  664. ("paragraph", "element-set", "structure"),
  665. ("structure", "paragraph", "element-set"),
  666. ],
  667. )
  668. async def test_exploration_order_and_completion_order_do_not_choose_compose_order(
  669. tmp_path: Path,
  670. creation_order: tuple[str, str, str],
  671. ) -> None:
  672. service, coordinator, root = await _service(tmp_path)
  673. coordinator.set_executor(_PlaceholderThenReplacementExecutor(coordinator))
  674. portfolio = await service.plan_script_tasks(
  675. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  676. parent_task_id=None,
  677. context={"root_trace_id": root, "tool_call_id": "portfolio"},
  678. )
  679. compose = await service.plan_script_tasks(
  680. contract_payloads=[_contract("compose", execution_ready=False)],
  681. parent_task_id=portfolio["task_ids"][0],
  682. context={"root_trace_id": root, "tool_call_id": "compose"},
  683. )
  684. compose_id = compose["task_ids"][0]
  685. task_by_kind: dict[str, str] = {}
  686. for kind in creation_order:
  687. planned = await service.plan_script_tasks(
  688. contract_payloads=[_contract(kind)],
  689. parent_task_id=compose_id,
  690. context={"root_trace_id": root, "tool_call_id": f"plan:{kind}"},
  691. )
  692. task_by_kind[kind] = planned["task_ids"][0]
  693. decision_by_kind: dict[str, str] = {}
  694. ref_by_kind: dict[str, ArtifactRef] = {}
  695. completion_order = tuple(reversed(creation_order))
  696. for kind in completion_order:
  697. task_id = task_by_kind[kind]
  698. cycle = (
  699. await service.dispatch_script_tasks(
  700. task_ids=(task_id,),
  701. context={"root_trace_id": root, "tool_call_id": f"dispatch:{kind}"},
  702. )
  703. )[0]
  704. accepted = await service.decide_script_task(
  705. task_id=task_id,
  706. action=DecisionAction.ACCEPT.value,
  707. reason=f"the bounded {kind} increment passed validation",
  708. validation_id=cycle["validation_id"],
  709. replacement_contract=None,
  710. child_contracts=(),
  711. context={"root_trace_id": root, "tool_call_id": f"accept:{kind}"},
  712. )
  713. decision_id = accepted["decision_id"]
  714. decision_by_kind[kind] = decision_id
  715. ledger = await coordinator.task_store.load(root)
  716. attempt = ledger.attempts[cast(str, ledger.decisions[decision_id].attempt_id)]
  717. assert attempt.submission is not None
  718. ref_by_kind[kind] = attempt.submission.artifact_refs[0]
  719. ledger = await coordinator.task_store.load(root)
  720. assert ledger.tasks[compose_id].status is TaskStatus.NEEDS_REPLAN
  721. adoption_kinds = ("paragraph", "structure", "element-set")
  722. closure = []
  723. for kind in adoption_kinds:
  724. ref = ref_by_kind[kind]
  725. closure.append(
  726. {
  727. "decision_id": decision_by_kind[kind],
  728. "artifact_ref": {
  729. "uri": ref.uri,
  730. "kind": ref.kind,
  731. "version": ref.version,
  732. "digest": ref.digest,
  733. },
  734. "scope_ref": "script-build://scopes/full",
  735. "expected_task_kind": kind,
  736. }
  737. )
  738. execution_ready = _contract("compose", execution_ready=False)
  739. execution_ready["candidate_closure_decision_refs"] = closure
  740. execution_ready["adopted_decision_ids"] = [decision_by_kind[kind] for kind in adoption_kinds]
  741. execution_ready["compose_order"] = [decision_by_kind[kind] for kind in adoption_kinds]
  742. await service.decide_script_task(
  743. task_id=compose_id,
  744. action=DecisionAction.REVISE.value,
  745. reason="formal adoption is based on scope and intent, not timing",
  746. validation_id=None,
  747. replacement_contract=execution_ready,
  748. child_contracts=(),
  749. context={"root_trace_id": root, "tool_call_id": "close-compose"},
  750. )
  751. reloaded = await FileSystemTaskStore(str(tmp_path / "ledger")).load(root)
  752. frozen = await service.contract_for_task(root, reloaded.tasks[compose_id])
  753. assert frozen.contract.compose_order == tuple(decision_by_kind[kind] for kind in adoption_kinds)
  754. assert [
  755. next(kind for kind, task_id in task_by_kind.items() if task_id == child_id)
  756. for child_id in reloaded.tasks[compose_id].child_task_ids
  757. ] == list(creation_order)
  758. assert completion_order == tuple(reversed(creation_order))
  759. @pytest.mark.asyncio
  760. async def test_phase_two_retrieval_counts_toward_task_and_depth_limits(tmp_path: Path) -> None:
  761. service, _, root = await _service(tmp_path)
  762. service.limits = PhaseTwoLimits(max_tasks=2)
  763. portfolio = await service.plan_script_tasks(
  764. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  765. parent_task_id=None,
  766. context={"root_trace_id": root, "tool_call_id": "portfolio"},
  767. )
  768. compose = await service.plan_script_tasks(
  769. contract_payloads=[_contract("compose", execution_ready=False)],
  770. parent_task_id=portfolio["task_ids"][0],
  771. context={"root_trace_id": root, "tool_call_id": "compose"},
  772. )
  773. with pytest.raises(TaskContractError, match="Task budget"):
  774. await service.plan_script_tasks(
  775. contract_payloads=[_contract("decode-retrieval")],
  776. parent_task_id=compose["task_ids"][0],
  777. context={"root_trace_id": root, "tool_call_id": "retrieval"},
  778. )
  779. service.limits = PhaseTwoLimits(max_depth=1)
  780. with pytest.raises(TaskContractError, match="depth"):
  781. await service.plan_script_tasks(
  782. contract_payloads=[_contract("structure", scope="script-build://scopes/full/local")],
  783. parent_task_id=compose["task_ids"][0],
  784. context={"root_trace_id": root, "tool_call_id": "too-deep"},
  785. )
  786. @pytest.mark.asyncio
  787. async def test_task_contract_cannot_be_silently_changed_in_task_spec(tmp_path: Path) -> None:
  788. service, coordinator, root = await _service(tmp_path)
  789. result = await service.plan_script_tasks(
  790. contract_payloads=[_contract("candidate-portfolio", execution_ready=False)],
  791. parent_task_id=None,
  792. context={"root_trace_id": root},
  793. )
  794. ledger = await coordinator.task_store.load(root)
  795. task = ledger.tasks[result["task_ids"][0]]
  796. task.specs[-1] = replace(task.specs[-1], objective="tampered")
  797. await coordinator.task_store.commit(ledger, expected_revision=ledger.revision)
  798. with pytest.raises(TaskContractError, match="DIGEST_MISMATCH"):
  799. await service.contract_for_task(root, task)