test_phase_two_contracts.py 39 KB

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