test_phase_two_candidates.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. from __future__ import annotations
  2. from dataclasses import replace
  3. from datetime import UTC, datetime
  4. from hashlib import sha256
  5. from types import SimpleNamespace
  6. from typing import Any, cast
  7. import pytest
  8. from agent.orchestration import ArtifactRef
  9. from script_build_host.application.phase_two_candidates import (
  10. CandidateScope,
  11. PhaseTwoCandidateError,
  12. PhaseTwoCandidateService,
  13. _candidate_state_revision,
  14. )
  15. from script_build_host.application.phase_two_inputs import (
  16. ActiveFrontierResolver,
  17. PhaseTwoInputError,
  18. )
  19. from script_build_host.domain.artifacts import (
  20. ArtifactKind,
  21. ArtifactState,
  22. ArtifactVersion,
  23. DirectionArtifact,
  24. DirectionGoal,
  25. EvidenceRecordV1,
  26. )
  27. from script_build_host.domain.errors import ProtocolViolation
  28. from script_build_host.domain.phase_two_artifacts import (
  29. CandidateLineageV1,
  30. CandidatePortfolioArtifactV1,
  31. ComparisonArtifactV1,
  32. ElementSetArtifactV1,
  33. GoalCoverage,
  34. ParagraphArtifactV1,
  35. ScriptElementV1,
  36. ScriptParagraphElementLinkV1,
  37. ScriptParagraphV1,
  38. StructureArtifactV1,
  39. StructuredScriptArtifactV1,
  40. )
  41. from script_build_host.domain.task_contracts import (
  42. AcceptedDecisionRef,
  43. AcceptedInput,
  44. AcceptedInputBundleV1,
  45. ScriptCriterion,
  46. ScriptIntentClass,
  47. ScriptTaskBudget,
  48. ScriptTaskContractV1,
  49. ScriptTaskKind,
  50. )
  51. from script_build_host.domain.workbench import paragraph_target_key, semantic_handle
  52. from script_build_host.domain.workspaces import CandidateWriteContext, WorkspaceError
  53. from script_build_host.infrastructure.canonical_json import canonical_sha256
  54. from script_build_host.repositories.sqlalchemy import (
  55. SqlAlchemyScriptBusinessArtifactRepository,
  56. )
  57. from script_build_host.repositories.workspace import (
  58. SqlAlchemyCandidateWorkspaceRepository,
  59. )
  60. DIGEST = "sha256:" + "a" * 64
  61. SCOPE = "script-build://scopes/opening"
  62. WRITE = "script-build://writes/paragraphs/opening"
  63. def _complete_paragraph() -> ScriptParagraphV1:
  64. atom = ({"原子点": "内容", "维度": "开场", "维度类型": "主维度"},)
  65. return ScriptParagraphV1(
  66. 1,
  67. 1,
  68. 1,
  69. None,
  70. "opening",
  71. {"beats": ["抛出问题", "给出答案"]},
  72. theme="为什么要主动改变",
  73. form="问题与回答",
  74. function="建立紧迫感",
  75. feeling="坚定且真诚",
  76. theme_elements=atom,
  77. form_elements=atom,
  78. function_elements=atom,
  79. feeling_elements=atom,
  80. description="先指出停滞的代价。再给出可执行的转折。",
  81. full_description="你可能一直在等待更好的时机。但真正的改变来自今天的第一步。",
  82. )
  83. def _complete_element() -> ScriptElementV1:
  84. return ScriptElementV1(1, "停滞代价", "实质", "核心论点")
  85. def _complete_link() -> ScriptParagraphElementLinkV1:
  86. return ScriptParagraphElementLinkV1(1, 1)
  87. def _lineage() -> CandidateLineageV1:
  88. return CandidateLineageV1(
  89. scope_ref=SCOPE,
  90. input_snapshot_ref="script-build://input-snapshots/11",
  91. input_closure_digest=DIGEST,
  92. write_scope=(WRITE,),
  93. goal_ids=("goal-1",),
  94. )
  95. def _source_artifacts() -> tuple[
  96. StructureArtifactV1,
  97. ParagraphArtifactV1,
  98. ElementSetArtifactV1,
  99. ]:
  100. paragraph = _complete_paragraph()
  101. element = _complete_element()
  102. link = _complete_link()
  103. lineage = _lineage()
  104. return (
  105. StructureArtifactV1(lineage, (paragraph,)),
  106. ParagraphArtifactV1(
  107. lineage,
  108. (paragraph,),
  109. (element,),
  110. (link,),
  111. {"created": {"paragraph_ids": [1]}},
  112. ),
  113. ElementSetArtifactV1(
  114. lineage,
  115. (element,),
  116. (link,),
  117. (paragraph,),
  118. {"created": {"element_ids": [1]}},
  119. ),
  120. )
  121. def _contract(
  122. kind: ScriptTaskKind,
  123. *,
  124. refs: tuple[AcceptedDecisionRef, ...] = (),
  125. comparison_refs: tuple[AcceptedDecisionRef, ...] = (),
  126. adopted: tuple[str, ...] = (),
  127. held: tuple[str, ...] = (),
  128. order: tuple[str, ...] = (),
  129. ) -> ScriptTaskContractV1:
  130. schemas = {
  131. ScriptTaskKind.PARAGRAPH: "paragraph-artifact/v1",
  132. ScriptTaskKind.DECODE_RETRIEVAL: "evidence-record/v1",
  133. ScriptTaskKind.COMPARE: "comparison-artifact/v1",
  134. ScriptTaskKind.COMPOSE: "structured-script/v1",
  135. ScriptTaskKind.CANDIDATE_PORTFOLIO: "candidate-portfolio/v1",
  136. }
  137. return ScriptTaskContractV1(
  138. task_kind=kind,
  139. scope_ref=SCOPE,
  140. intent_class=(
  141. ScriptIntentClass.COMPOSE
  142. if kind is ScriptTaskKind.COMPOSE
  143. else ScriptIntentClass.COMPARE
  144. if kind is ScriptTaskKind.COMPARE
  145. else ScriptIntentClass.EXPLORE
  146. ),
  147. objective="produce one bounded candidate increment",
  148. input_decision_refs=refs if kind is ScriptTaskKind.PARAGRAPH else (),
  149. base_artifact_ref=None,
  150. write_scope=(WRITE,),
  151. gap_ref=None,
  152. output_schema=schemas[kind],
  153. criteria=(ScriptCriterion("closed", "output is concretely complete"),),
  154. budget=ScriptTaskBudget(),
  155. goal_ids=("goal-1",),
  156. candidate_closure_decision_refs=(
  157. refs if kind in {ScriptTaskKind.COMPOSE, ScriptTaskKind.CANDIDATE_PORTFOLIO} else ()
  158. ),
  159. adopted_decision_ids=adopted,
  160. held_or_rejected_decision_ids=held,
  161. compose_order=order,
  162. comparison_decision_refs=comparison_refs,
  163. )
  164. class _Bindings:
  165. def __init__(self, active_direction_artifact_version_id: int = 10) -> None:
  166. self.active_direction_artifact_version_id = active_direction_artifact_version_id
  167. async def get_by_root(self, root_trace_id: str) -> Any:
  168. return SimpleNamespace(
  169. root_trace_id=root_trace_id,
  170. script_build_id=7,
  171. input_snapshot_id=11,
  172. active_direction_artifact_version_id=self.active_direction_artifact_version_id,
  173. )
  174. class _TaskStore:
  175. def __init__(self, ledger: Any) -> None:
  176. self.ledger = ledger
  177. async def load(self, root_trace_id: str) -> Any:
  178. assert root_trace_id == "root"
  179. return self.ledger
  180. class _AcceptedInputs:
  181. def __init__(
  182. self, contracts: dict[str, ScriptTaskContractV1], bundle: AcceptedInputBundleV1
  183. ) -> None:
  184. self.contracts = contracts
  185. self.bundle = bundle
  186. async def contract_for_task(self, *, task: Any, **_: Any) -> ScriptTaskContractV1:
  187. return self.contracts[task.task_id]
  188. async def resolve(self, **_: Any) -> AcceptedInputBundleV1:
  189. return self.bundle
  190. class _FrameworkArtifacts:
  191. async def get(self, *_: Any) -> Any:
  192. raise AssertionError("framework snapshot should not be read")
  193. class _SnapshotArtifacts:
  194. def __init__(self, ref: ArtifactRef) -> None:
  195. self.ref = ref
  196. async def get(self, root_trace_id: str, snapshot_id: str) -> Any:
  197. assert (root_trace_id, snapshot_id) == ("root", "validation-snapshot")
  198. return SimpleNamespace(artifact_refs=[self.ref], evidence_refs=[])
  199. class _RawStore:
  200. def __init__(self, content: bytes) -> None:
  201. self.content = content
  202. async def read_bytes(self, ref: str) -> bytes:
  203. assert ref.endswith(sha256(self.content).hexdigest())
  204. return self.content
  205. class _Artifacts:
  206. def __init__(self, versions: dict[str, ArtifactVersion]) -> None:
  207. self.versions = versions
  208. self.frozen: ArtifactVersion | None = None
  209. async def read_by_ref(self, ref: ArtifactRef, **_: Any) -> ArtifactVersion:
  210. return self.versions[ref.uri]
  211. async def get_by_attempt(self, **owners: Any) -> ArtifactVersion:
  212. for value in self.versions.values():
  213. if value.attempt_id == owners["attempt_id"]:
  214. return value
  215. raise AssertionError("Attempt artifact not found")
  216. async def get_by_id(self, identifier: int, **_: Any) -> ArtifactVersion:
  217. for value in self.versions.values():
  218. if value.artifact_version_id == identifier:
  219. return value
  220. if identifier != 10:
  221. raise AssertionError("Artifact version not found")
  222. direction = DirectionArtifact(
  223. goals=(
  224. DirectionGoal(
  225. "goal-1",
  226. "complete the script",
  227. "the delivery needs one complete script",
  228. success_criteria=("the script is complete",),
  229. ),
  230. ),
  231. evidence_refs=("script-build://artifact-versions/90",),
  232. )
  233. return ArtifactVersion(
  234. 10,
  235. 7,
  236. "direction",
  237. "direction-attempt",
  238. 1,
  239. ArtifactKind.DIRECTION,
  240. DIGEST,
  241. ArtifactState.FROZEN,
  242. direction,
  243. datetime.now(UTC),
  244. datetime.now(UTC),
  245. )
  246. async def freeze(self, *, artifact: Any, **owners: Any) -> tuple[ArtifactVersion, ArtifactRef]:
  247. digest = canonical_sha256(artifact.content_payload()).wire
  248. artifact = replace(artifact, canonical_sha256=digest)
  249. artifact_kind = (
  250. ArtifactKind.COMPARISON
  251. if isinstance(artifact, ComparisonArtifactV1)
  252. else ArtifactKind.CANDIDATE_PORTFOLIO
  253. )
  254. version = ArtifactVersion(
  255. artifact_version_id=99,
  256. script_build_id=owners["script_build_id"],
  257. task_id=owners["task_id"],
  258. attempt_id=owners["attempt_id"],
  259. spec_version=owners["spec_version"],
  260. artifact_type=artifact_kind,
  261. canonical_sha256=digest,
  262. state=ArtifactState.FROZEN,
  263. artifact=artifact,
  264. created_at=datetime.now(UTC),
  265. frozen_at=datetime.now(UTC),
  266. )
  267. self.frozen = version
  268. ref = ArtifactRef(
  269. "script-build://artifact-versions/99",
  270. artifact_kind.value,
  271. "99",
  272. digest,
  273. )
  274. self.versions[ref.uri] = version
  275. return version, ref
  276. def _scope_fixture(
  277. contract: ScriptTaskContractV1,
  278. *,
  279. bundle: AcceptedInputBundleV1 | None = None,
  280. task_id: str = "task",
  281. attempt_id: str = "attempt",
  282. ) -> tuple[Any, dict[str, Any]]:
  283. task = SimpleNamespace(task_id=task_id, attempt_ids=[attempt_id])
  284. attempt = SimpleNamespace(
  285. attempt_id=attempt_id,
  286. task_id=task_id,
  287. spec_version=1,
  288. accepted_child_decision_ids=(),
  289. )
  290. ledger = SimpleNamespace(
  291. tasks={task_id: task},
  292. attempts={attempt_id: attempt},
  293. decisions={},
  294. revision=1,
  295. )
  296. accepted = _AcceptedInputs(
  297. {task_id: contract},
  298. bundle or AcceptedInputBundleV1((), DIGEST),
  299. )
  300. return (ledger, accepted), {
  301. "root_trace_id": "root",
  302. "task_id": task_id,
  303. "attempt_id": attempt_id,
  304. "spec_version": 1,
  305. }
  306. @pytest.mark.asyncio
  307. async def test_phase_one_manifest_does_not_require_candidate_workspace() -> None:
  308. contract = _contract(ScriptTaskKind.DECODE_RETRIEVAL)
  309. (ledger, accepted), context = _scope_fixture(contract)
  310. evidence = EvidenceRecordV1(
  311. evidence_id="evidence",
  312. source_type="decode",
  313. tool_name="retrieve_decode",
  314. query={},
  315. source_refs=("source",),
  316. raw_artifact_ref=None,
  317. summary="bounded evidence",
  318. supports=("goal",),
  319. confidence="high",
  320. limitations=(),
  321. content_sha256=DIGEST,
  322. created_at=datetime.now(UTC),
  323. )
  324. version = ArtifactVersion(
  325. 1,
  326. 7,
  327. "task",
  328. "attempt",
  329. 1,
  330. ArtifactKind.EVIDENCE,
  331. DIGEST,
  332. ArtifactState.FROZEN,
  333. evidence,
  334. datetime.now(UTC),
  335. datetime.now(UTC),
  336. )
  337. service = PhaseTwoCandidateService(
  338. bindings=cast(Any, _Bindings()),
  339. task_store=_TaskStore(ledger),
  340. framework_artifact_store=_FrameworkArtifacts(),
  341. artifacts=cast(Any, _Artifacts({"script-build://artifact-versions/1": version})),
  342. accepted_inputs=accepted,
  343. active_frontier=ActiveFrontierResolver(),
  344. workspaces=None,
  345. )
  346. manifest = await service.resolve_attempt_manifest(context=context)
  347. assert manifest.artifact_ref.kind == "evidence"
  348. assert manifest.scope_ref == SCOPE
  349. @pytest.mark.asyncio
  350. async def test_paragraph_workspace_uses_positive_branch_and_freezes_on_manifest(
  351. database: Any,
  352. ) -> None:
  353. _, sessions = database
  354. repository = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  355. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, repository)
  356. contract = _contract(ScriptTaskKind.PARAGRAPH)
  357. (ledger, accepted), context = _scope_fixture(contract)
  358. service = PhaseTwoCandidateService(
  359. bindings=cast(Any, _Bindings()),
  360. task_store=_TaskStore(ledger),
  361. framework_artifact_store=_FrameworkArtifacts(),
  362. artifacts=repository,
  363. accepted_inputs=accepted,
  364. active_frontier=ActiveFrontierResolver(),
  365. workspaces=workspaces,
  366. )
  367. created = await service.create_script_paragraph(
  368. payload={"paragraph_index": 1, "name": "opening", "content_range": {}},
  369. context=context,
  370. )
  371. manifest = await service.resolve_attempt_manifest(context=context)
  372. version = await repository.get_by_attempt(
  373. script_build_id=7, task_id="task", attempt_id="attempt"
  374. )
  375. assert created["paragraph_id"] > 0
  376. assert version.artifact_version_id > 0
  377. assert manifest.artifact_ref.digest == version.canonical_sha256
  378. assert manifest.artifact_ref.kind == "paragraph"
  379. with pytest.raises(PhaseTwoCandidateError, match="WRITE_SCOPE_VIOLATION"):
  380. await service.create_script_paragraph(
  381. payload={
  382. "paragraph_index": 2,
  383. "name": "forged",
  384. "content_range": {},
  385. "branch_id": 0,
  386. },
  387. context=context,
  388. )
  389. @pytest.mark.asyncio
  390. async def test_semantic_paragraph_save_is_atomic_and_exact_replay_is_idempotent(
  391. database: Any,
  392. ) -> None:
  393. _, sessions = database
  394. repository = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  395. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, repository)
  396. contract = _contract(ScriptTaskKind.PARAGRAPH)
  397. (ledger, accepted), context = _scope_fixture(contract)
  398. service = PhaseTwoCandidateService(
  399. bindings=cast(Any, _Bindings()),
  400. task_store=_TaskStore(ledger),
  401. framework_artifact_store=_FrameworkArtifacts(),
  402. artifacts=repository,
  403. accepted_inputs=accepted,
  404. active_frontier=ActiveFrontierResolver(),
  405. workspaces=workspaces,
  406. )
  407. scope = await service._workspace_scope(context, paragraph=True)
  408. before = await workspaces.snapshot(scope.write_context)
  409. revision = _candidate_state_revision(scope, before, ledger.revision)
  410. atom = [{"原子点": "observable reversal", "维度": "opening", "维度类型": "主维度"}]
  411. payload = (
  412. {
  413. "client_key": "opening",
  414. "paragraph_index": 1,
  415. "name": "opening",
  416. "content_range": {"scope": "opening"},
  417. "level": 1,
  418. "theme_elements": atom,
  419. "form_elements": atom,
  420. "function_elements": atom,
  421. "feeling_elements": [{"原子点": "curiosity", "维度": "tone"}],
  422. "theme": "A visible detail changes the original assumption.",
  423. "form": "Concrete setup followed by a concise reversal.",
  424. "function": "Give the audience a reason to continue.",
  425. "feeling": "Measured surprise grounded in observation.",
  426. "description": "The opening overturns one assumption with evidence.",
  427. "full_description": (
  428. "Start from a familiar expectation and show exactly how the observed "
  429. "detail changes it."
  430. ),
  431. },
  432. )
  433. first = await service.save_script_paragraphs(
  434. paragraphs=payload,
  435. expected_state_revision=revision,
  436. context=context,
  437. )
  438. replay = await service.save_script_paragraphs(
  439. paragraphs=payload,
  440. expected_state_revision=revision,
  441. context=context,
  442. )
  443. assert first["status"] == "saved"
  444. assert first["created"] == 1
  445. assert replay["status"] == "not_modified"
  446. assert replay["created"] == replay["updated"] == 0
  447. assert replay["changed_target_keys"] == first["changed_target_keys"]
  448. assert len((await workspaces.snapshot(scope.write_context)).paragraphs) == 1
  449. changed_payload = (dict(payload[0], name="changed after stale projection"),)
  450. with pytest.raises(PhaseTwoCandidateError, match="STALE_WORKBENCH_STATE"):
  451. await service.save_script_paragraphs(
  452. paragraphs=changed_payload,
  453. expected_state_revision=revision,
  454. context=context,
  455. )
  456. @pytest.mark.asyncio
  457. async def test_paragraph_batch_maps_parent_keys_and_rolls_back_atomically(database: Any) -> None:
  458. _, sessions = database
  459. repository = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  460. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, repository)
  461. contract = _contract(ScriptTaskKind.PARAGRAPH)
  462. (ledger, accepted), context = _scope_fixture(contract)
  463. service = PhaseTwoCandidateService(
  464. bindings=cast(Any, _Bindings()),
  465. task_store=_TaskStore(ledger),
  466. framework_artifact_store=_FrameworkArtifacts(),
  467. artifacts=repository,
  468. accepted_inputs=accepted,
  469. active_frontier=ActiveFrontierResolver(),
  470. workspaces=workspaces,
  471. )
  472. created = await service.create_script_paragraphs(
  473. paragraphs=(
  474. {
  475. "client_key": "root",
  476. "paragraph_index": 1,
  477. "name": "opening",
  478. "content_range": {"beats": ["setup", "turn"]},
  479. "theme": "具体主题正文",
  480. "form": "对话漫画",
  481. "function": "建立冲突",
  482. "feeling": "好奇",
  483. "description": "角色在器械旁发生可见冲突。",
  484. "full_description": "角色先指责别人占用器械,随后被发现自己也在刷手机。",
  485. },
  486. {
  487. "client_key": "child",
  488. "parent_client_key": "root",
  489. "paragraph_index": 2,
  490. "level": 2,
  491. "name": "turn",
  492. "content_range": {"beats": ["turn"]},
  493. },
  494. ),
  495. context=context,
  496. )
  497. assert created["created"] == 2
  498. assert set(created["paragraph_ids_by_client_key"]) == {"root", "child"}
  499. workspace = await service.read_attempt_workspace(context=context)
  500. root_row = next(item for item in workspace["paragraphs"] if item["name"] == "opening")
  501. assert root_row["theme"] == "具体主题正文"
  502. assert root_row["full_description"].endswith("自己也在刷手机。")
  503. contract2 = replace(contract, objective="second isolated workspace")
  504. (ledger2, accepted2), context2 = _scope_fixture(
  505. contract2, task_id="task-2", attempt_id="attempt-2"
  506. )
  507. service2 = PhaseTwoCandidateService(
  508. bindings=cast(Any, _Bindings()),
  509. task_store=_TaskStore(ledger2),
  510. framework_artifact_store=_FrameworkArtifacts(),
  511. artifacts=repository,
  512. accepted_inputs=accepted2,
  513. active_frontier=ActiveFrontierResolver(),
  514. workspaces=workspaces,
  515. )
  516. with pytest.raises(WorkspaceError, match="child content range"):
  517. await service2.create_script_paragraphs(
  518. paragraphs=(
  519. {
  520. "client_key": "root",
  521. "paragraph_index": 1,
  522. "name": "root",
  523. "content_range": {"beats": ["setup"]},
  524. },
  525. {
  526. "client_key": "child",
  527. "parent_client_key": "root",
  528. "paragraph_index": 2,
  529. "level": 2,
  530. "name": "child",
  531. "content_range": {"beats": ["missing"]},
  532. },
  533. ),
  534. context=context2,
  535. )
  536. write_context = CandidateWriteContext(
  537. script_build_id=7,
  538. task_id="task-2",
  539. attempt_id="attempt-2",
  540. spec_version=1,
  541. objective=contract2.objective,
  542. input_refs=(),
  543. write_scope=contract2.write_scope,
  544. )
  545. assert not (await workspaces.snapshot(write_context)).paragraphs
  546. @pytest.mark.asyncio
  547. async def test_element_set_materializes_all_accepted_paragraphs_before_linking(
  548. database: Any,
  549. ) -> None:
  550. _, sessions = database
  551. repository = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  552. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, repository)
  553. paragraph = replace(
  554. _complete_paragraph(),
  555. theme_elements=(({"原子点": "内容", "维度": "主题", "维度类型": "主维度"}),),
  556. form_elements=(({"原子点": "对话", "维度": "形式", "维度类型": "主维度"}),),
  557. function_elements=(({"原子点": "冲突", "维度": "作用", "维度类型": "主维度"}),),
  558. feeling_elements=(({"原子点": "好奇", "维度": "感受"}),),
  559. )
  560. _, paragraph_ref = await repository.freeze(
  561. script_build_id=7,
  562. task_id="paragraph-source",
  563. attempt_id="paragraph-source-attempt",
  564. spec_version=1,
  565. artifact=ParagraphArtifactV1(
  566. _lineage(),
  567. (paragraph,),
  568. (),
  569. (),
  570. {"created": {"paragraph_ids": [1]}},
  571. ),
  572. )
  573. paragraph_ref = ArtifactRef(
  574. paragraph_ref.uri,
  575. paragraph_ref.kind,
  576. paragraph_ref.version,
  577. paragraph_ref.digest,
  578. )
  579. accepted_ref = AcceptedDecisionRef(
  580. "paragraph-decision",
  581. paragraph_ref,
  582. SCOPE,
  583. ScriptTaskKind.PARAGRAPH,
  584. )
  585. contract = ScriptTaskContractV1(
  586. task_kind=ScriptTaskKind.ELEMENT_SET,
  587. scope_ref=SCOPE,
  588. intent_class=ScriptIntentClass.EXPLORE,
  589. objective="attach concrete elements to every accepted paragraph",
  590. input_decision_refs=(accepted_ref,),
  591. base_artifact_ref=None,
  592. write_scope=("script-build://writes/elements",),
  593. gap_ref=None,
  594. output_schema="element-set-artifact/v1",
  595. criteria=(ScriptCriterion("closed", "all elements are linked"),),
  596. budget=ScriptTaskBudget(),
  597. goal_ids=("goal-1",),
  598. )
  599. bundle = AcceptedInputBundleV1(
  600. (
  601. AcceptedInput(
  602. "paragraph-decision",
  603. paragraph_ref,
  604. ScriptTaskKind.PARAGRAPH,
  605. SCOPE,
  606. "explicit",
  607. ),
  608. ),
  609. DIGEST,
  610. )
  611. (ledger, accepted), context = _scope_fixture(contract, bundle=bundle)
  612. service = PhaseTwoCandidateService(
  613. bindings=cast(Any, _Bindings()),
  614. task_store=_TaskStore(ledger),
  615. framework_artifact_store=_FrameworkArtifacts(),
  616. artifacts=repository,
  617. accepted_inputs=accepted,
  618. active_frontier=ActiveFrontierResolver(),
  619. workspaces=workspaces,
  620. )
  621. workspace = await service.read_attempt_workspace(context=context)
  622. assert len(workspace["paragraphs"]) == 1
  623. paragraph_id = workspace["paragraphs"][0]["paragraph_id"]
  624. assert paragraph_id > 0
  625. assert workspace["paragraphs"][0]["full_description"]
  626. with pytest.raises(WorkspaceError, match="link paragraph"):
  627. await service.create_script_elements(
  628. elements=(
  629. {
  630. "client_key": "invalid",
  631. "name": "不应落库的元素",
  632. "dimension_primary": "实质",
  633. "dimension_secondary": "回滚验证",
  634. },
  635. ),
  636. links=(
  637. {
  638. "paragraph_id": paragraph_id + 999,
  639. "element_client_keys": ["invalid"],
  640. },
  641. ),
  642. context=context,
  643. )
  644. rolled_back = await service.read_attempt_workspace(context=context)
  645. assert rolled_back["elements"] == []
  646. assert rolled_back["paragraph_element_links"] == []
  647. scope = await service._workspace_scope(context, element=True)
  648. before = await workspaces.snapshot(scope.write_context)
  649. revision = _candidate_state_revision(scope, before, ledger.revision)
  650. target = paragraph_target_key("root", "task", "attempt", paragraph_id)
  651. elements = (
  652. {
  653. "client_key": "machine",
  654. "name": "被占用的高位下拉机",
  655. "dimension_primary": "实质",
  656. "dimension_secondary": "冲突道具",
  657. },
  658. {
  659. "client_key": "bubble",
  660. "name": "占着不练的对话气泡",
  661. "dimension_primary": "形式",
  662. "dimension_secondary": "视觉文字",
  663. },
  664. )
  665. links = (
  666. {
  667. "paragraph_target_key": target,
  668. "element_client_keys": ["machine", "bubble"],
  669. },
  670. )
  671. created = await service.save_script_elements(
  672. elements=elements,
  673. links=links,
  674. expected_state_revision=revision,
  675. context=context,
  676. )
  677. replay = await service.save_script_elements(
  678. elements=elements,
  679. links=links,
  680. expected_state_revision=revision,
  681. context=context,
  682. )
  683. assert created["status"] == "saved"
  684. assert created["created"] == 2
  685. assert created["linked"] == 2
  686. assert replay["status"] == "not_modified"
  687. final = await workspaces.snapshot(scope.write_context)
  688. assert len(final.elements) == 2
  689. assert len(final.links) == 2
  690. changed_elements = (dict(elements[0], name="changed after stale projection"), elements[1])
  691. with pytest.raises(PhaseTwoCandidateError, match="STALE_WORKBENCH_STATE"):
  692. await service.save_script_elements(
  693. elements=changed_elements,
  694. links=links,
  695. expected_state_revision=revision,
  696. context=context,
  697. )
  698. manifest = await service.resolve_attempt_manifest(context=context)
  699. assert manifest.artifact_ref.kind == ArtifactKind.ELEMENT_SET.value
  700. @pytest.mark.asyncio
  701. async def test_element_seed_lineage_survives_full_compose_projection(database: Any) -> None:
  702. _, sessions = database
  703. artifacts = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  704. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, artifacts)
  705. paragraph = _complete_paragraph()
  706. structure_version, structure_ref = await artifacts.freeze(
  707. script_build_id=7,
  708. task_id="structure-source",
  709. attempt_id="structure-attempt",
  710. spec_version=1,
  711. artifact=StructureArtifactV1(_lineage(), (paragraph,)),
  712. )
  713. paragraph_lineage = replace(
  714. _lineage(),
  715. base_artifact_ref=structure_ref.uri,
  716. base_artifact_digest=structure_ref.digest,
  717. base_revision=structure_version.artifact_version_id,
  718. source_lineage=(
  719. {"entity": "paragraph", "local_id": 1, "source_local_id": 1},
  720. ),
  721. )
  722. paragraph_version, paragraph_ref = await artifacts.freeze(
  723. script_build_id=7,
  724. task_id="paragraph-source",
  725. attempt_id="paragraph-attempt",
  726. spec_version=1,
  727. artifact=ParagraphArtifactV1(
  728. paragraph_lineage,
  729. (paragraph,),
  730. (),
  731. (),
  732. {"created": {"paragraph_ids": [1]}},
  733. ),
  734. )
  735. element_context = CandidateWriteContext(
  736. script_build_id=7,
  737. task_id="element-task",
  738. attempt_id="element-attempt",
  739. spec_version=1,
  740. objective="link one grounded element",
  741. input_refs=(paragraph_ref.uri,),
  742. write_scope=("script-build://writes/elements",),
  743. )
  744. await workspaces.get_or_create(element_context, artifact_kind=ArtifactKind.ELEMENT_SET)
  745. seeded = await workspaces.seed_from_accepted_artifacts(
  746. element_context, (paragraph_version,)
  747. )
  748. seeded_id = seeded.paragraphs[0].paragraph_id
  749. await workspaces.create_elements(
  750. element_context,
  751. (
  752. {
  753. "client_key": "element",
  754. "name": "grounded element",
  755. "dimension_primary": "实质",
  756. "dimension_secondary": "观察",
  757. },
  758. ),
  759. ({"paragraph_id": seeded_id, "element_client_keys": ["element"]},),
  760. )
  761. element_version, element_ref = await workspaces.freeze(
  762. element_context,
  763. lineage=replace(
  764. _lineage(),
  765. write_scope=("script-build://writes/elements",),
  766. ),
  767. )
  768. assert element_version.artifact.lineage.source_lineage[0]["source_artifact_ref"] == (
  769. paragraph_ref.uri
  770. )
  771. compose_contract = replace(
  772. _contract(ScriptTaskKind.COMPOSE),
  773. write_scope=("script-build://writes",),
  774. )
  775. compose_context = CandidateWriteContext(
  776. script_build_id=7,
  777. task_id="compose-task",
  778. attempt_id="compose-attempt",
  779. spec_version=1,
  780. objective=compose_contract.objective,
  781. input_refs=(structure_ref.uri, paragraph_ref.uri, element_ref.uri),
  782. write_scope=compose_contract.write_scope,
  783. )
  784. await workspaces.get_or_create(
  785. compose_context, artifact_kind=ArtifactKind.STRUCTURED_SCRIPT
  786. )
  787. scope = CandidateScope(
  788. root_trace_id="root",
  789. script_build_id=7,
  790. input_snapshot_id="11",
  791. task=SimpleNamespace(task_id="compose-task"),
  792. attempt=SimpleNamespace(attempt_id="compose-attempt", spec_version=1),
  793. contract=compose_contract,
  794. write_context=compose_context,
  795. )
  796. service = PhaseTwoCandidateService(
  797. bindings=cast(Any, _Bindings()),
  798. task_store=cast(Any, _TaskStore(SimpleNamespace())),
  799. framework_artifact_store=_FrameworkArtifacts(),
  800. artifacts=artifacts,
  801. accepted_inputs=cast(Any, None),
  802. active_frontier=ActiveFrontierResolver(),
  803. workspaces=workspaces,
  804. )
  805. await service._materialize(
  806. scope,
  807. (structure_version, paragraph_version, element_version),
  808. (),
  809. )
  810. composed = await workspaces.snapshot(compose_context)
  811. assert len(composed.paragraphs) == 1
  812. assert len(composed.elements) == 1
  813. assert len(composed.links) == 1
  814. @pytest.mark.asyncio
  815. async def test_element_seed_disambiguates_same_local_id_and_replays_idempotently(
  816. database: Any,
  817. ) -> None:
  818. _, sessions = database
  819. artifacts = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  820. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, artifacts)
  821. versions: list[ArtifactVersion] = []
  822. refs: list[ArtifactRef] = []
  823. for index in (1, 2):
  824. paragraph = replace(
  825. _complete_paragraph(),
  826. name=f"paragraph-{index}",
  827. full_description=f"complete source paragraph {index}",
  828. )
  829. version, ref = await artifacts.freeze(
  830. script_build_id=7,
  831. task_id=f"paragraph-{index}",
  832. attempt_id=f"paragraph-attempt-{index}",
  833. spec_version=1,
  834. artifact=ParagraphArtifactV1(
  835. _lineage(),
  836. (paragraph,),
  837. (),
  838. (),
  839. {"created": {"paragraph_ids": [1]}},
  840. ),
  841. )
  842. versions.append(version)
  843. refs.append(ref)
  844. context = CandidateWriteContext(
  845. script_build_id=7,
  846. task_id="element-multi",
  847. attempt_id="element-multi-attempt",
  848. spec_version=1,
  849. objective="seed two accepted paragraphs",
  850. input_refs=tuple(item.uri for item in refs),
  851. write_scope=("script-build://writes/elements",),
  852. )
  853. await workspaces.get_or_create(context, artifact_kind=ArtifactKind.ELEMENT_SET)
  854. first = await workspaces.seed_from_accepted_artifacts(context, tuple(versions))
  855. replay = await workspaces.seed_from_accepted_artifacts(context, tuple(reversed(versions)))
  856. assert len(first.paragraphs) == len(replay.paragraphs) == 2
  857. assert {item["source_local_id"] for item in first.source_identity_map} == {1}
  858. assert {item["source_artifact_ref"] for item in first.source_identity_map} == {
  859. item.uri for item in refs
  860. }
  861. @pytest.mark.asyncio
  862. async def test_candidate_service_discards_existing_draft_workspace_on_abandoned_attempt(
  863. database: Any,
  864. ) -> None:
  865. _, sessions = database
  866. repository = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  867. workspaces = SqlAlchemyCandidateWorkspaceRepository(sessions, repository)
  868. contract = _contract(ScriptTaskKind.PARAGRAPH)
  869. (ledger, accepted), context = _scope_fixture(contract)
  870. service = PhaseTwoCandidateService(
  871. bindings=cast(Any, _Bindings()),
  872. task_store=_TaskStore(ledger),
  873. framework_artifact_store=_FrameworkArtifacts(),
  874. artifacts=repository,
  875. accepted_inputs=accepted,
  876. active_frontier=ActiveFrontierResolver(),
  877. workspaces=workspaces,
  878. )
  879. await service.create_script_paragraph(
  880. payload={"paragraph_index": 1, "name": "draft", "content_range": {}},
  881. context=context,
  882. )
  883. await service.discard_attempt(
  884. root_trace_id="root",
  885. task_id="task",
  886. attempt_id="attempt",
  887. reason="validator blocked the bounded increment",
  888. )
  889. write_context = CandidateWriteContext(
  890. script_build_id=7,
  891. task_id="task",
  892. attempt_id="attempt",
  893. spec_version=1,
  894. objective=contract.objective,
  895. input_refs=(),
  896. write_scope=contract.write_scope,
  897. )
  898. assert (await workspaces.require(write_context)).state is ArtifactState.DISCARDED
  899. with pytest.raises(WorkspaceError, match="ATTEMPT_WORKSPACE_FROZEN"):
  900. await service.create_script_paragraph(
  901. payload={"paragraph_index": 2, "name": "late", "content_range": {}},
  902. context=context,
  903. )
  904. @pytest.mark.asyncio
  905. async def test_frozen_image_must_be_accepted_and_digest_and_mime_are_rechecked() -> None:
  906. content = b"\x89PNG\r\n\x1a\n" + b"safe"
  907. raw_ref = f"script-build://raw-artifacts/sha256/{sha256(content).hexdigest()}"
  908. ref = ArtifactRef("script-build://artifact-versions/2", "evidence", "2", DIGEST)
  909. item = AcceptedInput("d1", ref, ScriptTaskKind.DECODE_RETRIEVAL, SCOPE, "explicit")
  910. bundle = AcceptedInputBundleV1((item,), DIGEST)
  911. contract = _contract(ScriptTaskKind.PARAGRAPH)
  912. (ledger, accepted), context = _scope_fixture(contract, bundle=bundle)
  913. evidence = EvidenceRecordV1(
  914. "e",
  915. "decode",
  916. "retrieve_decode",
  917. {},
  918. ("source",),
  919. raw_ref,
  920. "summary",
  921. ("goal",),
  922. "high",
  923. (),
  924. DIGEST,
  925. datetime.now(UTC),
  926. )
  927. version = ArtifactVersion(
  928. 2,
  929. 7,
  930. "child",
  931. "child-attempt",
  932. 1,
  933. ArtifactKind.EVIDENCE,
  934. DIGEST,
  935. ArtifactState.FROZEN,
  936. evidence,
  937. datetime.now(UTC),
  938. datetime.now(UTC),
  939. )
  940. service = PhaseTwoCandidateService(
  941. bindings=cast(Any, _Bindings()),
  942. task_store=_TaskStore(ledger),
  943. framework_artifact_store=_FrameworkArtifacts(),
  944. artifacts=cast(Any, _Artifacts({ref.uri: version})),
  945. accepted_inputs=accepted,
  946. active_frontier=ActiveFrontierResolver(),
  947. workspaces=None,
  948. raw_artifacts=_RawStore(content),
  949. )
  950. images = await service.view_frozen_images(
  951. image_handles=[semantic_handle("image", raw_ref)], context=context
  952. )
  953. assert images[0]["media_type"] == "image/png"
  954. assert "url" not in images[0]
  955. with pytest.raises(PhaseTwoCandidateError, match="outside the accepted"):
  956. await service.view_frozen_images(
  957. image_handles=[semantic_handle("image", _RAW_OTHER)], context=context
  958. )
  959. @pytest.mark.asyncio
  960. async def test_active_frontier_write_conflict_is_not_resolved_by_completion_order() -> None:
  961. ref1 = ArtifactRef("script-build://artifact-versions/1", "paragraph", "1", DIGEST)
  962. ref2 = ArtifactRef("script-build://artifact-versions/2", "paragraph", "2", DIGEST)
  963. refs = (
  964. AcceptedDecisionRef("d1", ref1, SCOPE, ScriptTaskKind.PARAGRAPH),
  965. AcceptedDecisionRef("d2", ref2, SCOPE, ScriptTaskKind.PARAGRAPH),
  966. )
  967. contract = _contract(
  968. ScriptTaskKind.COMPOSE, refs=refs, adopted=("d1", "d2"), order=("d1", "d2")
  969. )
  970. bundle = AcceptedInputBundleV1(
  971. (
  972. AcceptedInput("d1", ref1, ScriptTaskKind.PARAGRAPH, SCOPE, "explicit"),
  973. AcceptedInput("d2", ref2, ScriptTaskKind.PARAGRAPH, SCOPE, "explicit"),
  974. ),
  975. DIGEST,
  976. )
  977. (ledger, accepted), context = _scope_fixture(contract, bundle=bundle)
  978. child_contract = _contract(ScriptTaskKind.PARAGRAPH)
  979. for decision_id in ("d1", "d2"):
  980. task_id = f"task-{decision_id}"
  981. ledger.tasks[task_id] = SimpleNamespace(task_id=task_id, attempt_ids=[f"a-{decision_id}"])
  982. ledger.attempts[f"a-{decision_id}"] = SimpleNamespace(
  983. attempt_id=f"a-{decision_id}", task_id=task_id, spec_version=1
  984. )
  985. ledger.decisions[decision_id] = SimpleNamespace(
  986. task_id=task_id, attempt_id=f"a-{decision_id}"
  987. )
  988. accepted.contracts[task_id] = child_contract
  989. service = PhaseTwoCandidateService(
  990. bindings=cast(Any, _Bindings()),
  991. task_store=_TaskStore(ledger),
  992. framework_artifact_store=_FrameworkArtifacts(),
  993. artifacts=cast(Any, _Artifacts({})),
  994. accepted_inputs=accepted,
  995. active_frontier=ActiveFrontierResolver(),
  996. workspaces=None,
  997. )
  998. with pytest.raises(PhaseTwoInputError, match="WRITE_SCOPE_CONFLICT"):
  999. await service.read_active_frontier(context=context)
  1000. @pytest.mark.asyncio
  1001. async def test_comparison_candidates_are_contract_derived_and_pass_fairness_precheck() -> None:
  1002. candidate_refs = (
  1003. ArtifactRef("script-build://artifact-versions/1", "paragraph", "1", DIGEST),
  1004. ArtifactRef("script-build://artifact-versions/2", "paragraph", "2", DIGEST),
  1005. )
  1006. decision_refs = tuple(
  1007. AcceptedDecisionRef(
  1008. f"candidate-{index}",
  1009. ref,
  1010. SCOPE,
  1011. ScriptTaskKind.PARAGRAPH,
  1012. )
  1013. for index, ref in enumerate(candidate_refs, start=1)
  1014. )
  1015. bundle = AcceptedInputBundleV1(
  1016. tuple(
  1017. AcceptedInput(
  1018. decision_ref.decision_id,
  1019. decision_ref.artifact_ref,
  1020. ScriptTaskKind.PARAGRAPH,
  1021. SCOPE,
  1022. "explicit",
  1023. )
  1024. for decision_ref in decision_refs
  1025. ),
  1026. DIGEST,
  1027. )
  1028. contract = _contract(ScriptTaskKind.COMPARE, comparison_refs=decision_refs)
  1029. (ledger, accepted), context = _scope_fixture(contract, bundle=bundle)
  1030. artifacts = _Artifacts({})
  1031. service = PhaseTwoCandidateService(
  1032. bindings=cast(Any, _Bindings()),
  1033. task_store=_TaskStore(ledger),
  1034. framework_artifact_store=_FrameworkArtifacts(),
  1035. artifacts=cast(Any, artifacts),
  1036. accepted_inputs=accepted,
  1037. active_frontier=ActiveFrontierResolver(),
  1038. workspaces=None,
  1039. )
  1040. criterion_results = [
  1041. {
  1042. "criterion_id": "closed",
  1043. "candidate_results": [
  1044. {"decision_id": "candidate-1", "reason": "uses one visible detail"},
  1045. {"decision_id": "candidate-2", "reason": "remains more abstract"},
  1046. ],
  1047. }
  1048. ]
  1049. frozen = await service.save_comparison_candidate(
  1050. payload={
  1051. "criterion_results": criterion_results,
  1052. "conflicts": ["both candidates write the opening scope"],
  1053. "recommended_decision_id": "candidate-1",
  1054. },
  1055. context=context,
  1056. )
  1057. assert artifacts.frozen is not None
  1058. comparison = artifacts.frozen.artifact
  1059. assert isinstance(comparison, ComparisonArtifactV1)
  1060. assert comparison.candidate_artifact_refs == tuple(ref.uri for ref in candidate_refs)
  1061. assert [
  1062. item["artifact_ref"] for item in comparison.criterion_results[0]["candidate_results"]
  1063. ] == [ref.uri for ref in candidate_refs]
  1064. frozen_ref = ArtifactRef.from_dict(frozen["artifact_ref"])
  1065. service._framework_artifact_store = _SnapshotArtifacts(frozen_ref)
  1066. rules = await service.deterministic_precheck(
  1067. context={**context, "snapshot_id": "validation-snapshot"}
  1068. )
  1069. assert {str(item["rule_id"]): item["verdict"] for item in rules} == {
  1070. "business-artifact-owner": "passed",
  1071. "realized-content": "passed",
  1072. "candidate-lineage": "passed",
  1073. "comparison-fairness": "passed",
  1074. }
  1075. with pytest.raises(PhaseTwoCandidateError, match="derived from the frozen contract"):
  1076. await service.save_comparison_candidate(
  1077. payload={
  1078. "candidate_artifact_refs": [candidate_refs[1].uri],
  1079. "criterion_results": criterion_results,
  1080. "recommended_decision_id": "candidate-2",
  1081. },
  1082. context=context,
  1083. )
  1084. @pytest.mark.asyncio
  1085. async def test_portfolio_adoption_and_canonical_digest_come_from_frozen_contract() -> None:
  1086. ref1 = ArtifactRef("script-build://artifact-versions/1", "structured_script", "1", DIGEST)
  1087. ref2 = ArtifactRef("script-build://artifact-versions/2", "structured_script", "2", DIGEST)
  1088. refs = (
  1089. AcceptedDecisionRef("d1", ref1, SCOPE, ScriptTaskKind.COMPOSE),
  1090. AcceptedDecisionRef("d2", ref2, SCOPE, ScriptTaskKind.COMPOSE),
  1091. )
  1092. contract = _contract(
  1093. ScriptTaskKind.CANDIDATE_PORTFOLIO,
  1094. refs=refs,
  1095. adopted=("d1",),
  1096. held=("d2",),
  1097. order=("d1",),
  1098. )
  1099. bundle = AcceptedInputBundleV1(
  1100. (
  1101. AcceptedInput("d1", ref1, ScriptTaskKind.COMPOSE, SCOPE, "explicit"),
  1102. AcceptedInput("d2", ref2, ScriptTaskKind.COMPOSE, SCOPE, "explicit"),
  1103. ),
  1104. DIGEST,
  1105. )
  1106. (ledger, accepted), context = _scope_fixture(contract, bundle=bundle)
  1107. paragraph = _complete_paragraph()
  1108. element = _complete_element()
  1109. link = _complete_link()
  1110. def source_versions(identifier: int) -> dict[str, ArtifactVersion]:
  1111. base = 20 + identifier * 10
  1112. versions: dict[str, ArtifactVersion] = {}
  1113. for offset, (kind, artifact) in enumerate(
  1114. zip(
  1115. (
  1116. ArtifactKind.STRUCTURE,
  1117. ArtifactKind.PARAGRAPH,
  1118. ArtifactKind.ELEMENT_SET,
  1119. ),
  1120. _source_artifacts(),
  1121. strict=True,
  1122. ),
  1123. start=1,
  1124. ):
  1125. version_id = base + offset
  1126. uri = f"script-build://artifact-versions/{version_id}"
  1127. versions[uri] = ArtifactVersion(
  1128. version_id,
  1129. 7,
  1130. f"source-{version_id}",
  1131. f"source-attempt-{version_id}",
  1132. 1,
  1133. kind,
  1134. DIGEST,
  1135. ArtifactState.FROZEN,
  1136. artifact,
  1137. datetime.now(UTC),
  1138. datetime.now(UTC),
  1139. )
  1140. return versions
  1141. def structured(identifier: int) -> ArtifactVersion:
  1142. source_refs = tuple(source_versions(identifier))
  1143. artifact = StructuredScriptArtifactV1(
  1144. direction_ref="script-build://artifact-versions/10",
  1145. input_closure_digest=DIGEST,
  1146. paragraphs=(paragraph,),
  1147. elements=(element,),
  1148. paragraph_element_links=(link,),
  1149. source_artifact_refs=source_refs,
  1150. goal_coverage=(GoalCoverage("goal-1", (source_refs[1], source_refs[2])),),
  1151. evidence_refs=(),
  1152. acceptance_notes=("accepted",),
  1153. canonical_sha256=DIGEST,
  1154. )
  1155. return ArtifactVersion(
  1156. identifier,
  1157. 7,
  1158. f"compose-{identifier}",
  1159. f"compose-attempt-{identifier}",
  1160. 1,
  1161. ArtifactKind.STRUCTURED_SCRIPT,
  1162. DIGEST,
  1163. ArtifactState.FROZEN,
  1164. artifact,
  1165. datetime.now(UTC),
  1166. datetime.now(UTC),
  1167. )
  1168. versions = {
  1169. **source_versions(1),
  1170. **source_versions(2),
  1171. ref1.uri: structured(1),
  1172. ref2.uri: structured(2),
  1173. }
  1174. artifacts = _Artifacts(versions)
  1175. service = PhaseTwoCandidateService(
  1176. bindings=cast(Any, _Bindings()),
  1177. task_store=_TaskStore(ledger),
  1178. framework_artifact_store=_FrameworkArtifacts(),
  1179. artifacts=cast(Any, artifacts),
  1180. accepted_inputs=accepted,
  1181. active_frontier=ActiveFrontierResolver(),
  1182. workspaces=None,
  1183. )
  1184. result = await service.save_candidate_portfolio(
  1185. payload={
  1186. "unresolved_defects": [
  1187. {
  1188. "severity": "warning",
  1189. "defect_code": "MINOR_STYLE",
  1190. "criterion_id": "closed",
  1191. "scope_ref": SCOPE,
  1192. "observed_excerpt": "opening cadence is slightly repetitive",
  1193. "evidence_refs": [],
  1194. "invalidated_inputs": [],
  1195. "recommended_action_class": "revise",
  1196. }
  1197. ],
  1198. },
  1199. context=context,
  1200. )
  1201. assert artifacts.frozen is not None
  1202. portfolio = artifacts.frozen.artifact
  1203. assert isinstance(portfolio, CandidatePortfolioArtifactV1)
  1204. assert portfolio.accepted_decision_ids == ("d1",)
  1205. assert portfolio.rejected_or_held_decision_ids == ("d2",)
  1206. assert result["artifact_ref"]["digest"] == canonical_sha256(portfolio.content_payload()).wire
  1207. with pytest.raises(PhaseTwoCandidateError, match="outside the accepted closure"):
  1208. await service.save_candidate_portfolio(
  1209. payload={
  1210. "unresolved_defects": [
  1211. {
  1212. "severity": "warning",
  1213. "defect_code": "UNTRUSTED_EVIDENCE",
  1214. "criterion_id": "closed",
  1215. "scope_ref": SCOPE,
  1216. "observed_excerpt": "unsupported warning",
  1217. "evidence_refs": ["script-build://artifact-versions/999"],
  1218. "invalidated_inputs": [],
  1219. "recommended_action_class": "revise",
  1220. }
  1221. ],
  1222. },
  1223. context=context,
  1224. )
  1225. with pytest.raises(ProtocolViolation, match=r"unsupported enum|must not be blank"):
  1226. await service.save_candidate_portfolio(
  1227. payload={
  1228. "unresolved_defects": [
  1229. {"severity": "warning", "defect_code": "INCOMPLETE_WARNING"}
  1230. ],
  1231. },
  1232. context=context,
  1233. )
  1234. with pytest.raises(PhaseTwoCandidateError, match="derived from the frozen contract"):
  1235. await service.save_candidate_portfolio(
  1236. payload={"adopted_structured_script_ref": ref2.uri}, context=context
  1237. )
  1238. @pytest.mark.asyncio
  1239. async def test_candidate_portfolio_command_replay_reuses_one_frozen_version(database: Any) -> None:
  1240. _, sessions = database
  1241. repository = SqlAlchemyScriptBusinessArtifactRepository(sessions)
  1242. paragraph = _complete_paragraph()
  1243. element = _complete_element()
  1244. link = _complete_link()
  1245. direction_version, direction_ref = await repository.freeze(
  1246. script_build_id=7,
  1247. task_id="direction",
  1248. attempt_id="direction-attempt",
  1249. spec_version=1,
  1250. artifact=DirectionArtifact(
  1251. goals=(
  1252. DirectionGoal(
  1253. "goal-1",
  1254. "complete the script",
  1255. "the delivery needs one complete script",
  1256. success_criteria=("the script is complete",),
  1257. ),
  1258. ),
  1259. evidence_refs=("script-build://artifact-versions/90",),
  1260. ),
  1261. )
  1262. async def freeze_structured(identifier: int) -> tuple[ArtifactVersion, ArtifactRef]:
  1263. structure, paragraph_source, element_source = _source_artifacts()
  1264. source_refs: list[str] = []
  1265. for suffix, source in (
  1266. ("structure", structure),
  1267. ("paragraph", paragraph_source),
  1268. ("elements", element_source),
  1269. ):
  1270. _, source_ref = await repository.freeze(
  1271. script_build_id=7,
  1272. task_id=f"{suffix}-{identifier}",
  1273. attempt_id=f"{suffix}-attempt-{identifier}",
  1274. spec_version=1,
  1275. artifact=source,
  1276. )
  1277. source_refs.append(source_ref.uri)
  1278. return await repository.freeze(
  1279. script_build_id=7,
  1280. task_id=f"compose-{identifier}",
  1281. attempt_id=f"compose-attempt-{identifier}",
  1282. spec_version=1,
  1283. artifact=StructuredScriptArtifactV1(
  1284. direction_ref=direction_ref.uri,
  1285. input_closure_digest=DIGEST,
  1286. paragraphs=(paragraph,),
  1287. elements=(element,),
  1288. paragraph_element_links=(link,),
  1289. source_artifact_refs=tuple(source_refs),
  1290. goal_coverage=(GoalCoverage("goal-1", (source_refs[1], source_refs[2])),),
  1291. evidence_refs=(),
  1292. acceptance_notes=("accepted",),
  1293. ),
  1294. )
  1295. (_, stored_ref1), (_, stored_ref2) = await freeze_structured(1), await freeze_structured(2)
  1296. ref1 = ArtifactRef(
  1297. stored_ref1.uri,
  1298. stored_ref1.kind,
  1299. stored_ref1.version,
  1300. stored_ref1.digest,
  1301. )
  1302. ref2 = ArtifactRef(
  1303. stored_ref2.uri,
  1304. stored_ref2.kind,
  1305. stored_ref2.version,
  1306. stored_ref2.digest,
  1307. )
  1308. refs = (
  1309. AcceptedDecisionRef("d1", ref1, SCOPE, ScriptTaskKind.COMPOSE),
  1310. AcceptedDecisionRef("d2", ref2, SCOPE, ScriptTaskKind.COMPOSE),
  1311. )
  1312. contract = _contract(
  1313. ScriptTaskKind.CANDIDATE_PORTFOLIO,
  1314. refs=refs,
  1315. adopted=("d1",),
  1316. held=("d2",),
  1317. order=("d1",),
  1318. )
  1319. bundle = AcceptedInputBundleV1(
  1320. (
  1321. AcceptedInput("d1", ref1, ScriptTaskKind.COMPOSE, SCOPE, "explicit"),
  1322. AcceptedInput("d2", ref2, ScriptTaskKind.COMPOSE, SCOPE, "explicit"),
  1323. ),
  1324. DIGEST,
  1325. )
  1326. (ledger, accepted), context = _scope_fixture(
  1327. contract,
  1328. bundle=bundle,
  1329. task_id="portfolio",
  1330. attempt_id="portfolio-attempt",
  1331. )
  1332. service = PhaseTwoCandidateService(
  1333. bindings=cast(Any, _Bindings(direction_version.artifact_version_id)),
  1334. task_store=_TaskStore(ledger),
  1335. framework_artifact_store=_FrameworkArtifacts(),
  1336. artifacts=repository,
  1337. accepted_inputs=accepted,
  1338. active_frontier=ActiveFrontierResolver(),
  1339. workspaces=None,
  1340. )
  1341. first = await service.save_candidate_portfolio(
  1342. payload={"unresolved_defects": []}, context=context
  1343. )
  1344. replay = await service.save_candidate_portfolio(
  1345. payload={"unresolved_defects": []}, context=context
  1346. )
  1347. frozen = await repository.get_by_attempt(
  1348. script_build_id=7,
  1349. task_id="portfolio",
  1350. attempt_id="portfolio-attempt",
  1351. )
  1352. assert first == replay
  1353. assert first["artifact_ref"]["version"] == str(frozen.artifact_version_id)
  1354. assert frozen.artifact_type is ArtifactKind.CANDIDATE_PORTFOLIO
  1355. _RAW_OTHER = "script-build://raw-artifacts/sha256/" + "b" * 64