test_phase_two_contracts.py 49 KB

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