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
forma_core/database.py ADDED
@@ -0,0 +1,2362 @@
1
+ import logging
2
+ from forma_core.config import config
3
+ import copy
4
+ import uuid
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timezone
7
+ from typing import Any, Callable, Dict, List, Optional
8
+ from urllib.parse import urlparse
9
+
10
+ from dotenv import load_dotenv
11
+ from forma_core.runtime import deployment_mode_enabled, forma_dev_mode_enabled
12
+ from forma_core.project_list_cache import invalidate_project_lists
13
+ from forma_core.workspaces.projects.objects import attach_project_object_metadata_to_dict
14
+ from forma_core.workspaces.design_briefs import DesignBrief, DesignBriefCreate
15
+ from forma_core.workspaces.projects import ProjectRevision, ProjectStateError, ProjectStateService
16
+ from forma_core.workspaces.projects.resolver import ProjectReadResolution, ProjectReadResolver
17
+ from forma_core.workspaces.readiness import (
18
+ BuildInitiationOutcome,
19
+ BuildMode,
20
+ ProjectBuild,
21
+ ProjectBuildService,
22
+ ReadinessError,
23
+ ReadinessResult,
24
+ ReadinessStatus,
25
+ evaluate_readiness,
26
+ )
27
+ from forma_core.workspaces.workflow import (
28
+ ProjectWorkflow,
29
+ ProjectWorkflowService,
30
+ ProjectWorkflowState,
31
+ ProjectWorkflowTransition,
32
+ WorkflowActorType,
33
+ WorkflowTransitionOutcome,
34
+ ensure_action_allowed,
35
+ )
36
+ from forma_core.persistence.base import DatabaseProvider
37
+ from forma_core.persistence.models import (
38
+ Base,
39
+ DBAlphaSignup,
40
+ DBComponentTemplate,
41
+ DBProjectChat,
42
+ DBUserIntegrationConfig,
43
+ DBUserSettings,
44
+ DBWorkspaceIntegrationConfig,
45
+ )
46
+ from forma_core.persistence.providers import SQLiteProvider, SupabaseProvider, create_sqlite_provider
47
+ from forma_core.persistence.repositories import (
48
+ ApplicationRepository,
49
+ SqlAlchemyRepository,
50
+ SupabaseRepository,
51
+ )
52
+
53
+ load_dotenv()
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ DEFAULT_SQLITE_DATABASE_URL = "sqlite:///./forma.db"
58
+ SUPABASE_KEY_ENV_VARS = (
59
+ "SUPABASE_SERVICE_ROLE_KEY",
60
+ "SUPABASE_SECRET_KEY",
61
+ )
62
+ DATABASE_BACKEND_ENV_VARS = ("DATABASE_BACKEND", "DATABASE_PROVIDER", "DB_BACKEND", "DB_PROVIDER")
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class DatabaseConfig:
67
+ backend: str
68
+ source: str
69
+ url: str
70
+
71
+
72
+ class DesignBriefNotFoundError(LookupError):
73
+ """The requested project brief or version is not visible to the caller."""
74
+
75
+
76
+ class DesignBriefAccessError(PermissionError):
77
+ """The project id is already owned by a different user."""
78
+
79
+
80
+ class CliProjectConflictError(RuntimeError):
81
+ """A CLI sync write was based on a stale remote revision."""
82
+
83
+
84
+ def _env(name: str, default: Optional[str] = None) -> Optional[str]:
85
+ value = config.get(name)
86
+ if value is None:
87
+ return default
88
+ value = value.strip()
89
+ return value or default
90
+
91
+
92
+ def _backend_override() -> Optional[str]:
93
+ aliases = {
94
+ "sqlite": "sqlite",
95
+ "sqlite3": "sqlite",
96
+ "supabase": "supabase",
97
+ }
98
+ for name in DATABASE_BACKEND_ENV_VARS:
99
+ value = _env(name)
100
+ if not value:
101
+ continue
102
+ normalized = aliases.get(value.lower())
103
+ if normalized:
104
+ return normalized
105
+ logger.warning("Ignoring unsupported %s=%r. Expected sqlite or supabase.", name, value)
106
+ return None
107
+
108
+
109
+ def _sqlite_database_url() -> str:
110
+ value = _env("SQLITE_DATABASE_URL") or _env("SQLITE_DB_URL") or DEFAULT_SQLITE_DATABASE_URL
111
+ if "://" not in value:
112
+ return f"sqlite:///{value}"
113
+ return value
114
+
115
+
116
+ def _supabase_url() -> Optional[str]:
117
+ return _env("SUPABASE_URL") or _env("NEXT_PUBLIC_SUPABASE_URL")
118
+
119
+
120
+ def _is_local_supabase_url(url: Optional[str]) -> bool:
121
+ if not url:
122
+ return False
123
+ try:
124
+ parsed = urlparse(url)
125
+ except Exception:
126
+ return False
127
+ host = (parsed.hostname or "").strip().lower()
128
+ return host in {"localhost", "127.0.0.1", "::1"} or host.endswith(".localhost")
129
+
130
+
131
+ def _supabase_key() -> tuple[Optional[str], Optional[str]]:
132
+ for name in SUPABASE_KEY_ENV_VARS:
133
+ value = _env(name)
134
+ if value:
135
+ return value, name
136
+ return None, None
137
+
138
+
139
+ def _public_supabase_key_sources() -> List[str]:
140
+ return [
141
+ name
142
+ for name in ("SUPABASE_KEY", "SUPABASE_ANON_KEY", "NEXT_PUBLIC_SUPABASE_ANON_KEY")
143
+ if _env(name)
144
+ ]
145
+
146
+
147
+ def _warn_ignored_database_urls() -> None:
148
+ ignored = [
149
+ name
150
+ for name in (
151
+ "SUPABASE_DATABASE_URL",
152
+ "SUPABASE_DB_URL",
153
+ "SUPABASE_POSTGRES_URL",
154
+ "SUPABASE_POOLER_URL",
155
+ "DATABASE_URL",
156
+ "POSTGRES_URL",
157
+ "POSTGRES_URL_NON_POOLING",
158
+ )
159
+ if _env(name)
160
+ ]
161
+ if ignored:
162
+ logger.warning(
163
+ "Ignoring raw database URL env vars (%s). Supabase mode uses SUPABASE_URL plus "
164
+ "SUPABASE_SERVICE_ROLE_KEY/SUPABASE_SECRET_KEY through the Supabase client.",
165
+ ", ".join(ignored),
166
+ )
167
+
168
+
169
+ def _build_supabase_client(url: str, key: str):
170
+ try:
171
+ import httpx
172
+ from supabase import create_client
173
+ from supabase.lib.client_options import SyncClientOptions
174
+ except ImportError as exc:
175
+ raise RuntimeError("Supabase client is not installed. Run pip install -r apps/api/requirements.txt.") from exc
176
+ # The sync Supabase client enables HTTP/2 by default, but its httpcore stream
177
+ # bookkeeping is not safe when shared by FastAPI's concurrent worker threads.
178
+ http_client = httpx.Client(http2=False, follow_redirects=True, timeout=120)
179
+ return create_client(url, key, options=SyncClientOptions(httpx_client=http_client))
180
+
181
+
182
+ def _select_database_config() -> tuple[DatabaseConfig, Any, Any]:
183
+ override = _backend_override()
184
+ sqlite_url = _sqlite_database_url()
185
+ url = _supabase_url()
186
+
187
+ if forma_dev_mode_enabled():
188
+ if override == "supabase" and _is_local_supabase_url(url):
189
+ logger.info("FORMA_DEV_MODE=true with local DATABASE_BACKEND=supabase; using local Supabase.")
190
+ else:
191
+ if override == "supabase":
192
+ logger.warning("FORMA_DEV_MODE=true overrides remote DATABASE_BACKEND=supabase; using SQLite.")
193
+ provider = create_sqlite_provider(source="FORMA_DEV_MODE", url=sqlite_url)
194
+ return DatabaseConfig(backend="sqlite", source="FORMA_DEV_MODE", url=sqlite_url), provider.engine, None
195
+
196
+ if override == "sqlite":
197
+ provider = create_sqlite_provider(source="SQLITE_DATABASE_URL", url=sqlite_url)
198
+ return DatabaseConfig(backend="sqlite", source="SQLITE_DATABASE_URL", url=sqlite_url), provider.engine, None
199
+
200
+ key, key_source = _supabase_key()
201
+ public_key_sources = _public_supabase_key_sources()
202
+ if override == "supabase" and (not url or not key):
203
+ public_key_hint = (
204
+ f" Found public/anon key env vars instead: {', '.join(public_key_sources)}."
205
+ if public_key_sources
206
+ else ""
207
+ )
208
+ raise RuntimeError(
209
+ "DATABASE_BACKEND=supabase requires SUPABASE_URL plus SUPABASE_SERVICE_ROLE_KEY "
210
+ "or SUPABASE_SECRET_KEY. The backend writes seed/project data and cannot use anon/publishable keys."
211
+ f"{public_key_hint}"
212
+ )
213
+
214
+ if url and key:
215
+ _warn_ignored_database_urls()
216
+ client = _build_supabase_client(url, key)
217
+ return DatabaseConfig(backend="supabase", source=f"SUPABASE_URL+{key_source}", url=url), None, client
218
+
219
+ if url or key:
220
+ if deployment_mode_enabled():
221
+ raise RuntimeError(
222
+ "FORMA_DEPLOYMENT_MODE=hosted requires SUPABASE_URL plus "
223
+ "SUPABASE_SERVICE_ROLE_KEY or SUPABASE_SECRET_KEY. Refusing to fall back to local SQLite."
224
+ )
225
+ logger.warning(
226
+ "Supabase client is partially configured. Provide both SUPABASE_URL and "
227
+ "SUPABASE_SERVICE_ROLE_KEY/SUPABASE_SECRET_KEY. Falling back to SQLite."
228
+ )
229
+ else:
230
+ if deployment_mode_enabled():
231
+ raise RuntimeError(
232
+ "FORMA_DEPLOYMENT_MODE=hosted requires Supabase persistence. Set DATABASE_BACKEND=sqlite "
233
+ "only for an explicitly documented local/self-hosted deployment."
234
+ )
235
+ _warn_ignored_database_urls()
236
+
237
+ provider = create_sqlite_provider(source="SQLITE_DATABASE_URL", url=sqlite_url)
238
+ return DatabaseConfig(backend="sqlite", source="SQLITE_DATABASE_URL", url=sqlite_url), provider.engine, None
239
+
240
+
241
+ _ACTIVE_DATABASE_CONFIG, engine, _SUPABASE_CLIENT = _select_database_config()
242
+ DATABASE_BACKEND = _ACTIVE_DATABASE_CONFIG.backend
243
+ DATABASE_SOURCE = _ACTIVE_DATABASE_CONFIG.source
244
+ DATABASE_URL = _ACTIVE_DATABASE_CONFIG.url
245
+ _DATABASE_PROVIDER: DatabaseProvider
246
+ if DATABASE_BACKEND == "supabase":
247
+ _DATABASE_PROVIDER = SupabaseProvider(
248
+ source=DATABASE_SOURCE,
249
+ url=DATABASE_URL,
250
+ client=_SUPABASE_CLIENT,
251
+ )
252
+ else:
253
+ assert engine is not None
254
+ _DATABASE_PROVIDER = SQLiteProvider(
255
+ source=DATABASE_SOURCE,
256
+ url=DATABASE_URL,
257
+ engine=engine,
258
+ )
259
+ _DATABASE_REPOSITORY: ApplicationRepository
260
+ if DATABASE_BACKEND == "supabase":
261
+ SessionLocal = None
262
+ _DATABASE_REPOSITORY = SupabaseRepository(_SUPABASE_CLIENT)
263
+ else:
264
+ assert isinstance(_DATABASE_PROVIDER, SQLiteProvider)
265
+ SessionLocal = _DATABASE_PROVIDER.session_factory
266
+ assert SessionLocal is not None
267
+ _DATABASE_REPOSITORY = SqlAlchemyRepository(SessionLocal)
268
+
269
+
270
+ def _canonical_project_id(value: str) -> str:
271
+ try:
272
+ return str(uuid.UUID(str(value).strip()))
273
+ except (TypeError, ValueError, AttributeError) as exc:
274
+ raise ValueError(f"generated_projects.project_id must be a UUID, got {value!r}.") from exc
275
+
276
+
277
+ def _normalize_chat_id(value: Optional[str]) -> Optional[str]:
278
+ if value is None:
279
+ return None
280
+ normalized = str(value).strip()
281
+ return normalized or None
282
+
283
+
284
+ def _normalize_user_id(value: Optional[str]) -> Optional[str]:
285
+ if value is None:
286
+ return None
287
+ normalized = str(value).strip()
288
+ return normalized or None
289
+
290
+
291
+ def _normalize_visibility(value: Optional[str]) -> str:
292
+ normalized = (value or "public").strip().lower()
293
+ return normalized if normalized in {"public", "private"} else "public"
294
+
295
+
296
+ def _hardware_ir_with_project_id(
297
+ project_id: str,
298
+ hardware_ir: Dict[str, Any],
299
+ chat_id: Optional[str] = None,
300
+ ) -> Dict[str, Any]:
301
+ hardware_ir = dict(hardware_ir or {})
302
+ metadata = dict(hardware_ir.get("assembly_metadata") or {})
303
+ metadata_project_id = metadata.get("project_id")
304
+ if metadata_project_id and _canonical_project_id(metadata_project_id) != project_id:
305
+ raise ValueError(
306
+ "hardware_ir.assembly_metadata.project_id must match generated_projects.project_id."
307
+ )
308
+ metadata["project_id"] = project_id
309
+ normalized_chat_id = _normalize_chat_id(chat_id) or _normalize_chat_id(metadata.get("chat_id"))
310
+ if normalized_chat_id:
311
+ metadata["chat_id"] = normalized_chat_id
312
+ hardware_ir["assembly_metadata"] = metadata
313
+ object_metadata = metadata.get("project_object") if isinstance(metadata.get("project_object"), dict) else {}
314
+ target_namespace = metadata.get("iteration_target_namespace") or object_metadata.get("target_namespace")
315
+ return attach_project_object_metadata_to_dict(hardware_ir, target_namespace=target_namespace)
316
+
317
+
318
+ def _sqlite_session():
319
+ if SessionLocal is None:
320
+ raise RuntimeError("SQLite session requested while Supabase backend is active.")
321
+ return SessionLocal()
322
+
323
+
324
+ def get_supabase_client():
325
+ if DATABASE_BACKEND != "supabase" or _SUPABASE_CLIENT is None:
326
+ raise RuntimeError("Supabase client requested while SQLite backend is active.")
327
+ return _SUPABASE_CLIENT
328
+
329
+
330
+ def get_database_provider() -> DatabaseProvider:
331
+ """Return the provider selected once at application composition time."""
332
+
333
+ return _DATABASE_PROVIDER
334
+
335
+
336
+ def init_db() -> None:
337
+ _DATABASE_PROVIDER.initialize()
338
+
339
+
340
+ def get_db():
341
+ db = _sqlite_session()
342
+ try:
343
+ yield db
344
+ finally:
345
+ db.close()
346
+
347
+
348
+ def count_component_templates() -> int:
349
+ return _DATABASE_REPOSITORY.count_component_templates()
350
+
351
+
352
+ def list_component_templates() -> List[Any]:
353
+ return _DATABASE_REPOSITORY.list_component_templates()
354
+
355
+
356
+ def get_component_template_by_part_number(part_number: str) -> Optional[Any]:
357
+ return _DATABASE_REPOSITORY.get_component_template_by_part_number(part_number)
358
+
359
+
360
+ def insert_component_template_if_missing(component: Dict[str, Any]) -> bool:
361
+ if get_component_template_by_part_number(component["part_number"]):
362
+ return False
363
+
364
+ record = {
365
+ "part_number": component["part_number"],
366
+ "name": component["name"],
367
+ "category": component["category"],
368
+ "description": component["description"],
369
+ "price": component["price"],
370
+ "sourcing_url": component["sourcing_url"],
371
+ "pins": component["pins"],
372
+ "use_cases": component["use_cases"],
373
+ }
374
+ _DATABASE_REPOSITORY.insert_component_template(record)
375
+ return True
376
+
377
+
378
+ def save_generated_project(
379
+ project_id: str,
380
+ title: str,
381
+ prompt: str,
382
+ hardware_ir: Dict[str, Any],
383
+ created_at: str,
384
+ chat_id: Optional[str] = None,
385
+ owner_user_id: Optional[str] = None,
386
+ visibility: Optional[str] = "public",
387
+ create_chat_record: bool = True,
388
+ ) -> None:
389
+ project_id = _canonical_project_id(project_id)
390
+ source_project_id = (hardware_ir.get("assembly_metadata") or {}).get("source_project_id") if isinstance(hardware_ir, dict) else None
391
+ if source_project_id:
392
+ source_project = get_generated_project(_canonical_project_id(source_project_id), include_deleted=True)
393
+ if not source_project or getattr(source_project, "status", "active") != "active":
394
+ raise RuntimeError("Cannot persist output for a deleted or missing source project.")
395
+ hardware_ir = _hardware_ir_with_project_id(project_id, hardware_ir, chat_id=chat_id)
396
+ metadata = hardware_ir.get("assembly_metadata") if isinstance(hardware_ir.get("assembly_metadata"), dict) else {}
397
+ normalized_chat_id = _normalize_chat_id(chat_id) or _normalize_chat_id(metadata.get("chat_id"))
398
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
399
+ linked_brief = _DATABASE_REPOSITORY.get_latest_design_brief(project_id, None)
400
+ if linked_brief is not None and getattr(linked_brief, "owner_user_id", None) != normalized_owner_user_id:
401
+ raise DesignBriefAccessError("DesignBrief is not owned by the project owner.")
402
+ linked_workflow = _DATABASE_REPOSITORY.get_project_workflow(project_id, None)
403
+ if linked_workflow is not None and getattr(linked_workflow, "owner_user_id", None) != normalized_owner_user_id:
404
+ raise DesignBriefAccessError("Workflow is not owned by the project owner.")
405
+ normalized_visibility = _normalize_visibility(visibility)
406
+ record = {
407
+ "project_id": project_id,
408
+ "chat_id": normalized_chat_id,
409
+ "owner_user_id": normalized_owner_user_id,
410
+ "creation_channel": "hosted",
411
+ "visibility": normalized_visibility,
412
+ "title": title,
413
+ "prompt": prompt,
414
+ "hardware_ir": hardware_ir,
415
+ "created_at": created_at,
416
+ "status": "active",
417
+ }
418
+ chat_record = None
419
+ if create_chat_record and normalized_chat_id and normalized_owner_user_id:
420
+ chat_record = {
421
+ "chat_id": normalized_chat_id,
422
+ "owner_user_id": normalized_owner_user_id,
423
+ "title": title or prompt[:80] or "Untitled chat",
424
+ "messages": [],
425
+ "created_at": created_at,
426
+ "updated_at": created_at,
427
+ }
428
+ _DATABASE_REPOSITORY.save_generated_project(record, chat_record)
429
+ invalidate_project_lists()
430
+
431
+
432
+ def persist_legacy_project_projection(
433
+ *,
434
+ project_id: str,
435
+ title: str,
436
+ prompt: str,
437
+ hardware_ir: Dict[str, Any],
438
+ created_at: str,
439
+ chat_id: Optional[str] = None,
440
+ owner_user_id: Optional[str] = None,
441
+ visibility: Optional[str] = "public",
442
+ create_chat_record: bool = True,
443
+ ) -> None:
444
+ """Write the retained generated-project compatibility projection."""
445
+
446
+ save_generated_project(
447
+ project_id=project_id,
448
+ title=title,
449
+ prompt=prompt,
450
+ hardware_ir=hardware_ir,
451
+ created_at=created_at,
452
+ chat_id=chat_id,
453
+ owner_user_id=owner_user_id,
454
+ visibility=visibility,
455
+ create_chat_record=create_chat_record,
456
+ )
457
+
458
+
459
+ def ensure_project_identity(
460
+ project_id: str,
461
+ owner_user_id: str,
462
+ *,
463
+ title: str = "Untitled Forma Project",
464
+ prompt: str = "",
465
+ chat_id: Optional[str] = None,
466
+ created_at: Optional[str] = None,
467
+ visibility: str = "public",
468
+ ) -> Dict[str, Any]:
469
+ """Create the canonical identity needed before a chat project can build."""
470
+
471
+ canonical_project_id = _canonical_project_id(project_id)
472
+ owner = _normalize_user_id(owner_user_id)
473
+ if not owner:
474
+ raise ValueError("owner_user_id is required.")
475
+ existing_identity = _DATABASE_REPOSITORY.get_project_identity(canonical_project_id)
476
+ if existing_identity is not None:
477
+ existing_owner = _normalize_user_id(existing_identity.get("owner_user_id"))
478
+ if existing_owner != owner:
479
+ raise DesignBriefAccessError("Project is not owned by the current user.")
480
+ if existing_identity.get("status", "active") != "active":
481
+ raise DesignBriefAccessError("Cannot initialize a deleted project.")
482
+ title = existing_identity.get("title") or title
483
+ prompt = existing_identity.get("prompt") or prompt
484
+ chat_id = existing_identity.get("chat_id") or chat_id
485
+ created_at = existing_identity.get("created_at") or created_at
486
+ visibility = existing_identity.get("visibility") or visibility
487
+ timestamp = created_at or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
488
+ record = {
489
+ "project_id": canonical_project_id,
490
+ "owner_user_id": owner,
491
+ "creation_channel": "hosted",
492
+ "title": str(title or "Untitled Forma Project").strip() or "Untitled Forma Project",
493
+ "prompt": str(prompt or "").strip(),
494
+ "chat_id": _normalize_chat_id(chat_id),
495
+ "workspace_id": None,
496
+ "visibility": _normalize_visibility(visibility),
497
+ "status": "active",
498
+ "created_at": timestamp,
499
+ "updated_at": timestamp,
500
+ }
501
+ _DATABASE_REPOSITORY.upsert_project_identity(record)
502
+ return record
503
+
504
+
505
+ def update_project_identity(
506
+ project_id: str,
507
+ owner_user_id: str,
508
+ *,
509
+ title: Optional[str] = None,
510
+ prompt: Optional[str] = None,
511
+ visibility: Optional[str] = None,
512
+ ) -> bool:
513
+ """Update canonical project metadata; compatibility projections are rebuilt separately."""
514
+ canonical_project_id = _canonical_project_id(project_id)
515
+ owner = _normalize_user_id(owner_user_id)
516
+ identity = _DATABASE_REPOSITORY.get_project_identity(canonical_project_id)
517
+ if not owner or identity is None or _normalize_user_id(identity.get("owner_user_id")) != owner:
518
+ return False
519
+ if identity.get("status", "active") != "active":
520
+ return False
521
+ record = dict(identity)
522
+ if title is not None:
523
+ record["title"] = title.strip() or "Untitled Forma Project"
524
+ if prompt is not None:
525
+ record["prompt"] = prompt.strip()
526
+ if visibility is not None:
527
+ record["visibility"] = _normalize_visibility(visibility)
528
+ record["updated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
529
+ _DATABASE_REPOSITORY.upsert_project_identity(record)
530
+ invalidate_project_lists()
531
+ return True
532
+
533
+
534
+ def ensure_chat_project(
535
+ project_id: str,
536
+ owner_user_id: str,
537
+ *,
538
+ prompt: str,
539
+ chat_id: Optional[str] = None,
540
+ title: Optional[str] = None,
541
+ ) -> DesignBrief:
542
+ """Bootstrap a chat project's canonical identity and first frozen brief."""
543
+
544
+ canonical_project_id = _canonical_project_id(project_id)
545
+ owner = _normalize_user_id(owner_user_id)
546
+ if not owner:
547
+ raise ValueError("owner_user_id is required.")
548
+ existing_identity = get_project_identity(canonical_project_id)
549
+ existing_legacy = None
550
+ if existing_identity is None:
551
+ # Pre-migration local databases still need to bootstrap into the
552
+ # canonical identity/revision model without making the legacy row the
553
+ # ongoing source of truth.
554
+ existing_legacy = get_generated_project(canonical_project_id, include_deleted=True)
555
+ existing = existing_identity or existing_legacy
556
+ if existing is not None:
557
+ existing_owner = _normalize_user_id(
558
+ existing.get("owner_user_id") if isinstance(existing, dict) else getattr(existing, "owner_user_id", None)
559
+ )
560
+ if existing_owner != owner:
561
+ raise DesignBriefAccessError("Project is not owned by the current user.")
562
+ existing_status = existing.get("status", "active") if isinstance(existing, dict) else getattr(existing, "status", "active")
563
+ if existing_status != "active":
564
+ raise DesignBriefAccessError("Cannot initialize a deleted project.")
565
+
566
+ summary = str(prompt or "").strip() or str(title or "Untitled Forma Project").strip()
567
+ existing_title = existing.get("title") if isinstance(existing, dict) else getattr(existing, "title", None)
568
+ existing_prompt = existing.get("prompt") if isinstance(existing, dict) else getattr(existing, "prompt", None)
569
+ existing_created_at = existing.get("created_at") if isinstance(existing, dict) else getattr(existing, "created_at", None)
570
+ existing_visibility = existing.get("visibility") if isinstance(existing, dict) else getattr(existing, "visibility", "public")
571
+ identity = ensure_project_identity(
572
+ canonical_project_id,
573
+ owner,
574
+ title=(title or existing_title or summary),
575
+ prompt=existing_prompt or summary,
576
+ chat_id=chat_id,
577
+ created_at=existing_created_at,
578
+ visibility=existing_visibility or "public",
579
+ )
580
+ canonical_chat_id = identity.get("chat_id") or _normalize_chat_id(chat_id)
581
+
582
+ try:
583
+ brief = get_latest_design_brief(canonical_project_id, owner)
584
+ except DesignBriefNotFoundError:
585
+ brief = create_design_brief_version(
586
+ canonical_project_id,
587
+ owner,
588
+ DesignBriefCreate(
589
+ schema_version="1.0",
590
+ conversation_id=canonical_chat_id or f"project-{canonical_project_id}",
591
+ intent=summary,
592
+ summary=summary,
593
+ ),
594
+ )
595
+ return brief
596
+
597
+
598
+ def persist_chat_project_revision(
599
+ project_id: str,
600
+ owner_user_id: str,
601
+ state: Any,
602
+ *,
603
+ source_job_id: str,
604
+ prompt: str,
605
+ chat_id: Optional[str] = None,
606
+ visibility: Optional[str] = None,
607
+ expected_parent_revision: int | None = None,
608
+ ) -> ProjectRevision:
609
+ """Commit generated chat output canonically, then refresh its gallery projection."""
610
+
611
+ from forma_core.workers.generation import build_generation_draft
612
+ from forma_core.workspaces.projects.models import HardwareIntermediateRepresentation
613
+
614
+ canonical_project_id = _canonical_project_id(project_id)
615
+ brief = ensure_chat_project(
616
+ canonical_project_id,
617
+ owner_user_id,
618
+ prompt=prompt,
619
+ chat_id=chat_id,
620
+ )
621
+ if visibility is not None:
622
+ if not update_project_identity(
623
+ canonical_project_id,
624
+ owner_user_id,
625
+ visibility=visibility,
626
+ ):
627
+ raise ValueError("Could not update the canonical project visibility.")
628
+ service = ProjectStateService(_DATABASE_REPOSITORY)
629
+ from forma_core.domains.generation import EngineeringResult
630
+ candidate = state if isinstance(state, EngineeringResult) else HardwareIntermediateRepresentation.model_validate(state)
631
+ try:
632
+ service.get_latest(canonical_project_id, owner_user_id)
633
+ except ProjectStateError as exc:
634
+ if exc.code != "project_revision_not_found":
635
+ raise
636
+ if not isinstance(candidate, EngineeringResult):
637
+ metadata = dict(candidate.assembly_metadata or {})
638
+ metadata["project_id"] = canonical_project_id
639
+ metadata.pop("revision", None)
640
+ candidate.assembly_metadata = metadata
641
+ revision = service.create_initial_revision(
642
+ build_generation_draft(brief, candidate),
643
+ project_id=canonical_project_id,
644
+ owner_user_id=owner_user_id,
645
+ design_brief_id=brief.design_brief_id,
646
+ design_brief_version=brief.brief_version,
647
+ source_job_id=source_job_id,
648
+ ).revision
649
+ else:
650
+ revision = service.create_revision(
651
+ build_generation_draft(brief, candidate),
652
+ project_id=canonical_project_id,
653
+ owner_user_id=owner_user_id,
654
+ source_job_id=source_job_id,
655
+ expected_parent_revision=expected_parent_revision,
656
+ ).revision
657
+ publish_project_revision(revision, brief, owner_user_id)
658
+ return revision
659
+
660
+
661
+ def publish_project_revision(
662
+ revision: ProjectRevision,
663
+ brief: DesignBrief,
664
+ owner_user_id: str,
665
+ *,
666
+ visibility: Optional[str] = None,
667
+ ) -> str:
668
+ """Project canonical state into the public gallery's generated-project store."""
669
+
670
+ project_id = _canonical_project_id(str(revision.project_id))
671
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
672
+ if not normalized_owner_user_id or normalized_owner_user_id != revision.owner_user_id:
673
+ raise ValueError("Project revision owner must match owner_user_id.")
674
+ if revision.project_id != brief.project_id or revision.design_brief_id != brief.design_brief_id:
675
+ raise ValueError("Project revision and DesignBrief identities must match.")
676
+
677
+ from forma_core.domains.generation import EngineeringResult
678
+ if isinstance(revision.state, EngineeringResult):
679
+ # Canonical revisions already persist the portable report. The legacy gallery
680
+ # projection cannot represent domain semantics and must not coerce them.
681
+ invalidate_project_lists()
682
+ return project_id
683
+
684
+ ir = revision.state.model_copy(deep=True)
685
+ ir.assembly_metadata = {
686
+ **(ir.assembly_metadata or {}),
687
+ "project_id": project_id,
688
+ "chat_id": brief.conversation_id,
689
+ "project_revision": revision.revision,
690
+ "design_brief_version": revision.design_brief_version,
691
+ }
692
+ hardware_ir = ir.model_dump(mode="json")
693
+ existing = get_generated_project(project_id, include_deleted=True)
694
+ if existing is not None:
695
+ if getattr(existing, "owner_user_id", None) != normalized_owner_user_id:
696
+ raise DesignBriefAccessError("Project is not owned by the revision owner.")
697
+ if getattr(existing, "status", "active") != "active":
698
+ raise RuntimeError("Cannot publish a deleted project revision.")
699
+ if not update_generated_project_hardware_ir(
700
+ project_id,
701
+ hardware_ir,
702
+ owner_user_id=normalized_owner_user_id,
703
+ ):
704
+ raise RuntimeError("Could not refresh the generated-project gallery projection.")
705
+ if visibility is not None and not update_generated_project_metadata(
706
+ project_id,
707
+ owner_user_id=normalized_owner_user_id,
708
+ visibility=visibility,
709
+ ):
710
+ raise RuntimeError("Could not refresh the generated-project gallery visibility.")
711
+ return project_id
712
+
713
+ save_generated_project(
714
+ project_id=project_id,
715
+ title=(ir.overview.title if ir.overview else brief.summary) or "Untitled Forma Project",
716
+ prompt=brief.summary,
717
+ hardware_ir=hardware_ir,
718
+ created_at=revision.created_at.isoformat().replace("+00:00", "Z"),
719
+ chat_id=brief.conversation_id,
720
+ owner_user_id=normalized_owner_user_id,
721
+ visibility=visibility or "public",
722
+ # Context gathering already owns the chat and its messages. Publishing
723
+ # the gallery projection must not replace that thread with an empty one.
724
+ create_chat_record=False,
725
+ )
726
+ return project_id
727
+
728
+
729
+ def list_generated_projects(owner_user_id: Optional[str] = None) -> List[Any]:
730
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
731
+ return _DATABASE_REPOSITORY.list_generated_projects(normalized_owner_user_id)
732
+
733
+
734
+ def list_generated_projects_page(
735
+ owner_user_id: Optional[str] = None,
736
+ *,
737
+ visibility: Optional[str] = None,
738
+ limit: int = 6,
739
+ offset: int = 0,
740
+ search: Optional[str] = None,
741
+ ) -> tuple[List[Any], int]:
742
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
743
+ normalized_visibility = str(visibility or "").strip().lower() or None
744
+ if normalized_visibility not in {None, "public", "private"}:
745
+ raise ValueError("visibility must be public or private.")
746
+ normalized_limit = max(1, min(int(limit), 50))
747
+ normalized_offset = max(0, int(offset))
748
+ normalized_search = " ".join(str(search or "").split())[:100] or None
749
+ return _DATABASE_REPOSITORY.list_generated_projects_page(
750
+ normalized_owner_user_id,
751
+ visibility=normalized_visibility,
752
+ limit=normalized_limit,
753
+ offset=normalized_offset,
754
+ search=normalized_search,
755
+ )
756
+
757
+
758
+ def get_generated_project(project_id: str, *, include_deleted: bool = False) -> Optional[Any]:
759
+ return _DATABASE_REPOSITORY.get_generated_project(project_id, include_deleted=include_deleted)
760
+
761
+
762
+ def get_project_identity(project_id: str) -> Optional[Any]:
763
+ return _DATABASE_REPOSITORY.get_project_identity(_canonical_project_id(project_id))
764
+
765
+
766
+ def resolve_project_for_read(
767
+ project_id: str,
768
+ owner_user_id: Optional[str] = None,
769
+ *,
770
+ include_deleted: bool = False,
771
+ ) -> ProjectReadResolution:
772
+ """Resolve one readable project across generated, canonical, and CLI stores."""
773
+
774
+ return ProjectReadResolver(_DATABASE_REPOSITORY).resolve(
775
+ project_id,
776
+ owner_user_id,
777
+ include_deleted=include_deleted,
778
+ )
779
+
780
+
781
+ def list_cli_projects(owner_user_id: str) -> List[Dict[str, Any]]:
782
+ """Return private CLI project metadata without project payloads."""
783
+ owner = _normalize_user_id(owner_user_id)
784
+ if not owner:
785
+ return []
786
+ return [
787
+ {
788
+ "project_id": str(record.project_id),
789
+ "workspace_id": getattr(record, "workspace_id", None),
790
+ "creation_channel": getattr(record, "creation_channel", "cli"),
791
+ "title": getattr(record, "title", ""),
792
+ "revision_id": getattr(record, "current_revision_id", None),
793
+ "revision": getattr(record, "current_revision", 0),
794
+ "updated_at": getattr(record, "updated_at", None),
795
+ "created_at": getattr(record, "created_at", None),
796
+ }
797
+ for record in _DATABASE_REPOSITORY.list_cli_projects(owner)
798
+ ]
799
+
800
+
801
+ def list_project_identities(owner_user_id: str) -> List[Dict[str, Any]]:
802
+ """Return the canonical project identities owned by a user."""
803
+ owner = _normalize_user_id(owner_user_id)
804
+ if not owner:
805
+ return []
806
+ return [
807
+ {
808
+ "project_id": str(record.project_id),
809
+ "owner_user_id": getattr(record, "owner_user_id", owner),
810
+ "creation_channel": getattr(record, "creation_channel", "hosted"),
811
+ "title": getattr(record, "title", ""),
812
+ "prompt": getattr(record, "prompt", ""),
813
+ "chat_id": getattr(record, "chat_id", None),
814
+ "workspace_id": getattr(record, "workspace_id", None),
815
+ "visibility": getattr(record, "visibility", "public"),
816
+ "status": getattr(record, "status", "active"),
817
+ "current_revision": getattr(record, "current_revision", 0),
818
+ "current_revision_id": getattr(record, "current_revision_id", None),
819
+ "created_at": getattr(record, "created_at", None),
820
+ "updated_at": getattr(record, "updated_at", None),
821
+ }
822
+ for record in _DATABASE_REPOSITORY.list_project_identities(owner)
823
+ ]
824
+
825
+
826
+ def list_project_gallery_inventory_page(
827
+ owner_user_id: Optional[str] = None,
828
+ *,
829
+ visibility: Optional[str] = None,
830
+ limit: int = 6,
831
+ offset: int = 0,
832
+ search: Optional[str] = None,
833
+ ) -> tuple[List[Any], int]:
834
+ """Return a bounded page of canonical identities and current revisions."""
835
+ owner = _normalize_user_id(owner_user_id)
836
+ normalized_visibility = str(visibility or "").strip().lower() or None
837
+ if normalized_visibility not in {None, "public", "private"}:
838
+ raise ValueError("visibility must be public or private.")
839
+ normalized_limit = max(1, min(int(limit), 50))
840
+ normalized_offset = max(0, int(offset))
841
+ normalized_search = " ".join(str(search or "").split())[:100] or None
842
+ return _DATABASE_REPOSITORY.list_project_gallery_inventory_page(
843
+ owner,
844
+ visibility=normalized_visibility,
845
+ limit=normalized_limit,
846
+ offset=normalized_offset,
847
+ search=normalized_search,
848
+ )
849
+
850
+
851
+ def list_project_gallery_inventory(
852
+ owner_user_id: Optional[str] = None,
853
+ *,
854
+ visibility: Optional[str] = None,
855
+ search: Optional[str] = None,
856
+ ) -> List[Any]:
857
+ """Return the compatibility no-limit gallery inventory from the same source."""
858
+ owner = _normalize_user_id(owner_user_id)
859
+ normalized_visibility = str(visibility or "").strip().lower() or None
860
+ if normalized_visibility not in {None, "public", "private"}:
861
+ raise ValueError("visibility must be public or private.")
862
+ normalized_search = " ".join(str(search or "").split())[:100] or None
863
+ return _DATABASE_REPOSITORY.list_project_gallery_inventory(
864
+ owner,
865
+ visibility=normalized_visibility,
866
+ search=normalized_search,
867
+ )
868
+
869
+
870
+ def get_cli_project_revision(
871
+ project_id: str,
872
+ owner_user_id: str,
873
+ revision_id: Optional[str] = None,
874
+ ) -> Optional[Dict[str, Any]]:
875
+ owner = _normalize_user_id(owner_user_id)
876
+ project = str(project_id or "").strip()
877
+ if not owner or not project:
878
+ return None
879
+ record = _DATABASE_REPOSITORY.get_cli_project_revision(project, owner, revision_id)
880
+ if record is None:
881
+ return None
882
+ return {
883
+ "revision_id": str(record.revision_id),
884
+ "project_id": str(record.project_id),
885
+ "revision": int(record.revision),
886
+ "parent_revision_id": getattr(record, "parent_revision_id", None),
887
+ "manifest": getattr(record, "manifest_json", {}),
888
+ "created_at": getattr(record, "created_at", None),
889
+ }
890
+
891
+
892
+ def insert_cli_project_revision(
893
+ manifest: Dict[str, Any],
894
+ owner_user_id: str,
895
+ *,
896
+ expected_revision_id: Optional[str] = None,
897
+ revision_id: Optional[str] = None,
898
+ revision: Optional[int] = None,
899
+ ) -> Dict[str, Any]:
900
+ """Create one public-by-default project revision with compare-and-swap ancestry."""
901
+ owner = _normalize_user_id(owner_user_id)
902
+ project_id = str(manifest.get("project_id") or "").strip()
903
+ if not owner or not project_id:
904
+ raise ValueError("A project_id and authenticated owner are required.")
905
+ existing = _DATABASE_REPOSITORY.get_cli_project(project_id, owner)
906
+ existing_identity = _DATABASE_REPOSITORY.get_project_identity(project_id)
907
+ requested_visibility = manifest.get("visibility") or "public"
908
+ if existing_identity is not None:
909
+ requested_visibility = (
910
+ getattr(existing_identity, "visibility", None)
911
+ or (existing_identity.get("visibility") if isinstance(existing_identity, dict) else None)
912
+ or requested_visibility
913
+ )
914
+ next_revision = int(revision) if revision is not None else (
915
+ int(getattr(existing, "current_revision", 0)) + 1 if existing else 1
916
+ )
917
+ now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
918
+ requested_revision_id = str(revision_id or uuid.uuid4())
919
+ latest = _DATABASE_REPOSITORY.get_cli_project_revision(project_id, owner)
920
+ if (
921
+ latest is not None
922
+ and int(getattr(latest, "revision", 0)) == next_revision
923
+ and str(getattr(latest, "parent_revision_id", "") or "") == str(expected_revision_id or "")
924
+ and getattr(latest, "manifest_json", None) == manifest
925
+ ):
926
+ return {
927
+ "revision_id": str(latest.revision_id),
928
+ "project_id": project_id,
929
+ "revision": int(latest.revision),
930
+ "parent_revision_id": getattr(latest, "parent_revision_id", None),
931
+ "manifest": getattr(latest, "manifest_json", manifest),
932
+ "created_at": getattr(latest, "created_at", None),
933
+ }
934
+ revision_record = {
935
+ "revision_id": requested_revision_id,
936
+ "project_id": project_id,
937
+ "owner_user_id": owner,
938
+ "revision": next_revision,
939
+ "parent_revision_id": expected_revision_id,
940
+ "manifest_json": manifest,
941
+ "created_at": now,
942
+ }
943
+ project_record = {
944
+ "project_id": project_id,
945
+ "workspace_id": manifest.get("workspace_id"),
946
+ "owner_user_id": owner,
947
+ "creation_channel": "cli",
948
+ "visibility": _normalize_visibility(str(requested_visibility)),
949
+ "title": str(manifest.get("title") or "Untitled Forma Project"),
950
+ "current_revision": 0,
951
+ "current_revision_id": None,
952
+ "created_at": now,
953
+ "updated_at": now,
954
+ }
955
+ saved = _DATABASE_REPOSITORY.insert_cli_project_revision(
956
+ project_record,
957
+ revision_record,
958
+ expected_revision_id,
959
+ )
960
+ if saved is None:
961
+ raise CliProjectConflictError("The cloud project changed since the local project was last pulled.")
962
+ return {
963
+ "revision_id": str(getattr(saved, "revision_id", requested_revision_id)),
964
+ "project_id": project_id,
965
+ "revision": int(getattr(saved, "revision", next_revision)),
966
+ "parent_revision_id": getattr(saved, "parent_revision_id", expected_revision_id),
967
+ "manifest": getattr(saved, "manifest_json", manifest),
968
+ "created_at": getattr(saved, "created_at", now),
969
+ }
970
+
971
+
972
+ def _cli_delivery_from_record(record: Any) -> Optional[Dict[str, Any]]:
973
+ if record is None:
974
+ return None
975
+ return {
976
+ "delivery_id": str(record.delivery_id),
977
+ "project_id": str(record.project_id),
978
+ "owner_user_id": str(record.owner_user_id),
979
+ "idempotency_key": str(record.idempotency_key),
980
+ "revision_id": str(record.revision_id),
981
+ "revision": int(record.revision),
982
+ "parent_revision_id": getattr(record, "parent_revision_id", None),
983
+ "manifest": getattr(record, "manifest_json", {}),
984
+ "manifest_digest": getattr(record, "manifest_digest", "") or "",
985
+ "status": str(getattr(record, "status", "pending")),
986
+ "receipt": getattr(record, "receipt_json", None),
987
+ "created_at": getattr(record, "created_at", None),
988
+ "completed_at": getattr(record, "completed_at", None),
989
+ }
990
+
991
+
992
+ def get_cli_project_delivery(
993
+ project_id: str,
994
+ owner_user_id: str,
995
+ idempotency_key: str,
996
+ ) -> Optional[Dict[str, Any]]:
997
+ return _cli_delivery_from_record(
998
+ _DATABASE_REPOSITORY.get_cli_project_delivery(
999
+ str(project_id or "").strip(),
1000
+ _normalize_user_id(owner_user_id) or "",
1001
+ str(idempotency_key or "").strip(),
1002
+ )
1003
+ )
1004
+
1005
+
1006
+ def get_cli_project_delivery_by_id(delivery_id: str) -> Optional[Dict[str, Any]]:
1007
+ return _cli_delivery_from_record(
1008
+ _DATABASE_REPOSITORY.get_cli_project_delivery_by_id(str(delivery_id or "").strip())
1009
+ )
1010
+
1011
+
1012
+ def list_cli_project_deliveries(owner_user_id: str) -> List[Dict[str, Any]]:
1013
+ records = _DATABASE_REPOSITORY.list_cli_project_deliveries(_normalize_user_id(owner_user_id) or "")
1014
+ return [_cli_delivery_from_record(record) for record in records]
1015
+
1016
+
1017
+ def insert_cli_project_delivery(record: Dict[str, Any]) -> Dict[str, Any]:
1018
+ saved = _DATABASE_REPOSITORY.insert_cli_project_delivery(record)
1019
+ if saved is None:
1020
+ raise ValueError("Delivery session could not be created.")
1021
+ delivery = _cli_delivery_from_record(saved)
1022
+ if delivery is None:
1023
+ raise ValueError("Delivery session could not be created.")
1024
+ return delivery
1025
+
1026
+
1027
+ def update_cli_project_delivery(
1028
+ delivery_id: str,
1029
+ owner_user_id: str,
1030
+ updates: Dict[str, Any],
1031
+ ) -> Optional[Dict[str, Any]]:
1032
+ return _cli_delivery_from_record(
1033
+ _DATABASE_REPOSITORY.update_cli_project_delivery(
1034
+ str(delivery_id or "").strip(),
1035
+ _normalize_user_id(owner_user_id) or "",
1036
+ updates,
1037
+ )
1038
+ )
1039
+
1040
+
1041
+ def publish_cli_project(
1042
+ project_id: str,
1043
+ owner_user_id: str,
1044
+ acting_user_id: str,
1045
+ ) -> Dict[str, Any]:
1046
+ """Flip an owned private CLI project to public and record the explicit action."""
1047
+ project_id = str(project_id or "").strip()
1048
+ owner = _normalize_user_id(owner_user_id)
1049
+ acting = _normalize_user_id(acting_user_id) or owner
1050
+ if not owner or not project_id:
1051
+ raise ValueError("A project_id and authenticated owner are required.")
1052
+ identity = _DATABASE_REPOSITORY.get_project_identity(project_id)
1053
+ if identity is None:
1054
+ raise ValueError("Project identity not found.")
1055
+ identity_owner = (
1056
+ identity.get("owner_user_id")
1057
+ if isinstance(identity, dict)
1058
+ else getattr(identity, "owner_user_id", None)
1059
+ )
1060
+ if identity_owner and str(identity_owner) != owner:
1061
+ raise ValueError("Project is owned by another user.")
1062
+ current = _normalize_visibility(
1063
+ identity.get("visibility")
1064
+ if isinstance(identity, dict)
1065
+ else getattr(identity, "visibility", None)
1066
+ )
1067
+ now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
1068
+ if current == "public":
1069
+ _DATABASE_REPOSITORY.update_cli_project_visibility(project_id, owner, "public")
1070
+ return {"project_id": project_id, "visibility": "public", "published": False, "already_public": True}
1071
+ _DATABASE_REPOSITORY.upsert_project_identity(
1072
+ {
1073
+ "project_id": project_id,
1074
+ "owner_user_id": owner,
1075
+ "visibility": "public",
1076
+ "updated_at": now,
1077
+ }
1078
+ )
1079
+ _DATABASE_REPOSITORY.update_cli_project_visibility(project_id, owner, "public")
1080
+ _DATABASE_REPOSITORY.record_project_publish_audit(
1081
+ {
1082
+ "id": str(uuid.uuid4()),
1083
+ "project_id": project_id,
1084
+ "owner_user_id": owner,
1085
+ "acting_user_id": acting,
1086
+ "visibility_before": current,
1087
+ "created_at": now,
1088
+ }
1089
+ )
1090
+ invalidate_project_lists()
1091
+ return {
1092
+ "project_id": project_id,
1093
+ "visibility": "public",
1094
+ "published": True,
1095
+ "visibility_before": current,
1096
+ "published_at": now,
1097
+ }
1098
+
1099
+
1100
+ def list_project_publish_audits(project_id: str, owner_user_id: str) -> List[Dict[str, Any]]:
1101
+ records = _DATABASE_REPOSITORY.list_project_publish_audits(
1102
+ str(project_id or "").strip(),
1103
+ _normalize_user_id(owner_user_id) or "",
1104
+ )
1105
+ return [
1106
+ {
1107
+ "id": str(record.id),
1108
+ "project_id": str(record.project_id),
1109
+ "owner_user_id": str(record.owner_user_id),
1110
+ "acting_user_id": str(record.acting_user_id),
1111
+ "visibility_before": str(record.visibility_before),
1112
+ "created_at": getattr(record, "created_at", None),
1113
+ }
1114
+ for record in records
1115
+ ]
1116
+
1117
+
1118
+ def get_cli_device_authorization(device_code_hash: Optional[str] = None, user_code_hash: Optional[str] = None) -> Optional[Any]:
1119
+ return _DATABASE_REPOSITORY.get_cli_device_authorization(device_code_hash, user_code_hash)
1120
+
1121
+
1122
+ def insert_cli_device_authorization(record: Dict[str, Any]) -> Any:
1123
+ return _DATABASE_REPOSITORY.insert_cli_device_authorization(record)
1124
+
1125
+
1126
+ def update_cli_device_authorization(
1127
+ device_code_hash: str,
1128
+ updates: Dict[str, Any],
1129
+ *,
1130
+ expected_status: Optional[str] = None,
1131
+ expected_consumed: Optional[bool] = None,
1132
+ ) -> Optional[Any]:
1133
+ return _DATABASE_REPOSITORY.update_cli_device_authorization(
1134
+ device_code_hash,
1135
+ updates,
1136
+ expected_status=expected_status,
1137
+ expected_consumed=expected_consumed,
1138
+ )
1139
+
1140
+
1141
+ def get_cli_token_session(token_hash: str) -> Optional[Any]:
1142
+ return _DATABASE_REPOSITORY.get_cli_token_session(token_hash)
1143
+
1144
+
1145
+ def insert_cli_token_session(record: Dict[str, Any]) -> Any:
1146
+ return _DATABASE_REPOSITORY.insert_cli_token_session(record)
1147
+
1148
+
1149
+ def revoke_cli_token_sessions(
1150
+ *,
1151
+ token_hash: Optional[str] = None,
1152
+ refresh_token_hash: Optional[str] = None,
1153
+ revoked_at: float,
1154
+ ) -> int:
1155
+ return _DATABASE_REPOSITORY.revoke_cli_token_sessions(
1156
+ token_hash=token_hash,
1157
+ refresh_token_hash=refresh_token_hash,
1158
+ revoked_at=revoked_at,
1159
+ )
1160
+
1161
+
1162
+ def _design_brief_from_record(record: Any) -> DesignBrief:
1163
+ payload = getattr(record, "payload_json", None)
1164
+ if not isinstance(payload, dict):
1165
+ raise ValueError("Persisted DesignBrief payload_json must be an object.")
1166
+ return DesignBrief.model_validate(payload)
1167
+
1168
+
1169
+ def create_design_brief_version(
1170
+ project_id: str,
1171
+ owner_user_id: str,
1172
+ brief: DesignBriefCreate,
1173
+ ) -> DesignBrief:
1174
+ canonical_project_id = _canonical_project_id(project_id)
1175
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1176
+ if not normalized_owner_user_id:
1177
+ raise ValueError("owner_user_id is required.")
1178
+
1179
+ project = _DATABASE_REPOSITORY.get_generated_project(canonical_project_id, include_deleted=True)
1180
+ if project is not None:
1181
+ if getattr(project, "owner_user_id", None) != normalized_owner_user_id:
1182
+ raise DesignBriefAccessError("Project is not owned by the current user.")
1183
+ if getattr(project, "status", "active") != "active":
1184
+ raise DesignBriefAccessError("Cannot append a DesignBrief to a deleted project.")
1185
+
1186
+ workflow = _DATABASE_REPOSITORY.get_project_workflow(canonical_project_id, None)
1187
+ if workflow is not None and getattr(workflow, "owner_user_id", None) != normalized_owner_user_id:
1188
+ raise DesignBriefAccessError("Project workflow is not owned by the current user.")
1189
+
1190
+ previous = _DATABASE_REPOSITORY.get_latest_design_brief(canonical_project_id, None)
1191
+ if previous is not None and getattr(previous, "owner_user_id", None) != normalized_owner_user_id:
1192
+ raise DesignBriefAccessError("Project is not owned by the current user.")
1193
+
1194
+ previous_brief = _design_brief_from_record(previous) if previous is not None else None
1195
+ next_version = previous_brief.brief_version + 1 if previous_brief else 1
1196
+ now = datetime.now(timezone.utc)
1197
+ design_brief = DesignBrief(
1198
+ **brief.model_dump(),
1199
+ design_brief_id=previous_brief.design_brief_id if previous_brief else uuid.uuid4(),
1200
+ project_id=canonical_project_id,
1201
+ brief_version=next_version,
1202
+ previous_version=previous_brief.brief_version if previous_brief else None,
1203
+ created_at=now,
1204
+ )
1205
+ record = {
1206
+ "id": str(uuid.uuid4()),
1207
+ "design_brief_id": str(design_brief.design_brief_id),
1208
+ "project_id": canonical_project_id,
1209
+ "conversation_id": design_brief.conversation_id,
1210
+ "owner_user_id": normalized_owner_user_id,
1211
+ "brief_version": design_brief.brief_version,
1212
+ "schema_version": design_brief.schema_version,
1213
+ "previous_version": design_brief.previous_version,
1214
+ "payload_json": design_brief.model_dump(mode="json"),
1215
+ "created_at": now.isoformat().replace("+00:00", "Z"),
1216
+ }
1217
+ return _design_brief_from_record(_DATABASE_REPOSITORY.insert_design_brief_version(record))
1218
+
1219
+
1220
+ def list_design_brief_versions(project_id: str, owner_user_id: str) -> List[DesignBrief]:
1221
+ canonical_project_id = _canonical_project_id(project_id)
1222
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1223
+ if not normalized_owner_user_id:
1224
+ return []
1225
+ records = _DATABASE_REPOSITORY.list_design_brief_versions(
1226
+ canonical_project_id,
1227
+ normalized_owner_user_id,
1228
+ )
1229
+ return [_design_brief_from_record(record) for record in records]
1230
+
1231
+
1232
+ def get_design_brief_version(
1233
+ project_id: str,
1234
+ owner_user_id: str,
1235
+ brief_version: int,
1236
+ ) -> DesignBrief:
1237
+ canonical_project_id = _canonical_project_id(project_id)
1238
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1239
+ record = None
1240
+ if normalized_owner_user_id and brief_version >= 1:
1241
+ record = _DATABASE_REPOSITORY.get_design_brief_version(
1242
+ canonical_project_id,
1243
+ normalized_owner_user_id,
1244
+ brief_version,
1245
+ )
1246
+ if record is None:
1247
+ raise DesignBriefNotFoundError("DesignBrief version not found.")
1248
+ return _design_brief_from_record(record)
1249
+
1250
+
1251
+ def get_latest_design_brief(project_id: str, owner_user_id: str) -> DesignBrief:
1252
+ canonical_project_id = _canonical_project_id(project_id)
1253
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1254
+ record = None
1255
+ if normalized_owner_user_id:
1256
+ record = _DATABASE_REPOSITORY.get_latest_design_brief(
1257
+ canonical_project_id,
1258
+ normalized_owner_user_id,
1259
+ )
1260
+ if record is None:
1261
+ raise DesignBriefNotFoundError("DesignBrief not found.")
1262
+ return _design_brief_from_record(record)
1263
+
1264
+
1265
+ def evaluate_project_readiness(project_id: str, owner_user_id: str) -> ReadinessResult:
1266
+ try:
1267
+ brief = get_latest_design_brief(project_id, owner_user_id)
1268
+ except DesignBriefNotFoundError as exc:
1269
+ raise ReadinessError("design_brief_not_found", "DesignBrief not found.") from exc
1270
+ return evaluate_readiness(brief)
1271
+
1272
+
1273
+ def _project_build_from_record(record: Any) -> ProjectBuild:
1274
+ return ProjectBuild.model_validate({
1275
+ "build_id": record.id,
1276
+ "project_id": record.project_id,
1277
+ "owner_user_id": record.owner_user_id,
1278
+ "design_brief_id": record.design_brief_id,
1279
+ "brief_version": record.brief_version,
1280
+ "brief_snapshot": record.brief_snapshot_json,
1281
+ "mode": record.mode,
1282
+ "readiness": record.readiness_result_json,
1283
+ "introduced_assumptions": record.introduced_assumptions_json,
1284
+ "warnings": record.warnings_json,
1285
+ "transition_id": record.transition_id,
1286
+ "idempotency_key": record.idempotency_key,
1287
+ "initiated_by": record.initiated_by,
1288
+ "created_at": record.created_at,
1289
+ })
1290
+
1291
+
1292
+ def get_latest_project_build(project_id: str, owner_user_id: str) -> ProjectBuild:
1293
+ canonical_project_id = _canonical_project_id(project_id)
1294
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1295
+ record = None
1296
+ if normalized_owner_user_id:
1297
+ record = _DATABASE_REPOSITORY.get_latest_project_build(canonical_project_id, normalized_owner_user_id)
1298
+ if record is None:
1299
+ raise ReadinessError("project_build_not_found", "Project build not found.")
1300
+ return _project_build_from_record(record)
1301
+
1302
+
1303
+ def initiate_project_build(
1304
+ project_id: str,
1305
+ owner_user_id: str,
1306
+ *,
1307
+ mode: BuildMode,
1308
+ actor_id: str,
1309
+ assumptions: Optional[List[str]] = None,
1310
+ idempotency_key: Optional[str] = None,
1311
+ resolve_unanswered_questions: bool = False,
1312
+ ) -> BuildInitiationOutcome:
1313
+ canonical_project_id = _canonical_project_id(project_id)
1314
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1315
+ if not normalized_owner_user_id:
1316
+ raise ValueError("owner_user_id is required.")
1317
+ try:
1318
+ latest = get_latest_design_brief(canonical_project_id, normalized_owner_user_id)
1319
+ except DesignBriefNotFoundError as exc:
1320
+ raise ReadinessError("design_brief_not_found", "DesignBrief not found.") from exc
1321
+ readiness = evaluate_readiness(latest)
1322
+ service = ProjectBuildService(_DATABASE_REPOSITORY)
1323
+ normalized_key = str(idempotency_key or "").strip() or None
1324
+ normalized_assumptions = list(dict.fromkeys(
1325
+ normalized
1326
+ for item in assumptions or []
1327
+ if (normalized := str(item or "").strip())
1328
+ ))
1329
+
1330
+ if normalized_key and _DATABASE_REPOSITORY.get_project_build_by_idempotency(
1331
+ canonical_project_id, normalized_owner_user_id, normalized_key
1332
+ ) is not None:
1333
+ return service.initiate(
1334
+ latest,
1335
+ readiness,
1336
+ normalized_owner_user_id,
1337
+ mode=mode,
1338
+ actor_id=actor_id,
1339
+ introduced_assumptions=normalized_assumptions,
1340
+ warnings=[],
1341
+ idempotency_key=normalized_key,
1342
+ )
1343
+
1344
+ # Validate workflow ownership/state before appending an assumption-bearing brief.
1345
+ workflow = get_project_workflow(canonical_project_id, normalized_owner_user_id)
1346
+ if workflow.state not in {ProjectWorkflowState.GATHERING_CONTEXT, ProjectWorkflowState.READY_TO_BUILD}:
1347
+ raise ReadinessError(
1348
+ "build_transition_not_allowed",
1349
+ f"Build cannot start while the project workflow is {workflow.state.value}.",
1350
+ context={"project_id": canonical_project_id, "workflow_state": workflow.state.value},
1351
+ )
1352
+
1353
+ frozen_brief = latest
1354
+ initial_readiness = readiness
1355
+ warnings: List[str] = []
1356
+ if mode == BuildMode.BUILD_ANYWAY:
1357
+ if readiness.status == ReadinessStatus.BLOCKED and not resolve_unanswered_questions:
1358
+ raise ReadinessError(
1359
+ "critical_readiness_blockers",
1360
+ "Build Anyway cannot bypass critical project unknowns.",
1361
+ context=readiness.model_dump(mode="json"),
1362
+ )
1363
+ if resolve_unanswered_questions:
1364
+ normalized_assumptions = list(dict.fromkeys([
1365
+ *normalized_assumptions,
1366
+ *(
1367
+ f"Build agents will choose a safe prototype default for: {question}"
1368
+ for question in latest.unresolved_questions
1369
+ ),
1370
+ ]))
1371
+ if readiness.status != ReadinessStatus.READY and not normalized_assumptions:
1372
+ raise ReadinessError(
1373
+ "build_anyway_assumptions_required",
1374
+ "Build Anyway requires explicit assumptions for incomplete context.",
1375
+ )
1376
+ if normalized_assumptions:
1377
+ payload = latest.model_dump(exclude={
1378
+ "design_brief_id", "project_id", "brief_version", "previous_version", "created_at"
1379
+ })
1380
+ payload["assumptions"] = list(dict.fromkeys([*latest.assumptions, *normalized_assumptions]))
1381
+ if resolve_unanswered_questions:
1382
+ payload["unresolved_questions"] = []
1383
+ frozen_brief = create_design_brief_version(
1384
+ canonical_project_id,
1385
+ normalized_owner_user_id,
1386
+ DesignBriefCreate.model_validate(payload),
1387
+ )
1388
+ readiness = evaluate_readiness(frozen_brief)
1389
+ if readiness.status == ReadinessStatus.BLOCKED:
1390
+ raise ReadinessError(
1391
+ "critical_readiness_blockers",
1392
+ "Build Anyway cannot bypass critical project unknowns.",
1393
+ context=readiness.model_dump(mode="json"),
1394
+ )
1395
+ warnings = [
1396
+ f"Build Anyway bypassed non-critical blocker {blocker.code}: {blocker.message}"
1397
+ for blocker in initial_readiness.unresolved_blockers
1398
+ if not blocker.critical
1399
+ ]
1400
+ if resolve_unanswered_questions:
1401
+ warnings.extend(
1402
+ f"Conversational build delegated blocker {blocker.code} to the build agents: {blocker.message}"
1403
+ for blocker in initial_readiness.unresolved_blockers
1404
+ if blocker.critical
1405
+ )
1406
+ warnings.extend(f"Execution relies on user assumption: {assumption}" for assumption in normalized_assumptions)
1407
+
1408
+ return service.initiate(
1409
+ frozen_brief,
1410
+ readiness,
1411
+ normalized_owner_user_id,
1412
+ mode=mode,
1413
+ actor_id=actor_id,
1414
+ introduced_assumptions=normalized_assumptions,
1415
+ warnings=warnings,
1416
+ idempotency_key=normalized_key,
1417
+ )
1418
+
1419
+
1420
+ def initialize_project_workflow(
1421
+ project_id: str,
1422
+ owner_user_id: str,
1423
+ *,
1424
+ actor_type: WorkflowActorType = WorkflowActorType.SYSTEM,
1425
+ actor_id: Optional[str] = None,
1426
+ reason: str = "Project workflow initialized.",
1427
+ chat_id: Optional[str] = None,
1428
+ title: Optional[str] = None,
1429
+ prompt: Optional[str] = None,
1430
+ ) -> WorkflowTransitionOutcome:
1431
+ outcome = ProjectWorkflowService(_DATABASE_REPOSITORY).initialize(
1432
+ project_id,
1433
+ owner_user_id,
1434
+ actor_type=actor_type,
1435
+ actor_id=actor_id,
1436
+ reason=reason,
1437
+ )
1438
+ if chat_id or title or prompt:
1439
+ ensure_project_identity(
1440
+ project_id,
1441
+ owner_user_id,
1442
+ title=title or "Untitled Forma Project",
1443
+ prompt=prompt or "",
1444
+ chat_id=chat_id,
1445
+ )
1446
+ return outcome
1447
+
1448
+
1449
+ def get_project_workflow(project_id: str, owner_user_id: str) -> ProjectWorkflow:
1450
+ return ProjectWorkflowService(_DATABASE_REPOSITORY).get(project_id, owner_user_id)
1451
+
1452
+
1453
+ def get_latest_project_revision(project_id: str, owner_user_id: str) -> ProjectRevision:
1454
+ """Read the latest immutable state through the canonical project boundary."""
1455
+
1456
+ return ProjectStateService(_DATABASE_REPOSITORY).get_latest(project_id, owner_user_id)
1457
+
1458
+
1459
+ def get_project_revision_by_source_job(
1460
+ project_id: str,
1461
+ owner_user_id: str,
1462
+ source_job_id: str,
1463
+ ) -> Optional[ProjectRevision]:
1464
+ """Return an existing revision for an idempotent worker/source delivery."""
1465
+ return ProjectStateService(_DATABASE_REPOSITORY).get_by_source_job(project_id, owner_user_id, source_job_id)
1466
+
1467
+
1468
+ def list_project_revisions(project_id: str, owner_user_id: str, *, limit: int = 21, before: int | None = None) -> List[ProjectRevision]:
1469
+ """Return a bounded page of the owner's saved snapshots."""
1470
+ return ProjectStateService(_DATABASE_REPOSITORY).list_revisions(project_id, owner_user_id, limit=limit, before=before)
1471
+
1472
+
1473
+ def get_project_revision_by_id(project_id: str, owner_user_id: str, revision_id: str) -> ProjectRevision:
1474
+ """Resolve the immutable revision referenced by a chat result or history entry."""
1475
+ return ProjectStateService(_DATABASE_REPOSITORY).get_revision_by_id(project_id, owner_user_id, revision_id)
1476
+
1477
+
1478
+ def list_latest_project_revisions(owner_user_id: str) -> List[ProjectRevision]:
1479
+ """List each owned project's latest immutable canonical revision."""
1480
+
1481
+ owner = _normalize_user_id(owner_user_id)
1482
+ if not owner:
1483
+ return []
1484
+ revisions: List[ProjectRevision] = []
1485
+ for record in _DATABASE_REPOSITORY.list_latest_project_revisions(owner):
1486
+ payload = getattr(record, "payload_json", None)
1487
+ if not isinstance(payload, dict):
1488
+ logger.warning(
1489
+ "Skipping project revision with invalid payload while listing owner projects: project_id=%s",
1490
+ getattr(record, "project_id", "unknown"),
1491
+ )
1492
+ continue
1493
+ try:
1494
+ revisions.append(ProjectRevision.model_validate(payload))
1495
+ except Exception:
1496
+ logger.exception(
1497
+ "Skipping invalid canonical project revision while listing owner projects: project_id=%s",
1498
+ getattr(record, "project_id", "unknown"),
1499
+ )
1500
+ return revisions
1501
+
1502
+
1503
+ def append_project_revision(
1504
+ project_id: str,
1505
+ owner_user_id: str,
1506
+ state: Any,
1507
+ *,
1508
+ source_job_id: str,
1509
+ ) -> ProjectRevision:
1510
+ """Persist an iteration as the next immutable canonical project revision."""
1511
+
1512
+ from forma_core.workers.generation import build_generation_draft
1513
+ from forma_core.workspaces.projects.models import HardwareIntermediateRepresentation
1514
+
1515
+ service = ProjectStateService(_DATABASE_REPOSITORY)
1516
+ try:
1517
+ parent = service.get_latest(project_id, owner_user_id)
1518
+ except ProjectStateError as exc:
1519
+ if exc.code != "project_revision_not_found":
1520
+ raise
1521
+
1522
+ # Legacy generated_projects rows have no immutable history. Migrate the
1523
+ # current projection once before appending the requested iteration.
1524
+ legacy = get_generated_project(project_id, include_deleted=True)
1525
+ if legacy is None or getattr(legacy, "status", "active") != "active":
1526
+ raise
1527
+ if str(getattr(legacy, "owner_user_id", "") or "").strip() != str(owner_user_id or "").strip():
1528
+ raise ProjectStateError("project_revision_not_found", "Project revision not found.")
1529
+
1530
+ project_uuid = _canonical_project_id(project_id)
1531
+ try:
1532
+ brief = get_latest_design_brief(project_id, owner_user_id)
1533
+ except DesignBriefNotFoundError:
1534
+ prompt = str(getattr(legacy, "prompt", "") or "").strip()
1535
+ title = str(getattr(legacy, "title", "") or "").strip()
1536
+ brief = create_design_brief_version(
1537
+ project_uuid,
1538
+ owner_user_id,
1539
+ DesignBriefCreate(
1540
+ schema_version="1.0",
1541
+ conversation_id=str(getattr(legacy, "chat_id", "") or "").strip()
1542
+ or f"project-{project_uuid}",
1543
+ intent=prompt or title or "Update an existing hardware project.",
1544
+ summary=prompt or title or "Update an existing hardware project.",
1545
+ ),
1546
+ )
1547
+
1548
+ baseline = HardwareIntermediateRepresentation.model_validate(getattr(legacy, "hardware_ir", {}))
1549
+ baseline.assembly_metadata = {
1550
+ **(baseline.assembly_metadata or {}),
1551
+ "project_id": str(project_uuid),
1552
+ "revision": 1,
1553
+ }
1554
+ baseline_draft = build_generation_draft(brief, baseline)
1555
+ try:
1556
+ service.create_initial_revision(
1557
+ baseline_draft,
1558
+ project_id=project_uuid,
1559
+ owner_user_id=owner_user_id,
1560
+ design_brief_id=brief.design_brief_id,
1561
+ design_brief_version=brief.brief_version,
1562
+ source_job_id=f"legacy-migration-{project_uuid}",
1563
+ )
1564
+ except ProjectStateError as migration_exc:
1565
+ if migration_exc.code != "initial_project_revision_exists":
1566
+ raise
1567
+ parent = service.get_latest(project_id, owner_user_id)
1568
+
1569
+ brief = service.get_frozen_design_brief(
1570
+ project_id,
1571
+ owner_user_id,
1572
+ parent.design_brief_id,
1573
+ parent.design_brief_version,
1574
+ )
1575
+ draft = build_generation_draft(brief, HardwareIntermediateRepresentation.model_validate(state))
1576
+ revision = service.create_revision(
1577
+ draft,
1578
+ project_id=project_id,
1579
+ owner_user_id=owner_user_id,
1580
+ source_job_id=source_job_id,
1581
+ ).revision
1582
+ invalidate_project_lists()
1583
+ return revision
1584
+
1585
+
1586
+ def create_project_generation_plan(
1587
+ build: ProjectBuild,
1588
+ owner_user_id: str,
1589
+ *,
1590
+ provider_name: Optional[str] = None,
1591
+ model_name: Optional[str] = None,
1592
+ generation_mode: str = "regular",
1593
+ ):
1594
+ """Create or replay the durable initial-generation plan for one frozen build."""
1595
+
1596
+ from forma_core.workers import (
1597
+ GENERATION_CAPABILITY_ID,
1598
+ GENERATION_INPUT_VERSION,
1599
+ GENERATION_WORKER_ID,
1600
+ WORKER_CONTRACT_VERSION,
1601
+ GenerationWorker,
1602
+ EngineeringGenerationEngine,
1603
+ WorkerOrchestrator,
1604
+ WorkerRequest,
1605
+ )
1606
+ from forma_core.workspaces.projects.generation_mode import GenerationMode
1607
+
1608
+ try:
1609
+ normalized_generation_mode = GenerationMode(str(generation_mode or "regular").strip().lower())
1610
+ except ValueError as exc:
1611
+ raise ValueError("generation_mode must be regular or progressive.") from exc
1612
+
1613
+ owner = _normalize_user_id(owner_user_id)
1614
+ if not owner or owner != build.owner_user_id:
1615
+ raise ValueError("The build owner must match owner_user_id.")
1616
+ plan_id = f"build-plan-{build.build_id}"
1617
+ existing = _DATABASE_REPOSITORY.get_worker_execution_plan(plan_id, owner)
1618
+ engine = EngineeringGenerationEngine(provider_name=provider_name, model_name=model_name)
1619
+ worker = GenerationWorker(ProjectStateService(_DATABASE_REPOSITORY), engine)
1620
+ orchestrator = WorkerOrchestrator(
1621
+ _DATABASE_REPOSITORY,
1622
+ [worker],
1623
+ workflow_service=ProjectWorkflowService(_DATABASE_REPOSITORY),
1624
+ )
1625
+ if existing is not None:
1626
+ return orchestrator.get_plan(plan_id, owner)
1627
+
1628
+ job_id = f"generation-{build.build_id}"
1629
+ request = WorkerRequest(
1630
+ contract_version=WORKER_CONTRACT_VERSION,
1631
+ project_id=build.project_id,
1632
+ project_revision=1,
1633
+ design_brief_id=build.design_brief_id,
1634
+ design_brief_version=build.brief_version,
1635
+ job_id=job_id,
1636
+ correlation_id=f"build-{build.build_id}",
1637
+ worker_id=GENERATION_WORKER_ID,
1638
+ capability_id=GENERATION_CAPABILITY_ID,
1639
+ input_contract_version=GENERATION_INPUT_VERSION,
1640
+ payload={"design_brief": build.brief_snapshot.model_dump(mode="json")},
1641
+ metadata={
1642
+ "build_id": str(build.build_id),
1643
+ "cad_required": False,
1644
+ "generation_mode": normalized_generation_mode.value,
1645
+ **(
1646
+ {"visual_approval_policy": "require_approval"}
1647
+ if normalized_generation_mode == GenerationMode.PROGRESSIVE
1648
+ else {}
1649
+ ),
1650
+ },
1651
+ )
1652
+ return orchestrator.create_plan([request], owner, max_concurrency=1, plan_id=plan_id)
1653
+
1654
+
1655
+ def get_project_generation_plan(plan_id: str, owner_user_id: str):
1656
+ """Return a persisted worker plan without exposing the backing repository."""
1657
+
1658
+ from forma_core.workers import GenerationWorker, WorkerOrchestrator
1659
+
1660
+ owner = _normalize_user_id(owner_user_id)
1661
+ orchestrator = WorkerOrchestrator(
1662
+ _DATABASE_REPOSITORY,
1663
+ [GenerationWorker(ProjectStateService(_DATABASE_REPOSITORY))],
1664
+ workflow_service=ProjectWorkflowService(_DATABASE_REPOSITORY),
1665
+ )
1666
+ return orchestrator.get_plan(plan_id, owner)
1667
+
1668
+
1669
+ def list_project_generation_jobs(
1670
+ *,
1671
+ status: Optional[str] = None,
1672
+ limit: int = 200,
1673
+ ) -> List[Dict[str, Any]]:
1674
+ """Project durable generation-plan tasks in the admin job record shape."""
1675
+
1676
+ from forma_core.workers import OrchestrationTaskStatus, WorkerExecutionPlan
1677
+
1678
+ normalized_status = str(status or "").strip().lower()
1679
+ records = _DATABASE_REPOSITORY.list_worker_execution_plans(limit=limit)
1680
+ jobs: List[Dict[str, Any]] = []
1681
+ for record in records:
1682
+ state = getattr(record, "state_json", None)
1683
+ if not isinstance(state, dict):
1684
+ logger.warning("Skipping worker execution plan with invalid state_json.")
1685
+ continue
1686
+ try:
1687
+ plan = WorkerExecutionPlan.model_validate(state)
1688
+ except Exception:
1689
+ logger.exception("Skipping invalid worker execution plan while listing admin jobs.")
1690
+ continue
1691
+
1692
+ for job_id, task in plan.jobs.items():
1693
+ job_status = task.status.value
1694
+ if task.status == OrchestrationTaskStatus.BLOCKED:
1695
+ job_status = "failed"
1696
+ if normalized_status and normalized_status != "all" and normalized_status != job_status:
1697
+ continue
1698
+
1699
+ brief = task.request.payload.get("design_brief")
1700
+ brief = brief if isinstance(brief, dict) else {}
1701
+ progress_events = [
1702
+ event
1703
+ for progress in task.progress
1704
+ for event in [progress.metadata.get("pipeline_event")]
1705
+ if isinstance(event, dict)
1706
+ ]
1707
+ error = task.error.message if task.error is not None else None
1708
+ completed_at = task.completed_at or (task.result.completed_at if task.result else None)
1709
+ result_output = task.result.output if task.result is not None else {}
1710
+ project_revision = result_output.get("project_revision")
1711
+ project_revision = project_revision if isinstance(project_revision, dict) else {}
1712
+ project_state = project_revision.get("state")
1713
+ project_state = project_state if isinstance(project_state, dict) else {}
1714
+ assembly_metadata = project_state.get("assembly_metadata")
1715
+ assembly_metadata = assembly_metadata if isinstance(assembly_metadata, dict) else {}
1716
+ image_status = assembly_metadata.get("image_output_status")
1717
+ image_error = assembly_metadata.get("image_output_error") or assembly_metadata.get("product_image_error")
1718
+ jobs.append(
1719
+ {
1720
+ "job_id": job_id,
1721
+ "message_id": plan.plan_id,
1722
+ "correlation_id": plan.correlation_id,
1723
+ "action": "forma.generate_project",
1724
+ "sender": "conversation",
1725
+ "recipient": task.request.worker_id,
1726
+ "status": job_status,
1727
+ "server_owned": True,
1728
+ "created_at": plan.created_at.isoformat(),
1729
+ "updated_at": plan.updated_at.isoformat(),
1730
+ "started_at": task.started_at.isoformat() if task.started_at else None,
1731
+ "completed_at": completed_at.isoformat() if completed_at else None,
1732
+ "payload": {
1733
+ "owner_user_id": plan.owner_user_id,
1734
+ "project_id": plan.project_id,
1735
+ "prompt": brief.get("intent") or brief.get("summary"),
1736
+ "design_brief_id": str(task.request.design_brief_id),
1737
+ "design_brief_version": task.request.design_brief_version,
1738
+ },
1739
+ "result_summary": {
1740
+ "project_id": plan.project_id,
1741
+ "title": brief.get("summary") or brief.get("intent"),
1742
+ "workflow": "default",
1743
+ "image_output_status": image_status,
1744
+ "image_output_failed": bool(
1745
+ assembly_metadata.get("image_output_failed") or image_status == "failed"
1746
+ ),
1747
+ "image_output_error": image_error,
1748
+ "image_output_error_type": assembly_metadata.get("image_output_error_type"),
1749
+ "image_output_reason": assembly_metadata.get("image_output_reason"),
1750
+ "image_output_debug": assembly_metadata.get("image_output_debug"),
1751
+ "image_output_provider": assembly_metadata.get("image_output_provider"),
1752
+ "image_output_model": assembly_metadata.get("image_output_model"),
1753
+ "operation_statuses": assembly_metadata.get("operation_statuses") or [],
1754
+ "operation_summary": assembly_metadata.get("operation_summary"),
1755
+ },
1756
+ "source_usage": {"workflow": "default", "source_labels": ["Conversation"]},
1757
+ "progress_events": progress_events,
1758
+ "error": error,
1759
+ "error_debug": task.error.model_dump(mode="json") if task.error is not None else None,
1760
+ }
1761
+ )
1762
+ if len(jobs) >= limit:
1763
+ return jobs
1764
+ return jobs
1765
+
1766
+
1767
+ async def execute_project_generation_plan(
1768
+ plan_id: str,
1769
+ owner_user_id: str,
1770
+ *,
1771
+ provider_name: Optional[str] = None,
1772
+ model_name: Optional[str] = None,
1773
+ cancellation_check: Optional[Callable[[], bool]] = None,
1774
+ ):
1775
+ """Execute or resume a persisted project-generation plan."""
1776
+
1777
+ from forma_core.workers import GenerationWorker, EngineeringGenerationEngine, WorkerOrchestrator
1778
+
1779
+ owner = _normalize_user_id(owner_user_id)
1780
+ worker = GenerationWorker(
1781
+ ProjectStateService(_DATABASE_REPOSITORY),
1782
+ EngineeringGenerationEngine(provider_name=provider_name, model_name=model_name),
1783
+ project_publisher=publish_project_revision,
1784
+ )
1785
+ orchestrator = WorkerOrchestrator(
1786
+ _DATABASE_REPOSITORY,
1787
+ [worker],
1788
+ workflow_service=ProjectWorkflowService(_DATABASE_REPOSITORY),
1789
+ cancellation_check=cancellation_check,
1790
+ )
1791
+ plan = await orchestrator.execute(plan_id, owner)
1792
+ invalidate_project_lists()
1793
+ return plan
1794
+
1795
+
1796
+ async def cancel_project_generation_plan(plan_id: str, owner_user_id: str):
1797
+ """Persist cancellation for a project-generation plan and its active worker."""
1798
+
1799
+ from forma_core.workers import GenerationWorker, WorkerOrchestrator
1800
+
1801
+ owner = _normalize_user_id(owner_user_id)
1802
+ orchestrator = WorkerOrchestrator(
1803
+ _DATABASE_REPOSITORY,
1804
+ [GenerationWorker(ProjectStateService(_DATABASE_REPOSITORY))],
1805
+ workflow_service=ProjectWorkflowService(_DATABASE_REPOSITORY),
1806
+ )
1807
+ return await orchestrator.cancel(plan_id, owner)
1808
+
1809
+
1810
+ async def reset_project_generation_plan(plan_id: str, owner_user_id: str):
1811
+ """Reset failed generation work while preserving the frozen project brief."""
1812
+
1813
+ from forma_core.workers import GenerationWorker, WorkerOrchestrator
1814
+
1815
+ owner = _normalize_user_id(owner_user_id)
1816
+ orchestrator = WorkerOrchestrator(
1817
+ _DATABASE_REPOSITORY,
1818
+ [GenerationWorker(ProjectStateService(_DATABASE_REPOSITORY))],
1819
+ workflow_service=ProjectWorkflowService(_DATABASE_REPOSITORY),
1820
+ )
1821
+ return await orchestrator.reset(plan_id, owner)
1822
+
1823
+
1824
+ def list_project_workflow_transitions(
1825
+ project_id: str,
1826
+ owner_user_id: str,
1827
+ ) -> List[ProjectWorkflowTransition]:
1828
+ return ProjectWorkflowService(_DATABASE_REPOSITORY).history(project_id, owner_user_id)
1829
+
1830
+
1831
+ def transition_project_workflow(
1832
+ project_id: str,
1833
+ owner_user_id: str,
1834
+ to_state: ProjectWorkflowState,
1835
+ *,
1836
+ actor_type: WorkflowActorType,
1837
+ actor_id: Optional[str],
1838
+ reason: str,
1839
+ idempotency_key: Optional[str] = None,
1840
+ ) -> WorkflowTransitionOutcome:
1841
+ return ProjectWorkflowService(_DATABASE_REPOSITORY).transition(
1842
+ project_id,
1843
+ owner_user_id,
1844
+ to_state,
1845
+ actor_type=actor_type,
1846
+ actor_id=actor_id,
1847
+ reason=reason,
1848
+ idempotency_key=idempotency_key,
1849
+ )
1850
+
1851
+
1852
+ def ensure_project_action_allowed(
1853
+ project_id: str,
1854
+ owner_user_id: str,
1855
+ action: str,
1856
+ *,
1857
+ require_workflow: bool = False,
1858
+ ) -> None:
1859
+ """Apply project workflow execution policy without coupling callers to persistence."""
1860
+
1861
+ try:
1862
+ workflow = ProjectWorkflowService(_DATABASE_REPOSITORY).get(project_id, owner_user_id)
1863
+ except WorkflowStateError:
1864
+ if not require_workflow:
1865
+ return
1866
+ raise
1867
+ ensure_action_allowed(workflow, action)
1868
+
1869
+
1870
+ def list_due_project_purges(before: str, limit: int = 25) -> List[Any]:
1871
+ return _DATABASE_REPOSITORY.list_due_project_purges(before, max(1, min(limit, 100)))
1872
+
1873
+
1874
+ def update_project_deletion_state(
1875
+ project_id: str,
1876
+ *,
1877
+ owner_user_id: Optional[str],
1878
+ allowed_statuses: List[str],
1879
+ updates: Dict[str, Any],
1880
+ expected_purge_started_at: Optional[str] = None,
1881
+ ) -> Optional[Any]:
1882
+ project_id = _canonical_project_id(project_id)
1883
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1884
+ updated = _DATABASE_REPOSITORY.update_project_deletion_state(
1885
+ project_id,
1886
+ normalized_owner_user_id,
1887
+ allowed_statuses,
1888
+ updates,
1889
+ expected_purge_started_at,
1890
+ )
1891
+ if updated:
1892
+ invalidate_project_lists()
1893
+ return updated
1894
+
1895
+
1896
+ def hard_purge_generated_project(project_id: str, owner_user_id: Optional[str] = None) -> bool:
1897
+ project_id = _canonical_project_id(project_id)
1898
+ purged = _DATABASE_REPOSITORY.hard_purge_project(project_id, _normalize_user_id(owner_user_id))
1899
+ if purged:
1900
+ invalidate_project_lists()
1901
+ return purged
1902
+
1903
+
1904
+ def update_generated_project_hardware_ir(
1905
+ project_id: str,
1906
+ hardware_ir: Dict[str, Any],
1907
+ owner_user_id: Optional[str] = None,
1908
+ ) -> bool:
1909
+ project_id = _canonical_project_id(project_id)
1910
+ hardware_ir = _hardware_ir_with_project_id(project_id, hardware_ir)
1911
+ metadata = hardware_ir.get("assembly_metadata") if isinstance(hardware_ir.get("assembly_metadata"), dict) else {}
1912
+ chat_id = _normalize_chat_id(metadata.get("chat_id"))
1913
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1914
+ updated = _DATABASE_REPOSITORY.update_generated_project_hardware_ir(
1915
+ project_id,
1916
+ hardware_ir,
1917
+ chat_id,
1918
+ normalized_owner_user_id,
1919
+ )
1920
+ if updated:
1921
+ invalidate_project_lists()
1922
+ return updated
1923
+
1924
+
1925
+ def refresh_legacy_project_projection(
1926
+ project_id: str,
1927
+ hardware_ir: Dict[str, Any],
1928
+ *,
1929
+ owner_user_id: Optional[str] = None,
1930
+ ) -> bool:
1931
+ """Refresh the retained legacy projection during compatibility reads."""
1932
+
1933
+ return update_generated_project_hardware_ir(
1934
+ project_id,
1935
+ hardware_ir,
1936
+ owner_user_id=owner_user_id,
1937
+ )
1938
+
1939
+
1940
+ def claim_unowned_generated_project(
1941
+ project_id: str,
1942
+ hardware_ir: Dict[str, Any],
1943
+ owner_user_id: str,
1944
+ ) -> bool:
1945
+ project_id = _canonical_project_id(project_id)
1946
+ hardware_ir = _hardware_ir_with_project_id(project_id, hardware_ir)
1947
+ metadata = hardware_ir.get("assembly_metadata") if isinstance(hardware_ir.get("assembly_metadata"), dict) else {}
1948
+ chat_id = _normalize_chat_id(metadata.get("chat_id"))
1949
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
1950
+ if not normalized_owner_user_id:
1951
+ return False
1952
+ identity_claimed = False
1953
+ identity = _DATABASE_REPOSITORY.get_project_identity(project_id)
1954
+ if identity is not None and not _normalize_user_id(identity.get("owner_user_id")):
1955
+ if identity.get("status", "active") != "active":
1956
+ return False
1957
+ identity_record = dict(identity)
1958
+ identity_record["owner_user_id"] = normalized_owner_user_id
1959
+ if chat_id:
1960
+ identity_record["chat_id"] = chat_id
1961
+ identity_record["updated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
1962
+ _DATABASE_REPOSITORY.upsert_project_identity(identity_record)
1963
+ invalidate_project_lists()
1964
+ identity_claimed = True
1965
+ claimed = _DATABASE_REPOSITORY.claim_unowned_generated_project(
1966
+ project_id,
1967
+ hardware_ir,
1968
+ chat_id,
1969
+ normalized_owner_user_id,
1970
+ )
1971
+ if claimed or identity_claimed:
1972
+ invalidate_project_lists()
1973
+ return claimed or identity_claimed
1974
+
1975
+
1976
+ def _hardware_ir_with_overview_title(hardware_ir: Any, title: str) -> Optional[Dict[str, Any]]:
1977
+ if hardware_ir is None:
1978
+ return None
1979
+ if hasattr(hardware_ir, "model_dump"):
1980
+ payload = hardware_ir.model_dump(mode="json")
1981
+ elif isinstance(hardware_ir, dict):
1982
+ payload = dict(hardware_ir)
1983
+ else:
1984
+ return None
1985
+ overview = payload.get("overview")
1986
+ next_overview = dict(overview) if isinstance(overview, dict) else {}
1987
+ next_overview["title"] = title
1988
+ payload["overview"] = next_overview
1989
+ return payload
1990
+
1991
+
1992
+ def update_generated_project_metadata(
1993
+ project_id: str,
1994
+ *,
1995
+ owner_user_id: str,
1996
+ title: Optional[str] = None,
1997
+ prompt: Optional[str] = None,
1998
+ visibility: Optional[str] = None,
1999
+ ) -> bool:
2000
+ project_id = _canonical_project_id(project_id)
2001
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2002
+ if not normalized_owner_user_id:
2003
+ return False
2004
+ updates: Dict[str, Any] = {}
2005
+ if title is not None:
2006
+ next_title = title.strip() or "Untitled Forma Project"
2007
+ updates["title"] = next_title
2008
+ project = get_generated_project(project_id)
2009
+ hardware_ir = _hardware_ir_with_overview_title(
2010
+ None if project is None else getattr(project, "hardware_ir", None),
2011
+ next_title,
2012
+ )
2013
+ if hardware_ir is not None:
2014
+ updates["hardware_ir"] = hardware_ir
2015
+ if prompt is not None:
2016
+ updates["prompt"] = prompt.strip()
2017
+ if visibility is not None:
2018
+ updates["visibility"] = _normalize_visibility(visibility)
2019
+ if not updates:
2020
+ return True
2021
+ updated = _DATABASE_REPOSITORY.update_generated_project_metadata(
2022
+ project_id,
2023
+ normalized_owner_user_id,
2024
+ updates,
2025
+ )
2026
+ if updated:
2027
+ invalidate_project_lists()
2028
+ return updated
2029
+
2030
+
2031
+ def delete_generated_project(project_id: str, owner_user_id: str) -> bool:
2032
+ project_id = _canonical_project_id(project_id)
2033
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2034
+ if not normalized_owner_user_id:
2035
+ return False
2036
+ deleted = _DATABASE_REPOSITORY.delete_generated_project(project_id, normalized_owner_user_id)
2037
+ if deleted:
2038
+ invalidate_project_lists()
2039
+ return deleted
2040
+
2041
+
2042
+ def get_project_contribution_consent(project_id: str, user_id: str) -> Optional[Any]:
2043
+ return _DATABASE_REPOSITORY.get_project_contribution_consent(
2044
+ _canonical_project_id(project_id),
2045
+ _normalize_user_id(user_id) or "",
2046
+ )
2047
+
2048
+
2049
+ def upsert_project_contribution_consent(record: Dict[str, Any]) -> Any:
2050
+ normalized = dict(record)
2051
+ normalized["project_id"] = _canonical_project_id(normalized["project_id"])
2052
+ normalized["user_id"] = _normalize_user_id(normalized.get("user_id")) or ""
2053
+ if not normalized["user_id"]:
2054
+ raise ValueError("Contribution consent requires a user id.")
2055
+ return _DATABASE_REPOSITORY.upsert_project_contribution_consent(normalized)
2056
+
2057
+
2058
+ def withdraw_project_contribution_consent(project_id: str, user_id: str, withdrawn_at: str) -> Optional[Any]:
2059
+ return _DATABASE_REPOSITORY.withdraw_project_contribution_consent(
2060
+ _canonical_project_id(project_id),
2061
+ _normalize_user_id(user_id) or "",
2062
+ withdrawn_at,
2063
+ )
2064
+
2065
+
2066
+ def anonymize_project_contribution_consent(project_id: str, user_id: str, anonymized_at: str) -> bool:
2067
+ return _DATABASE_REPOSITORY.anonymize_project_contribution_consent(
2068
+ _canonical_project_id(project_id),
2069
+ _normalize_user_id(user_id) or "",
2070
+ str(uuid.uuid4()),
2071
+ f"anonymous-{uuid.uuid4()}",
2072
+ anonymized_at,
2073
+ )
2074
+
2075
+
2076
+ def upsert_project_contribution_snapshot(record: Dict[str, Any]) -> Any:
2077
+ normalized = dict(record)
2078
+ normalized["source_project_id"] = _canonical_project_id(normalized["source_project_id"])
2079
+ return _DATABASE_REPOSITORY.upsert_project_contribution_snapshot(normalized)
2080
+
2081
+
2082
+ def anonymize_project_contribution_snapshot(consent_record_id: str, anonymized_at: str) -> bool:
2083
+ return _DATABASE_REPOSITORY.anonymize_project_contribution_snapshot(
2084
+ consent_record_id,
2085
+ str(uuid.uuid4()),
2086
+ str(uuid.uuid4()),
2087
+ anonymized_at,
2088
+ )
2089
+
2090
+
2091
+ def purge_project_contribution_snapshots(consent_record_id: str, purged_at: str) -> int:
2092
+ return _DATABASE_REPOSITORY.purge_project_contribution_snapshots(consent_record_id, purged_at)
2093
+
2094
+
2095
+ def add_project_deletion_audit(record: Dict[str, Any]) -> Any:
2096
+ normalized = dict(record)
2097
+ normalized["project_id"] = _canonical_project_id(normalized["project_id"])
2098
+ normalized["acting_user_id"] = _normalize_user_id(normalized.get("acting_user_id"))
2099
+ return _DATABASE_REPOSITORY.add_project_deletion_audit(normalized)
2100
+
2101
+
2102
+ def get_latest_project_deletion_audit(project_id: str) -> Optional[Any]:
2103
+ return _DATABASE_REPOSITORY.get_latest_project_deletion_audit(_canonical_project_id(project_id))
2104
+
2105
+
2106
+ def list_project_deletion_audits(limit: int = 100) -> List[Any]:
2107
+ return _DATABASE_REPOSITORY.list_project_deletion_audits(max(1, min(limit, 500)))
2108
+
2109
+
2110
+ def upsert_project_chat(
2111
+ *,
2112
+ chat_id: str,
2113
+ owner_user_id: str,
2114
+ title: str,
2115
+ messages: Optional[List[Dict[str, Any]]] = None,
2116
+ created_at: str,
2117
+ updated_at: str,
2118
+ ) -> Any:
2119
+ normalized_chat_id = _normalize_chat_id(chat_id)
2120
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2121
+ if not normalized_chat_id or not normalized_owner_user_id:
2122
+ raise ValueError("chat_id and owner_user_id are required.")
2123
+ for message in messages or []:
2124
+ linked_project_id = None
2125
+ if isinstance(message, dict):
2126
+ linked_project_id = message.get("projectId") or message.get("project_id")
2127
+ if not linked_project_id:
2128
+ continue
2129
+ try:
2130
+ linked_project = get_generated_project(str(linked_project_id), include_deleted=True)
2131
+ except ValueError:
2132
+ linked_project = None
2133
+ if linked_project is not None:
2134
+ linked_project_is_active = getattr(linked_project, "status", "active") == "active"
2135
+ else:
2136
+ try:
2137
+ get_latest_project_revision(str(linked_project_id), normalized_owner_user_id)
2138
+ linked_project_is_active = True
2139
+ except (ProjectStateError, ValueError):
2140
+ linked_project_is_active = False
2141
+ if not linked_project_is_active:
2142
+ raise ValueError("Cannot write chat data for a deleted or missing project.")
2143
+ record = {
2144
+ "chat_id": normalized_chat_id,
2145
+ "owner_user_id": normalized_owner_user_id,
2146
+ "title": title.strip() or "Untitled chat",
2147
+ "messages": messages or [],
2148
+ "created_at": created_at,
2149
+ "updated_at": updated_at,
2150
+ }
2151
+ return _DATABASE_REPOSITORY.upsert_project_chat(record)
2152
+
2153
+
2154
+ def list_project_chats(owner_user_id: str) -> List[Any]:
2155
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2156
+ if not normalized_owner_user_id:
2157
+ return []
2158
+ return _DATABASE_REPOSITORY.list_project_chats(normalized_owner_user_id)
2159
+
2160
+
2161
+ def get_project_chat(chat_id: str, owner_user_id: str) -> Optional[Any]:
2162
+ normalized_chat_id = _normalize_chat_id(chat_id)
2163
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2164
+ if not normalized_chat_id or not normalized_owner_user_id:
2165
+ return None
2166
+ return _DATABASE_REPOSITORY.get_project_chat(normalized_chat_id, normalized_owner_user_id)
2167
+
2168
+
2169
+ def delete_project_chat(chat_id: str, owner_user_id: str) -> bool:
2170
+ normalized_chat_id = _normalize_chat_id(chat_id)
2171
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2172
+ if not normalized_chat_id or not normalized_owner_user_id:
2173
+ return False
2174
+ return _DATABASE_REPOSITORY.delete_project_chat(normalized_chat_id, normalized_owner_user_id)
2175
+
2176
+
2177
+ def save_alpha_signup(
2178
+ *,
2179
+ name: str,
2180
+ email: str,
2181
+ organization: Optional[str],
2182
+ additional_info: Optional[str],
2183
+ source: str,
2184
+ metadata: Optional[Dict[str, Any]],
2185
+ created_at: str,
2186
+ ) -> Any:
2187
+ record = {
2188
+ "name": name,
2189
+ "email": email.lower(),
2190
+ "organization": organization,
2191
+ "additional_info": additional_info,
2192
+ "source": source,
2193
+ "metadata_json": metadata or {},
2194
+ "created_at": created_at,
2195
+ }
2196
+ return _DATABASE_REPOSITORY.save_alpha_signup(record)
2197
+
2198
+
2199
+ def project_engagement_for_ids(
2200
+ project_ids: List[str],
2201
+ owner_user_id: Optional[str] = None,
2202
+ ) -> Dict[str, Dict[str, Any]]:
2203
+ normalized_ids: List[str] = []
2204
+ seen: set[str] = set()
2205
+ for value in project_ids:
2206
+ project_id = str(value or "").strip()
2207
+ if not project_id or project_id in seen:
2208
+ continue
2209
+ seen.add(project_id)
2210
+ normalized_ids.append(project_id)
2211
+ save_counts = _DATABASE_REPOSITORY.count_project_saves(normalized_ids)
2212
+ remix_counts = _DATABASE_REPOSITORY.count_project_remixes(normalized_ids)
2213
+ saved_ids = set()
2214
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2215
+ if normalized_owner_user_id:
2216
+ saved_ids = set(_DATABASE_REPOSITORY.list_saved_project_ids(normalized_owner_user_id, normalized_ids))
2217
+ return {
2218
+ project_id: {
2219
+ "save_count": int(save_counts.get(project_id, 0)),
2220
+ "remix_count": int(remix_counts.get(project_id, 0)),
2221
+ "saved": project_id in saved_ids,
2222
+ }
2223
+ for project_id in normalized_ids
2224
+ }
2225
+
2226
+
2227
+ def _project_engagement_timestamp() -> str:
2228
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
2229
+
2230
+
2231
+ def save_project_for_user(project_id: str, owner_user_id: str) -> Dict[str, Any]:
2232
+ normalized_project_id = str(project_id or "").strip()
2233
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2234
+ if not normalized_project_id or not normalized_owner_user_id:
2235
+ raise ValueError("project_id and owner_user_id are required.")
2236
+ created = _DATABASE_REPOSITORY.insert_project_save(
2237
+ {
2238
+ "project_id": normalized_project_id,
2239
+ "owner_user_id": normalized_owner_user_id,
2240
+ "created_at": _project_engagement_timestamp(),
2241
+ }
2242
+ )
2243
+ if created:
2244
+ invalidate_project_lists()
2245
+ engagement = project_engagement_for_ids([normalized_project_id], normalized_owner_user_id).get(
2246
+ normalized_project_id,
2247
+ {"save_count": 0, "remix_count": 0, "saved": True},
2248
+ )
2249
+ return {
2250
+ "saved": True,
2251
+ "save_count": int(engagement.get("save_count") or 0),
2252
+ "remix_count": int(engagement.get("remix_count") or 0),
2253
+ }
2254
+
2255
+
2256
+ def unsave_project_for_user(project_id: str, owner_user_id: str) -> Dict[str, Any]:
2257
+ normalized_project_id = str(project_id or "").strip()
2258
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2259
+ if not normalized_project_id or not normalized_owner_user_id:
2260
+ raise ValueError("project_id and owner_user_id are required.")
2261
+ deleted = _DATABASE_REPOSITORY.delete_project_save(normalized_project_id, normalized_owner_user_id)
2262
+ if deleted:
2263
+ invalidate_project_lists()
2264
+ engagement = project_engagement_for_ids([normalized_project_id], normalized_owner_user_id).get(
2265
+ normalized_project_id,
2266
+ {"save_count": 0, "remix_count": 0, "saved": False},
2267
+ )
2268
+ return {
2269
+ "saved": False,
2270
+ "save_count": int(engagement.get("save_count") or 0),
2271
+ "remix_count": int(engagement.get("remix_count") or 0),
2272
+ }
2273
+
2274
+
2275
+ def remix_generated_project(source_project_id: str, owner_user_id: str) -> Optional[Any]:
2276
+ source = get_generated_project(str(source_project_id or "").strip())
2277
+ if source is None:
2278
+ return None
2279
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2280
+ if not normalized_owner_user_id:
2281
+ raise ValueError("owner_user_id is required.")
2282
+ new_project_id = str(uuid.uuid4())
2283
+ new_chat_id = str(uuid.uuid4())
2284
+ created_at = _project_engagement_timestamp()
2285
+ source_ir = getattr(source, "hardware_ir", None)
2286
+ hardware_ir = copy.deepcopy(source_ir) if isinstance(source_ir, dict) else {}
2287
+ metadata = hardware_ir.get("assembly_metadata") if isinstance(hardware_ir.get("assembly_metadata"), dict) else {}
2288
+ metadata = dict(metadata)
2289
+ metadata["project_id"] = new_project_id
2290
+ metadata["chat_id"] = new_chat_id
2291
+ metadata["source_project_id"] = source.project_id
2292
+ metadata["remixed_from_project_id"] = source.project_id
2293
+ hardware_ir["assembly_metadata"] = metadata
2294
+ title = getattr(source, "title", None) or "Untitled project"
2295
+ record = {
2296
+ "project_id": new_project_id,
2297
+ "chat_id": new_chat_id,
2298
+ "owner_user_id": normalized_owner_user_id,
2299
+ "visibility": _normalize_visibility(getattr(source, "visibility", None)),
2300
+ "title": title,
2301
+ "prompt": getattr(source, "prompt", None) or "",
2302
+ "hardware_ir": hardware_ir,
2303
+ "created_at": created_at,
2304
+ "status": "active",
2305
+ }
2306
+ chat_record = {
2307
+ "chat_id": new_chat_id,
2308
+ "owner_user_id": normalized_owner_user_id,
2309
+ "title": (title.strip()[:80] if isinstance(title, str) else "") or "Untitled chat",
2310
+ "messages": [],
2311
+ "created_at": created_at,
2312
+ "updated_at": created_at,
2313
+ }
2314
+ _DATABASE_REPOSITORY.save_generated_project(record, chat_record)
2315
+ _DATABASE_REPOSITORY.insert_project_remix(
2316
+ {
2317
+ "remix_project_id": new_project_id,
2318
+ "source_project_id": source.project_id,
2319
+ "owner_user_id": normalized_owner_user_id,
2320
+ "created_at": created_at,
2321
+ }
2322
+ )
2323
+ invalidate_project_lists()
2324
+ return get_generated_project(new_project_id)
2325
+
2326
+
2327
+ def get_user_settings(owner_user_id: str) -> Optional[Any]:
2328
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2329
+ if not normalized_owner_user_id:
2330
+ return None
2331
+ return _DATABASE_REPOSITORY.get_user_settings(normalized_owner_user_id)
2332
+
2333
+
2334
+ def set_user_model_training_preference(
2335
+ owner_user_id: str,
2336
+ *,
2337
+ allow_model_training: bool,
2338
+ updated_at: str,
2339
+ ) -> Any:
2340
+ normalized_owner_user_id = _normalize_user_id(owner_user_id)
2341
+ if not normalized_owner_user_id:
2342
+ raise ValueError("owner_user_id is required.")
2343
+ existing = _DATABASE_REPOSITORY.get_user_settings(normalized_owner_user_id)
2344
+ record = {
2345
+ "owner_user_id": normalized_owner_user_id,
2346
+ "model_training_opt_out": not allow_model_training,
2347
+ "created_at": getattr(existing, "created_at", None) or updated_at,
2348
+ "updated_at": updated_at,
2349
+ }
2350
+ return _DATABASE_REPOSITORY.upsert_user_settings(record)
2351
+
2352
+
2353
+ def list_model_training_opt_out_user_ids() -> List[str]:
2354
+ """Return owner ids that dataset exports must exclude from model training."""
2355
+
2356
+ return _DATABASE_REPOSITORY.list_model_training_opt_out_user_ids()
2357
+
2358
+
2359
+ def get_database_config() -> Dict[str, Any]:
2360
+ config = _DATABASE_PROVIDER.describe()
2361
+ config["dev_mode"] = forma_dev_mode_enabled()
2362
+ return config