openforma 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. forma_cli/__init__.py +5 -0
  2. forma_cli/app.py +1139 -0
  3. forma_cli/config.py +112 -0
  4. forma_cli/credentials.py +141 -0
  5. forma_cli/local.py +562 -0
  6. forma_cli/metadata_api.py +138 -0
  7. forma_cli/project_artifacts.py +182 -0
  8. forma_cli/sdk.py +571 -0
  9. forma_core/__init__.py +9 -0
  10. forma_core/__main__.py +4 -0
  11. forma_core/_version.py +3 -0
  12. forma_core/agents/__init__.py +50 -0
  13. forma_core/agents/clarification.py +194 -0
  14. forma_core/agents/component_reconciliation.py +99 -0
  15. forma_core/agents/context_gathering.py +115 -0
  16. forma_core/agents/continuous.py +537 -0
  17. forma_core/agents/contracts.py +247 -0
  18. forma_core/agents/firecrawl_mcp.py +484 -0
  19. forma_core/agents/lattice.py +239 -0
  20. forma_core/agents/orchestrator.py +3724 -0
  21. forma_core/agents/pipeline.py +843 -0
  22. forma_core/agents/project_correction.py +83 -0
  23. forma_core/agents/prompt_compaction.py +428 -0
  24. forma_core/agents/system_architecture.py +345 -0
  25. forma_core/agents/video_correction.py +119 -0
  26. forma_core/agents/web_research_workflow.py +1256 -0
  27. forma_core/agents/workflows.py +176 -0
  28. forma_core/assets/__init__.py +1 -0
  29. forma_core/assets/models.py +156 -0
  30. forma_core/assets/project.py +17 -0
  31. forma_core/assets/repository.py +48 -0
  32. forma_core/assets/service.py +142 -0
  33. forma_core/assets/validation.py +35 -0
  34. forma_core/benchmarks/__init__.py +5 -0
  35. forma_core/benchmarks/ir_triad_v1.py +477 -0
  36. forma_core/biology/__init__.py +28 -0
  37. forma_core/biology/benchmark.py +80 -0
  38. forma_core/biology/ewart_liverchip.py +279 -0
  39. forma_core/biology/ir.py +25 -0
  40. forma_core/biology/liverbench.py +416 -0
  41. forma_core/biology/liverbench_assay.py +251 -0
  42. forma_core/biology/liverbench_baselines.py +133 -0
  43. forma_core/biology/liverbench_independent.py +229 -0
  44. forma_core/biology/liverchip_demo.py +154 -0
  45. forma_core/biology/liverchip_evidence.py +149 -0
  46. forma_core/biology/models.py +247 -0
  47. forma_core/biology/validation.py +72 -0
  48. forma_core/cad_migrations/__init__.py +6 -0
  49. forma_core/cad_migrations/cli.py +101 -0
  50. forma_core/cad_migrations/emitters.py +227 -0
  51. forma_core/cad_migrations/models.py +121 -0
  52. forma_core/cad_migrations/planner.py +68 -0
  53. forma_core/chemistry/__init__.py +5 -0
  54. forma_core/chemistry/models.py +215 -0
  55. forma_core/chemistry/stoichiometry.py +272 -0
  56. forma_core/chemistry/validation.py +179 -0
  57. forma_core/cli/__init__.py +1 -0
  58. forma_core/cli/__main__.py +4 -0
  59. forma_core/cli/main.py +370 -0
  60. forma_core/config/__init__.py +28 -0
  61. forma_core/config/compatibility.py +282 -0
  62. forma_core/config/contract.py +184 -0
  63. forma_core/config/environment.py +129 -0
  64. forma_core/config/parti.py +34 -0
  65. forma_core/config/runtime.py +303 -0
  66. forma_core/control/__init__.py +10 -0
  67. forma_core/control/actions.py +136 -0
  68. forma_core/control/adapters.py +36 -0
  69. forma_core/control/cli.py +49 -0
  70. forma_core/control/client.py +124 -0
  71. forma_core/control/models.py +168 -0
  72. forma_core/control/opencode_worker.py +80 -0
  73. forma_core/control/package.py +318 -0
  74. forma_core/control/rover_scene/__init__.py +1 -0
  75. forma_core/control/rover_scene/__main__.py +34 -0
  76. forma_core/control/rover_scene/assets.py +65 -0
  77. forma_core/control/rover_scene/fleet.py +214 -0
  78. forma_core/control/rover_scene/host.py +258 -0
  79. forma_core/control/rover_scene/kinematics.py +35 -0
  80. forma_core/control/rover_scene/machine.py +347 -0
  81. forma_core/control/rover_scene/robot.py +166 -0
  82. forma_core/control/rover_scene/scene.py +206 -0
  83. forma_core/control/rover_scene/view.py +80 -0
  84. forma_core/control/rover_scene/web/index.html +25 -0
  85. forma_core/control/rover_scene/web/viewer.js +148 -0
  86. forma_core/control/runtime.py +356 -0
  87. forma_core/control/so101.py +235 -0
  88. forma_core/control/tasks.py +287 -0
  89. forma_core/database.py +2362 -0
  90. forma_core/debug.py +314 -0
  91. forma_core/domains/__init__.py +7 -0
  92. forma_core/domains/agents.py +85 -0
  93. forma_core/domains/base.py +69 -0
  94. forma_core/domains/benchmark.py +87 -0
  95. forma_core/domains/cli.py +48 -0
  96. forma_core/domains/compatibility.py +234 -0
  97. forma_core/domains/composition.py +372 -0
  98. forma_core/domains/diagnostics.py +15 -0
  99. forma_core/domains/generation.py +479 -0
  100. forma_core/domains/interaction.py +301 -0
  101. forma_core/domains/planning.py +140 -0
  102. forma_core/domains/providers.py +214 -0
  103. forma_core/domains/registry.py +267 -0
  104. forma_core/domains/selection.py +75 -0
  105. forma_core/domains/storage.py +60 -0
  106. forma_core/domains/tools.py +180 -0
  107. forma_core/electronics/__init__.py +1 -0
  108. forma_core/electronics/models.py +84 -0
  109. forma_core/electronics/primitives.py +43 -0
  110. forma_core/electronics/rules.py +340 -0
  111. forma_core/external_sources.py +497 -0
  112. forma_core/fabricator/__init__.py +33 -0
  113. forma_core/fabricator/__main__.py +7 -0
  114. forma_core/fabricator/main.py +578 -0
  115. forma_core/firmware/__init__.py +60 -0
  116. forma_core/firmware/drivers.py +140 -0
  117. forma_core/firmware/examples.py +503 -0
  118. forma_core/firmware/generate.py +520 -0
  119. forma_core/firmware/models.py +34 -0
  120. forma_core/firmware/sil/__init__.py +5 -0
  121. forma_core/firmware/sil/adapter.py +71 -0
  122. forma_core/firmware/sil/build.py +49 -0
  123. forma_core/firmware/sil/native/CMakeLists.txt +9 -0
  124. forma_core/firmware/sil/native/bridge.cpp +112 -0
  125. forma_core/firmware/sil/native/controller.cpp +123 -0
  126. forma_core/firmware/sil/native/controller.h +49 -0
  127. forma_core/firmware/sil/simulator.py +139 -0
  128. forma_core/firmware/targets.py +111 -0
  129. forma_core/firmware/validation.py +130 -0
  130. forma_core/fluidics/__init__.py +6 -0
  131. forma_core/fluidics/benchmark.py +217 -0
  132. forma_core/fluidics/calculations.py +79 -0
  133. forma_core/fluidics/examples.py +54 -0
  134. forma_core/fluidics/ir.py +25 -0
  135. forma_core/fluidics/models.py +132 -0
  136. forma_core/fluidics/topology.py +47 -0
  137. forma_core/fluidics/validation.py +134 -0
  138. forma_core/generation.py +32 -0
  139. forma_core/geometry_bindings/__init__.py +20 -0
  140. forma_core/geometry_bindings/cad_adapter.py +80 -0
  141. forma_core/geometry_bindings/models.py +163 -0
  142. forma_core/geometry_bindings/resolution.py +340 -0
  143. forma_core/geometry_bindings/tools.py +125 -0
  144. forma_core/image_providers.py +3049 -0
  145. forma_core/images.py +3 -0
  146. forma_core/integrations/__init__.py +1 -0
  147. forma_core/integrations/huggingface/__init__.py +29 -0
  148. forma_core/integrations/huggingface/huggingface_artifacts.py +272 -0
  149. forma_core/jobs/__init__.py +1 -0
  150. forma_core/jobs/context.py +277 -0
  151. forma_core/jobs/continuous.py +719 -0
  152. forma_core/jobs/metrics.py +124 -0
  153. forma_core/jobs/migrations.py +161 -0
  154. forma_core/jobs/persistence.py +28 -0
  155. forma_core/jobs/repositories.py +422 -0
  156. forma_core/jobs/schema.py +28 -0
  157. forma_core/jobs/source_usage.py +230 -0
  158. forma_core/jobs/store.py +476 -0
  159. forma_core/llm.py +3 -0
  160. forma_core/llm_providers.py +2682 -0
  161. forma_core/logs.py +107 -0
  162. forma_core/mechanics/__init__.py +1 -0
  163. forma_core/mechanics/gear_benchmark.py +85 -0
  164. forma_core/mechanics/mechanism_benchmarks.py +345 -0
  165. forma_core/mechanics/models.py +72 -0
  166. forma_core/mechanics/primitives.py +109 -0
  167. forma_core/mechanics/solid_cad.py +83 -0
  168. forma_core/observability.py +237 -0
  169. forma_core/openai_streams.py +780 -0
  170. forma_core/opencode/__init__.py +25 -0
  171. forma_core/opencode/architecture.py +82 -0
  172. forma_core/opencode/capabilities.py +130 -0
  173. forma_core/opencode/models.py +419 -0
  174. forma_core/opencode/persistence.py +62 -0
  175. forma_core/opencode/public_events.py +91 -0
  176. forma_core/opencode/schema.py +28 -0
  177. forma_core/opencode/store.py +874 -0
  178. forma_core/persistence/__init__.py +16 -0
  179. forma_core/persistence/base.py +38 -0
  180. forma_core/persistence/images.py +598 -0
  181. forma_core/persistence/migrations.py +200 -0
  182. forma_core/persistence/models.py +439 -0
  183. forma_core/persistence/project_artifacts.py +341 -0
  184. forma_core/persistence/project_reconciliation.py +1094 -0
  185. forma_core/persistence/providers/__init__.py +4 -0
  186. forma_core/persistence/providers/sqlite.py +114 -0
  187. forma_core/persistence/providers/supabase.py +31 -0
  188. forma_core/persistence/repositories/__init__.py +9 -0
  189. forma_core/persistence/repositories/base.py +335 -0
  190. forma_core/persistence/repositories/sqlite.py +1571 -0
  191. forma_core/persistence/repositories/supabase.py +1576 -0
  192. forma_core/persistence/schema.py +176 -0
  193. forma_core/processes/__init__.py +5 -0
  194. forma_core/processes/models.py +338 -0
  195. forma_core/processes/validation.py +141 -0
  196. forma_core/project_list_cache.py +316 -0
  197. forma_core/prompt_continuity.py +387 -0
  198. forma_core/providers/__init__.py +39 -0
  199. forma_core/providers/base.py +28 -0
  200. forma_core/providers/models.py +138 -0
  201. forma_core/providers/openai.py +92 -0
  202. forma_core/providers/openai_compatible.py +190 -0
  203. forma_core/providers/registry.py +68 -0
  204. forma_core/providers/registry_utils.py +46 -0
  205. forma_core/py.typed +1 -0
  206. forma_core/runtime.py +3 -0
  207. forma_core/selectors.py +36 -0
  208. forma_core/signups/__init__.py +5 -0
  209. forma_core/signups/models.py +49 -0
  210. forma_core/terminal/__init__.py +1 -0
  211. forma_core/terminal/dashboard.py +475 -0
  212. forma_core/terminal/images.py +156 -0
  213. forma_core/thermal/__init__.py +5 -0
  214. forma_core/thermal/models.py +361 -0
  215. forma_core/thermal/validation.py +175 -0
  216. forma_core/user_integrations.py +2069 -0
  217. forma_core/utils.py +291 -0
  218. forma_core/validation.py +83 -0
  219. forma_core/vertex_auth.py +92 -0
  220. forma_core/video_prompts.py +193 -0
  221. forma_core/video_review.py +1006 -0
  222. forma_core/wiring.py +356 -0
  223. forma_core/workers/__init__.py +120 -0
  224. forma_core/workers/contracts.py +183 -0
  225. forma_core/workers/generation.py +753 -0
  226. forma_core/workers/orchestration.py +805 -0
  227. forma_core/workers/registry.py +222 -0
  228. forma_core/workers/reverse_engineering.py +272 -0
  229. forma_core/workers/validation.py +291 -0
  230. forma_core/workspaces/__init__.py +5 -0
  231. forma_core/workspaces/chats/__init__.py +11 -0
  232. forma_core/workspaces/chats/models.py +48 -0
  233. forma_core/workspaces/context/__init__.py +15 -0
  234. forma_core/workspaces/context/agent.py +260 -0
  235. forma_core/workspaces/context/models.py +117 -0
  236. forma_core/workspaces/context/pdf.py +418 -0
  237. forma_core/workspaces/design_briefs/__init__.py +25 -0
  238. forma_core/workspaces/design_briefs/models.py +85 -0
  239. forma_core/workspaces/design_briefs/references.py +56 -0
  240. forma_core/workspaces/models.py +41 -0
  241. forma_core/workspaces/projects/__init__.py +88 -0
  242. forma_core/workspaces/projects/cad_generation.py +1016 -0
  243. forma_core/workspaces/projects/context_governance.py +365 -0
  244. forma_core/workspaces/projects/design_lifecycle.py +668 -0
  245. forma_core/workspaces/projects/fabrication/__init__.py +54 -0
  246. forma_core/workspaces/projects/fabrication/demo_printers.py +236 -0
  247. forma_core/workspaces/projects/fabrication/models.py +120 -0
  248. forma_core/workspaces/projects/fabrication/printer_config.py +205 -0
  249. forma_core/workspaces/projects/fabrication/slicers/__init__.py +7 -0
  250. forma_core/workspaces/projects/fabrication/slicers/base.py +25 -0
  251. forma_core/workspaces/projects/fabrication/slicers/cura.py +125 -0
  252. forma_core/workspaces/projects/fabrication/slicers/orca.py +208 -0
  253. forma_core/workspaces/projects/fabrication/slicing.py +202 -0
  254. forma_core/workspaces/projects/fabrication/validation.py +103 -0
  255. forma_core/workspaces/projects/gear_benchmark.py +6 -0
  256. forma_core/workspaces/projects/generation_mode.py +70 -0
  257. forma_core/workspaces/projects/identity.py +28 -0
  258. forma_core/workspaces/projects/iteration.py +680 -0
  259. forma_core/workspaces/projects/manifest.py +362 -0
  260. forma_core/workspaces/projects/mechanism_benchmarks.py +12 -0
  261. forma_core/workspaces/projects/models.py +913 -0
  262. forma_core/workspaces/projects/objects.py +731 -0
  263. forma_core/workspaces/projects/outcomes.py +47 -0
  264. forma_core/workspaces/projects/output.py +735 -0
  265. forma_core/workspaces/projects/resolver.py +397 -0
  266. forma_core/workspaces/projects/solid_cad.py +8 -0
  267. forma_core/workspaces/projects/state.py +622 -0
  268. forma_core/workspaces/readiness/__init__.py +28 -0
  269. forma_core/workspaces/readiness/evaluator.py +103 -0
  270. forma_core/workspaces/readiness/models.py +97 -0
  271. forma_core/workspaces/readiness/service.py +225 -0
  272. forma_core/workspaces/reverse_engineering/__init__.py +37 -0
  273. forma_core/workspaces/reverse_engineering/analyzer.py +246 -0
  274. forma_core/workspaces/reverse_engineering/models.py +128 -0
  275. forma_core/workspaces/validation/__init__.py +37 -0
  276. forma_core/workspaces/validation/evaluator.py +327 -0
  277. forma_core/workspaces/validation/models.py +146 -0
  278. forma_core/workspaces/validation/service.py +212 -0
  279. forma_core/workspaces/workflow/__init__.py +29 -0
  280. forma_core/workspaces/workflow/guard.py +33 -0
  281. forma_core/workspaces/workflow/models.py +77 -0
  282. forma_core/workspaces/workflow/service.py +287 -0
  283. openforma-0.4.0.dist-info/METADATA +247 -0
  284. openforma-0.4.0.dist-info/RECORD +288 -0
  285. openforma-0.4.0.dist-info/WHEEL +5 -0
  286. openforma-0.4.0.dist-info/entry_points.txt +4 -0
  287. openforma-0.4.0.dist-info/licenses/LICENSE +373 -0
  288. openforma-0.4.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,622 @@
1
+ """Canonical, immutable project revision boundary shared by workers and workspace adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Annotated, Any, Literal, Protocol
7
+ from uuid import UUID, uuid4
8
+
9
+ from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator, field_validator
10
+
11
+ from forma_core.workspaces.design_briefs import DesignBrief
12
+ from forma_core.workspaces.projects.models import ComponentInstance, HardwareIntermediateRepresentation
13
+
14
+
15
+ from forma_core.domains.generation import EngineeringResult
16
+
17
+ PROJECT_REVISION_SCHEMA_VERSION = "1.0"
18
+ NonEmptyString = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
19
+
20
+
21
+ def _utc_now() -> datetime:
22
+ return datetime.now(timezone.utc)
23
+
24
+
25
+ class ProjectSystem(BaseModel):
26
+ """A generated functional system composed from project components."""
27
+
28
+ model_config = ConfigDict(extra="forbid")
29
+
30
+ system_id: NonEmptyString
31
+ kind: NonEmptyString
32
+ name: NonEmptyString
33
+ component_refs: list[NonEmptyString] = Field(default_factory=list)
34
+ metadata: dict[str, Any] = Field(default_factory=dict)
35
+
36
+
37
+ class ProjectArtifact(BaseModel):
38
+ """A durable artifact reference owned by one canonical project revision."""
39
+
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+ artifact_id: NonEmptyString
43
+ kind: NonEmptyString
44
+ uri: NonEmptyString
45
+ media_type: NonEmptyString | None = None
46
+ checksum: NonEmptyString | None = None
47
+ metadata: dict[str, Any] = Field(default_factory=dict)
48
+
49
+
50
+ class ProjectRevisionDraft(BaseModel):
51
+ """Identity-free structured output produced by a worker before persistence."""
52
+
53
+ model_config = ConfigDict(extra="forbid")
54
+
55
+ state: EngineeringResult | HardwareIntermediateRepresentation
56
+ components: list[ComponentInstance] = Field(default_factory=list)
57
+ systems: list[ProjectSystem] = Field(default_factory=list)
58
+ artifacts: list[ProjectArtifact] = Field(default_factory=list)
59
+ assumptions: list[NonEmptyString] = Field(default_factory=list)
60
+
61
+ @field_validator("state", mode="before")
62
+ @classmethod
63
+ def parse_state(cls, value: Any) -> Any:
64
+ """Tagged domain reports must never fall back to permissive legacy parsing."""
65
+ if isinstance(value, dict) and value.get("format") == "forma.engineering-result":
66
+ return EngineeringResult.model_validate(value)
67
+ return value
68
+
69
+ @model_validator(mode="after")
70
+ def require_consistent_unique_output(self) -> "ProjectRevisionDraft":
71
+ if isinstance(self.state, EngineeringResult):
72
+ if self.components or self.systems:
73
+ raise ValueError("Domain revisions retain component semantics in their owning artifacts.")
74
+ if len({a.artifact_id for a in self.artifacts}) != len(self.artifacts):
75
+ raise ValueError("Project artifact identities must be unique.")
76
+ return self
77
+ component_payloads = [item.model_dump(mode="json") for item in self.components]
78
+ state_component_payloads = [item.model_dump(mode="json") for item in self.state.components]
79
+ if component_payloads != state_component_payloads:
80
+ raise ValueError("Project revision components must match the canonical HardwareIntermediateRepresentation state.")
81
+ # Keep runtime-only shared part details available to worker consumers while
82
+ # persisting only the normalized physical-instance records.
83
+ self.components = list(self.state.components)
84
+ for values, label in (
85
+ ([item.system_id for item in self.systems], "system_id"),
86
+ ([item.artifact_id for item in self.artifacts], "artifact_id"),
87
+ (list(self.assumptions), "assumption"),
88
+ ):
89
+ if len(values) != len(set(values)):
90
+ raise ValueError(f"Project revision {label} values must be unique.")
91
+ component_refs = {item.ref_des for item in self.components}
92
+ dangling = sorted({
93
+ ref_des
94
+ for system in self.systems
95
+ for ref_des in system.component_refs
96
+ if ref_des not in component_refs
97
+ })
98
+ if dangling:
99
+ raise ValueError(f"Project systems reference unknown components: {', '.join(dangling)}.")
100
+ return self
101
+
102
+
103
+ class ProjectRevision(ProjectRevisionDraft):
104
+ """An immutable revision committed through the shared project-state boundary."""
105
+
106
+ schema_version: Literal["1.0"] = PROJECT_REVISION_SCHEMA_VERSION
107
+ revision_id: UUID
108
+ project_id: UUID
109
+ owner_user_id: NonEmptyString
110
+ revision: int = Field(ge=1)
111
+ parent_revision: int | None = Field(default=None, ge=1)
112
+ design_brief_id: UUID
113
+ design_brief_version: int = Field(ge=1)
114
+ source_job_id: NonEmptyString
115
+ created_at: datetime = Field(default_factory=_utc_now)
116
+
117
+
118
+ class ProjectRevisionOutcome(BaseModel):
119
+ model_config = ConfigDict(extra="forbid")
120
+
121
+ revision: ProjectRevision
122
+ idempotent_replay: bool = False
123
+
124
+
125
+ class ProjectStateError(RuntimeError):
126
+ def __init__(
127
+ self,
128
+ code: str,
129
+ message: str,
130
+ *,
131
+ retryable: bool = False,
132
+ context: dict[str, Any] | None = None,
133
+ ) -> None:
134
+ super().__init__(message)
135
+ self.code = code
136
+ self.message = message
137
+ self.retryable = retryable
138
+ self.context = context or {}
139
+
140
+ def as_dict(self) -> dict[str, Any]:
141
+ return {
142
+ "code": self.code,
143
+ "message": self.message,
144
+ "retryable": self.retryable,
145
+ "context": dict(self.context),
146
+ }
147
+
148
+
149
+ class ProjectStateRepository(Protocol):
150
+ def get_design_brief_version(
151
+ self,
152
+ project_id: str,
153
+ owner_user_id: str,
154
+ brief_version: int,
155
+ ) -> Any | None: ...
156
+
157
+ def get_latest_project_revision(self, project_id: str, owner_user_id: str) -> Any | None: ...
158
+
159
+ def list_project_revisions(self, project_id: str, owner_user_id: str, *, limit: int, before: int | None = None) -> list[Any]: ...
160
+
161
+ def get_project_revision_by_id(self, project_id: str, owner_user_id: str, revision_id: str) -> Any | None: ...
162
+
163
+ def get_project_revision(
164
+ self,
165
+ project_id: str,
166
+ owner_user_id: str,
167
+ revision: int,
168
+ ) -> Any | None: ...
169
+
170
+ def get_project_revision_by_source_job(
171
+ self,
172
+ project_id: str,
173
+ owner_user_id: str,
174
+ source_job_id: str,
175
+ ) -> Any | None: ...
176
+
177
+ def insert_initial_project_revision(self, record: dict[str, Any]) -> Any | None: ...
178
+ def insert_project_revision(self, record: dict[str, Any], expected_parent_revision: int) -> Any | None: ...
179
+
180
+
181
+ def _canonical_uuid(value: str | UUID, field_name: str) -> UUID:
182
+ try:
183
+ return UUID(str(value).strip())
184
+ except (TypeError, ValueError, AttributeError) as exc:
185
+ raise ProjectStateError("invalid_project_revision_identity", f"{field_name} must be a UUID.") from exc
186
+
187
+
188
+ def _revision_from_record(record: Any) -> ProjectRevision:
189
+ payload = getattr(record, "payload_json", None)
190
+ if not isinstance(payload, dict):
191
+ raise ProjectStateError(
192
+ "invalid_persisted_project_revision",
193
+ "Persisted project revision payload_json must be an object.",
194
+ )
195
+ return ProjectRevision.model_validate(payload)
196
+
197
+
198
+ class ProjectStateService:
199
+ """Create and retrieve revisions without allowing cross-project or stale writes."""
200
+
201
+ def __init__(self, repository: ProjectStateRepository) -> None:
202
+ self._repository = repository
203
+
204
+ def get_latest(self, project_id: str | UUID, owner_user_id: str) -> ProjectRevision:
205
+ project = str(_canonical_uuid(project_id, "project_id"))
206
+ owner = str(owner_user_id or "").strip()
207
+ record = self._repository.get_latest_project_revision(project, owner)
208
+ if record is None:
209
+ raise ProjectStateError("project_revision_not_found", "Project revision not found.")
210
+ return _revision_from_record(record)
211
+
212
+ def get_revision(
213
+ self,
214
+ project_id: str | UUID,
215
+ owner_user_id: str,
216
+ revision: int,
217
+ ) -> ProjectRevision:
218
+ project = str(_canonical_uuid(project_id, "project_id"))
219
+ owner = str(owner_user_id or "").strip()
220
+ record = self._repository.get_project_revision(project, owner, revision)
221
+ if record is None:
222
+ raise ProjectStateError(
223
+ "project_revision_not_found",
224
+ "The exact project revision is not available to the project owner.",
225
+ context={"project_id": project, "revision": revision},
226
+ )
227
+ return _revision_from_record(record)
228
+
229
+ def get_by_source_job(
230
+ self,
231
+ project_id: str | UUID,
232
+ owner_user_id: str,
233
+ source_job_id: str,
234
+ ) -> ProjectRevision | None:
235
+ project = str(_canonical_uuid(project_id, "project_id"))
236
+ owner = str(owner_user_id or "").strip()
237
+ job_id = str(source_job_id or "").strip()
238
+ record = self._repository.get_project_revision_by_source_job(project, owner, job_id)
239
+ return _revision_from_record(record) if record is not None else None
240
+
241
+ def list_revisions(self, project_id: str | UUID, owner_user_id: str, *, limit: int = 21, before: int | None = None) -> list[ProjectRevision]:
242
+ """Page immutable snapshots in descending version order within one owner/project."""
243
+ project = str(_canonical_uuid(project_id, "project_id"))
244
+ records = self._repository.list_project_revisions(project, owner_user_id.strip(), limit=limit, before=before)
245
+ return [_revision_from_record(record) for record in records]
246
+
247
+ def get_revision_by_id(self, project_id: str | UUID, owner_user_id: str, revision_id: str | UUID) -> ProjectRevision:
248
+ """Read an exact snapshot, never substituting the latest project state."""
249
+ project = str(_canonical_uuid(project_id, "project_id"))
250
+ revision = str(_canonical_uuid(revision_id, "revision_id"))
251
+ record = self._repository.get_project_revision_by_id(project, owner_user_id.strip(), revision)
252
+ if record is None:
253
+ raise ProjectStateError("project_revision_not_found", "Project revision not found.")
254
+ return _revision_from_record(record)
255
+
256
+ def require_frozen_design_brief(
257
+ self,
258
+ design_brief: DesignBrief,
259
+ owner_user_id: str,
260
+ ) -> DesignBrief:
261
+ owner = str(owner_user_id or "").strip()
262
+ record = self._repository.get_design_brief_version(
263
+ str(design_brief.project_id),
264
+ owner,
265
+ design_brief.brief_version,
266
+ )
267
+ payload = getattr(record, "payload_json", None) if record is not None else None
268
+ if not isinstance(payload, dict):
269
+ raise ProjectStateError(
270
+ "frozen_design_brief_not_found",
271
+ "The exact frozen DesignBrief is not available to the project owner.",
272
+ )
273
+ persisted = DesignBrief.model_validate(payload)
274
+ if persisted != design_brief:
275
+ raise ProjectStateError(
276
+ "frozen_design_brief_mismatch",
277
+ "Generation input does not match the persisted frozen DesignBrief snapshot.",
278
+ context={
279
+ "project_id": str(design_brief.project_id),
280
+ "design_brief_id": str(design_brief.design_brief_id),
281
+ "design_brief_version": design_brief.brief_version,
282
+ },
283
+ )
284
+ return persisted
285
+
286
+ def get_frozen_design_brief(
287
+ self,
288
+ project_id: str | UUID,
289
+ owner_user_id: str,
290
+ design_brief_id: str | UUID,
291
+ design_brief_version: int,
292
+ ) -> DesignBrief:
293
+ project = str(_canonical_uuid(project_id, "project_id"))
294
+ brief_id = _canonical_uuid(design_brief_id, "design_brief_id")
295
+ owner = str(owner_user_id or "").strip()
296
+ record = self._repository.get_design_brief_version(project, owner, design_brief_version)
297
+ payload = getattr(record, "payload_json", None) if record is not None else None
298
+ if not isinstance(payload, dict):
299
+ raise ProjectStateError(
300
+ "frozen_design_brief_not_found",
301
+ "The exact frozen DesignBrief is not available to the project owner.",
302
+ )
303
+ brief = DesignBrief.model_validate(payload)
304
+ if brief.design_brief_id != brief_id or brief.project_id != UUID(project):
305
+ raise ProjectStateError(
306
+ "frozen_design_brief_not_found",
307
+ "The exact frozen DesignBrief is not available to the project owner.",
308
+ )
309
+ return brief
310
+
311
+ def create_initial_revision(
312
+ self,
313
+ draft: ProjectRevisionDraft,
314
+ *,
315
+ project_id: str | UUID,
316
+ owner_user_id: str,
317
+ design_brief_id: str | UUID,
318
+ design_brief_version: int,
319
+ source_job_id: str,
320
+ ) -> ProjectRevisionOutcome:
321
+ project_uuid = _canonical_uuid(project_id, "project_id")
322
+ brief_uuid = _canonical_uuid(design_brief_id, "design_brief_id")
323
+ project = str(project_uuid)
324
+ owner = str(owner_user_id or "").strip()
325
+ job_id = str(source_job_id or "").strip()
326
+ if not owner or not job_id:
327
+ raise ProjectStateError(
328
+ "invalid_project_revision_identity",
329
+ "owner_user_id and source_job_id are required.",
330
+ )
331
+
332
+ replay = self._repository.get_project_revision_by_source_job(project, owner, job_id)
333
+ if replay is not None:
334
+ revision = _revision_from_record(replay)
335
+ self._require_identity(revision, project_uuid, brief_uuid, design_brief_version, job_id)
336
+ return ProjectRevisionOutcome(revision=revision, idempotent_replay=True)
337
+
338
+ brief_record = self._repository.get_design_brief_version(project, owner, design_brief_version)
339
+ if brief_record is None or str(getattr(brief_record, "design_brief_id", "")) != str(brief_uuid):
340
+ raise ProjectStateError(
341
+ "frozen_design_brief_not_found",
342
+ "The exact frozen DesignBrief is not available to the project owner.",
343
+ context={
344
+ "project_id": project,
345
+ "design_brief_id": str(brief_uuid),
346
+ "design_brief_version": design_brief_version,
347
+ },
348
+ )
349
+ if self._repository.get_latest_project_revision(project, owner) is not None:
350
+ raise ProjectStateError(
351
+ "initial_project_revision_exists",
352
+ "The project already has an initial revision.",
353
+ context={"project_id": project},
354
+ )
355
+
356
+ revision_uuid = uuid4()
357
+ state = draft.state.model_copy(deep=True)
358
+ if isinstance(state, EngineeringResult):
359
+ if state.product.manifest.product_id != project:
360
+ raise ProjectStateError("project_revision_identity_mismatch", "Domain product targets a different project.")
361
+ else:
362
+ metadata = dict(state.assembly_metadata or {})
363
+ supplied_project = str(metadata.get("project_id") or "").strip()
364
+ if supplied_project and supplied_project != project:
365
+ raise ProjectStateError(
366
+ "project_revision_identity_mismatch",
367
+ "Generated state targets a different project.",
368
+ context={"expected_project_id": project, "actual_project_id": supplied_project},
369
+ )
370
+ supplied_revision = metadata.get("revision")
371
+ if supplied_revision not in (None, 1, "1"):
372
+ raise ProjectStateError(
373
+ "project_revision_identity_mismatch",
374
+ "Generated state targets a different project revision.",
375
+ context={"expected_revision": 1, "actual_revision": supplied_revision},
376
+ )
377
+ state.assembly_metadata = {
378
+ **metadata,
379
+ "project_id": project,
380
+ "revision": 1,
381
+ "project_revision": 1,
382
+ "canonical_revision_id": str(revision_uuid),
383
+ "design_brief_id": str(brief_uuid),
384
+ "design_brief_version": design_brief_version,
385
+ "source_job_id": job_id,
386
+ }
387
+ normalized_draft = draft.model_copy(update={"state": state, "components": list(getattr(state, "components", []))})
388
+ revision = ProjectRevision(
389
+ **normalized_draft.model_dump(),
390
+ revision_id=revision_uuid,
391
+ project_id=project_uuid,
392
+ owner_user_id=owner,
393
+ revision=1,
394
+ parent_revision=None,
395
+ design_brief_id=brief_uuid,
396
+ design_brief_version=design_brief_version,
397
+ source_job_id=job_id,
398
+ )
399
+ record = {
400
+ "id": str(revision.revision_id),
401
+ "project_id": project,
402
+ "owner_user_id": owner,
403
+ "revision": revision.revision,
404
+ "parent_revision": revision.parent_revision,
405
+ "design_brief_id": str(brief_uuid),
406
+ "design_brief_version": design_brief_version,
407
+ "source_job_id": job_id,
408
+ "payload_json": revision.model_dump(mode="json"),
409
+ "created_at": revision.created_at.isoformat(),
410
+ }
411
+ overview = getattr(state, "overview", None)
412
+ brief_payload = getattr(brief_record, "payload_json", None)
413
+ brief_payload = brief_payload if isinstance(brief_payload, dict) else {}
414
+ self._repository.upsert_project_identity({
415
+ "project_id": project,
416
+ "owner_user_id": owner,
417
+ "creation_channel": "hosted",
418
+ "title": str(getattr(overview, "title", "") or "Untitled project"),
419
+ "prompt": str(brief_payload.get("summary") or ""),
420
+ "chat_id": brief_payload.get("conversation_id"),
421
+ "workspace_id": None,
422
+ "visibility": "private" if isinstance(state, EngineeringResult) else "public",
423
+ "status": "active",
424
+ "created_at": revision.created_at.isoformat(),
425
+ "updated_at": revision.created_at.isoformat(),
426
+ })
427
+ saved = self._repository.insert_initial_project_revision(record)
428
+ if saved is not None:
429
+ return ProjectRevisionOutcome(revision=_revision_from_record(saved))
430
+
431
+ replay = self._repository.get_project_revision_by_source_job(project, owner, job_id)
432
+ if replay is not None:
433
+ persisted = _revision_from_record(replay)
434
+ self._require_identity(persisted, project_uuid, brief_uuid, design_brief_version, job_id)
435
+ return ProjectRevisionOutcome(revision=persisted, idempotent_replay=True)
436
+ raise ProjectStateError(
437
+ "project_revision_conflict",
438
+ "Project state changed before the initial revision could be committed.",
439
+ retryable=True,
440
+ context={"project_id": project},
441
+ )
442
+
443
+ def create_revision(
444
+ self,
445
+ draft: ProjectRevisionDraft,
446
+ *,
447
+ project_id: str | UUID,
448
+ owner_user_id: str,
449
+ source_job_id: str,
450
+ design_brief_id: str | UUID | None = None,
451
+ design_brief_version: int | None = None,
452
+ expected_parent_revision: int | None = None,
453
+ ) -> ProjectRevisionOutcome:
454
+ """Append one immutable revision to an existing canonical project."""
455
+
456
+ project_uuid = _canonical_uuid(project_id, "project_id")
457
+ project = str(project_uuid)
458
+ owner = str(owner_user_id or "").strip()
459
+ job_id = str(source_job_id or "").strip()
460
+
461
+ if not owner or not job_id:
462
+ raise ProjectStateError(
463
+ "invalid_project_revision_identity",
464
+ "owner_user_id and source_job_id are required.",
465
+ )
466
+
467
+ replay = self.get_by_source_job(project, owner, job_id)
468
+ if replay is not None:
469
+ return ProjectRevisionOutcome(
470
+ revision=replay,
471
+ idempotent_replay=True,
472
+ )
473
+
474
+ parent = self.get_latest(project, owner)
475
+ if expected_parent_revision is not None and parent.revision != expected_parent_revision:
476
+ raise ProjectStateError("project_revision_conflict", "Project changed; read the latest revision and retry.")
477
+
478
+ brief_id = (
479
+ _canonical_uuid(design_brief_id, "design_brief_id")
480
+ if design_brief_id is not None
481
+ else parent.design_brief_id
482
+ )
483
+
484
+ brief_version = (
485
+ int(design_brief_version)
486
+ if design_brief_version is not None
487
+ else parent.design_brief_version
488
+ )
489
+
490
+ self.get_frozen_design_brief(
491
+ project,
492
+ owner,
493
+ brief_id,
494
+ brief_version,
495
+ )
496
+
497
+ next_revision = parent.revision + 1
498
+
499
+ revision_uuid = uuid4()
500
+ state = draft.state.model_copy(deep=True)
501
+ if isinstance(state, EngineeringResult):
502
+ if state.product.manifest.product_id != project:
503
+ raise ProjectStateError("project_revision_identity_mismatch", "Domain product targets a different project.")
504
+ else:
505
+ metadata = dict(state.assembly_metadata or {})
506
+
507
+ supplied_project = str(
508
+ metadata.get("project_id") or ""
509
+ ).strip()
510
+
511
+ if supplied_project and supplied_project != project:
512
+ raise ProjectStateError(
513
+ "project_revision_identity_mismatch",
514
+ "Revised state targets a different project.",
515
+ )
516
+
517
+ state.assembly_metadata = {
518
+ **metadata,
519
+ "project_id": project,
520
+ "revision": next_revision,
521
+ "project_revision": next_revision,
522
+ "canonical_revision_id": str(revision_uuid),
523
+ "design_brief_id": str(brief_id),
524
+ "design_brief_version": brief_version,
525
+ "source_job_id": job_id,
526
+ }
527
+
528
+ normalized = draft.model_copy(
529
+ update={
530
+ "state": state,
531
+ "components": list(getattr(state, "components", [])),
532
+ }
533
+ )
534
+
535
+ revision = ProjectRevision(
536
+ **normalized.model_dump(),
537
+ revision_id=revision_uuid,
538
+ project_id=project_uuid,
539
+ owner_user_id=owner,
540
+ revision=next_revision,
541
+ parent_revision=parent.revision,
542
+ design_brief_id=brief_id,
543
+ design_brief_version=brief_version,
544
+ source_job_id=job_id,
545
+ )
546
+
547
+ record = {
548
+ "id": str(revision.revision_id),
549
+ "project_id": project,
550
+ "owner_user_id": owner,
551
+ "revision": revision.revision,
552
+ "parent_revision": revision.parent_revision,
553
+ "design_brief_id": str(revision.design_brief_id),
554
+ "design_brief_version": revision.design_brief_version,
555
+ "source_job_id": job_id,
556
+ "payload_json": revision.model_dump(mode="json"),
557
+ "created_at": revision.created_at.isoformat(),
558
+ }
559
+
560
+ saved = self._repository.insert_project_revision(
561
+ record,
562
+ parent.revision,
563
+ )
564
+
565
+ if saved is not None:
566
+ return ProjectRevisionOutcome(
567
+ revision=_revision_from_record(saved)
568
+ )
569
+
570
+ replay = self.get_by_source_job(
571
+ project,
572
+ owner,
573
+ job_id,
574
+ )
575
+
576
+ if replay is not None:
577
+ return ProjectRevisionOutcome(
578
+ revision=replay,
579
+ idempotent_replay=True,
580
+ )
581
+
582
+ raise ProjectStateError(
583
+ "project_revision_conflict",
584
+ "Project state changed before the revision could be committed.",
585
+ retryable=True,
586
+ context={
587
+ "project_id": project,
588
+ "parent_revision": parent.revision,
589
+ },
590
+ )
591
+
592
+ @staticmethod
593
+ def _require_identity(
594
+ revision: ProjectRevision,
595
+ project_id: UUID,
596
+ design_brief_id: UUID,
597
+ design_brief_version: int,
598
+ source_job_id: str,
599
+ ) -> None:
600
+ if (
601
+ revision.project_id != project_id
602
+ or revision.design_brief_id != design_brief_id
603
+ or revision.design_brief_version != design_brief_version
604
+ or revision.source_job_id != source_job_id
605
+ ):
606
+ raise ProjectStateError(
607
+ "project_revision_idempotency_conflict",
608
+ "The source job is already attached to a different project or DesignBrief revision.",
609
+ )
610
+
611
+
612
+ __all__ = [
613
+ "PROJECT_REVISION_SCHEMA_VERSION",
614
+ "ProjectArtifact",
615
+ "ProjectRevision",
616
+ "ProjectRevisionDraft",
617
+ "ProjectRevisionOutcome",
618
+ "ProjectStateError",
619
+ "ProjectStateRepository",
620
+ "ProjectStateService",
621
+ "ProjectSystem",
622
+ ]
@@ -0,0 +1,28 @@
1
+ from forma_core.workspaces.readiness.evaluator import evaluate_readiness
2
+ from forma_core.workspaces.readiness.models import (
3
+ BuildAnywayRequest,
4
+ BuildInitiationOutcome,
5
+ BuildMode,
6
+ BuildRequest,
7
+ ProjectBuild,
8
+ ReadinessBlocker,
9
+ ReadinessBlockerCategory,
10
+ ReadinessResult,
11
+ ReadinessStatus,
12
+ )
13
+ from forma_core.workspaces.readiness.service import ProjectBuildService, ReadinessError
14
+
15
+ __all__ = [
16
+ "BuildAnywayRequest",
17
+ "BuildInitiationOutcome",
18
+ "BuildMode",
19
+ "BuildRequest",
20
+ "ProjectBuild",
21
+ "ProjectBuildService",
22
+ "ReadinessBlocker",
23
+ "ReadinessBlockerCategory",
24
+ "ReadinessError",
25
+ "ReadinessResult",
26
+ "ReadinessStatus",
27
+ "evaluate_readiness",
28
+ ]