test_phase_two_contracts.py 45 KB

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