test_phase_two_contracts.py 45 KB

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