openforma 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. forma_cli/__init__.py +5 -0
  2. forma_cli/app.py +1139 -0
  3. forma_cli/config.py +112 -0
  4. forma_cli/credentials.py +141 -0
  5. forma_cli/local.py +562 -0
  6. forma_cli/metadata_api.py +138 -0
  7. forma_cli/project_artifacts.py +182 -0
  8. forma_cli/sdk.py +571 -0
  9. forma_core/__init__.py +9 -0
  10. forma_core/__main__.py +4 -0
  11. forma_core/_version.py +3 -0
  12. forma_core/agents/__init__.py +50 -0
  13. forma_core/agents/clarification.py +194 -0
  14. forma_core/agents/component_reconciliation.py +99 -0
  15. forma_core/agents/context_gathering.py +115 -0
  16. forma_core/agents/continuous.py +537 -0
  17. forma_core/agents/contracts.py +247 -0
  18. forma_core/agents/firecrawl_mcp.py +484 -0
  19. forma_core/agents/lattice.py +239 -0
  20. forma_core/agents/orchestrator.py +3724 -0
  21. forma_core/agents/pipeline.py +843 -0
  22. forma_core/agents/project_correction.py +83 -0
  23. forma_core/agents/prompt_compaction.py +428 -0
  24. forma_core/agents/system_architecture.py +345 -0
  25. forma_core/agents/video_correction.py +119 -0
  26. forma_core/agents/web_research_workflow.py +1256 -0
  27. forma_core/agents/workflows.py +176 -0
  28. forma_core/assets/__init__.py +1 -0
  29. forma_core/assets/models.py +156 -0
  30. forma_core/assets/project.py +17 -0
  31. forma_core/assets/repository.py +48 -0
  32. forma_core/assets/service.py +142 -0
  33. forma_core/assets/validation.py +35 -0
  34. forma_core/benchmarks/__init__.py +5 -0
  35. forma_core/benchmarks/ir_triad_v1.py +477 -0
  36. forma_core/biology/__init__.py +28 -0
  37. forma_core/biology/benchmark.py +80 -0
  38. forma_core/biology/ewart_liverchip.py +279 -0
  39. forma_core/biology/ir.py +25 -0
  40. forma_core/biology/liverbench.py +416 -0
  41. forma_core/biology/liverbench_assay.py +251 -0
  42. forma_core/biology/liverbench_baselines.py +133 -0
  43. forma_core/biology/liverbench_independent.py +229 -0
  44. forma_core/biology/liverchip_demo.py +154 -0
  45. forma_core/biology/liverchip_evidence.py +149 -0
  46. forma_core/biology/models.py +247 -0
  47. forma_core/biology/validation.py +72 -0
  48. forma_core/cad_migrations/__init__.py +6 -0
  49. forma_core/cad_migrations/cli.py +101 -0
  50. forma_core/cad_migrations/emitters.py +227 -0
  51. forma_core/cad_migrations/models.py +121 -0
  52. forma_core/cad_migrations/planner.py +68 -0
  53. forma_core/chemistry/__init__.py +5 -0
  54. forma_core/chemistry/models.py +215 -0
  55. forma_core/chemistry/stoichiometry.py +272 -0
  56. forma_core/chemistry/validation.py +179 -0
  57. forma_core/cli/__init__.py +1 -0
  58. forma_core/cli/__main__.py +4 -0
  59. forma_core/cli/main.py +370 -0
  60. forma_core/config/__init__.py +28 -0
  61. forma_core/config/compatibility.py +282 -0
  62. forma_core/config/contract.py +184 -0
  63. forma_core/config/environment.py +129 -0
  64. forma_core/config/parti.py +34 -0
  65. forma_core/config/runtime.py +303 -0
  66. forma_core/control/__init__.py +10 -0
  67. forma_core/control/actions.py +136 -0
  68. forma_core/control/adapters.py +36 -0
  69. forma_core/control/cli.py +49 -0
  70. forma_core/control/client.py +124 -0
  71. forma_core/control/models.py +168 -0
  72. forma_core/control/opencode_worker.py +80 -0
  73. forma_core/control/package.py +318 -0
  74. forma_core/control/rover_scene/__init__.py +1 -0
  75. forma_core/control/rover_scene/__main__.py +34 -0
  76. forma_core/control/rover_scene/assets.py +65 -0
  77. forma_core/control/rover_scene/fleet.py +214 -0
  78. forma_core/control/rover_scene/host.py +258 -0
  79. forma_core/control/rover_scene/kinematics.py +35 -0
  80. forma_core/control/rover_scene/machine.py +347 -0
  81. forma_core/control/rover_scene/robot.py +166 -0
  82. forma_core/control/rover_scene/scene.py +206 -0
  83. forma_core/control/rover_scene/view.py +80 -0
  84. forma_core/control/rover_scene/web/index.html +25 -0
  85. forma_core/control/rover_scene/web/viewer.js +148 -0
  86. forma_core/control/runtime.py +356 -0
  87. forma_core/control/so101.py +235 -0
  88. forma_core/control/tasks.py +287 -0
  89. forma_core/database.py +2362 -0
  90. forma_core/debug.py +314 -0
  91. forma_core/domains/__init__.py +7 -0
  92. forma_core/domains/agents.py +85 -0
  93. forma_core/domains/base.py +69 -0
  94. forma_core/domains/benchmark.py +87 -0
  95. forma_core/domains/cli.py +48 -0
  96. forma_core/domains/compatibility.py +234 -0
  97. forma_core/domains/composition.py +372 -0
  98. forma_core/domains/diagnostics.py +15 -0
  99. forma_core/domains/generation.py +479 -0
  100. forma_core/domains/interaction.py +301 -0
  101. forma_core/domains/planning.py +140 -0
  102. forma_core/domains/providers.py +214 -0
  103. forma_core/domains/registry.py +267 -0
  104. forma_core/domains/selection.py +75 -0
  105. forma_core/domains/storage.py +60 -0
  106. forma_core/domains/tools.py +180 -0
  107. forma_core/electronics/__init__.py +1 -0
  108. forma_core/electronics/models.py +84 -0
  109. forma_core/electronics/primitives.py +43 -0
  110. forma_core/electronics/rules.py +340 -0
  111. forma_core/external_sources.py +497 -0
  112. forma_core/fabricator/__init__.py +33 -0
  113. forma_core/fabricator/__main__.py +7 -0
  114. forma_core/fabricator/main.py +578 -0
  115. forma_core/firmware/__init__.py +60 -0
  116. forma_core/firmware/drivers.py +140 -0
  117. forma_core/firmware/examples.py +503 -0
  118. forma_core/firmware/generate.py +520 -0
  119. forma_core/firmware/models.py +34 -0
  120. forma_core/firmware/sil/__init__.py +5 -0
  121. forma_core/firmware/sil/adapter.py +71 -0
  122. forma_core/firmware/sil/build.py +49 -0
  123. forma_core/firmware/sil/native/CMakeLists.txt +9 -0
  124. forma_core/firmware/sil/native/bridge.cpp +112 -0
  125. forma_core/firmware/sil/native/controller.cpp +123 -0
  126. forma_core/firmware/sil/native/controller.h +49 -0
  127. forma_core/firmware/sil/simulator.py +139 -0
  128. forma_core/firmware/targets.py +111 -0
  129. forma_core/firmware/validation.py +130 -0
  130. forma_core/fluidics/__init__.py +6 -0
  131. forma_core/fluidics/benchmark.py +217 -0
  132. forma_core/fluidics/calculations.py +79 -0
  133. forma_core/fluidics/examples.py +54 -0
  134. forma_core/fluidics/ir.py +25 -0
  135. forma_core/fluidics/models.py +132 -0
  136. forma_core/fluidics/topology.py +47 -0
  137. forma_core/fluidics/validation.py +134 -0
  138. forma_core/generation.py +32 -0
  139. forma_core/geometry_bindings/__init__.py +20 -0
  140. forma_core/geometry_bindings/cad_adapter.py +80 -0
  141. forma_core/geometry_bindings/models.py +163 -0
  142. forma_core/geometry_bindings/resolution.py +340 -0
  143. forma_core/geometry_bindings/tools.py +125 -0
  144. forma_core/image_providers.py +3049 -0
  145. forma_core/images.py +3 -0
  146. forma_core/integrations/__init__.py +1 -0
  147. forma_core/integrations/huggingface/__init__.py +29 -0
  148. forma_core/integrations/huggingface/huggingface_artifacts.py +272 -0
  149. forma_core/jobs/__init__.py +1 -0
  150. forma_core/jobs/context.py +277 -0
  151. forma_core/jobs/continuous.py +719 -0
  152. forma_core/jobs/metrics.py +124 -0
  153. forma_core/jobs/migrations.py +161 -0
  154. forma_core/jobs/persistence.py +28 -0
  155. forma_core/jobs/repositories.py +422 -0
  156. forma_core/jobs/schema.py +28 -0
  157. forma_core/jobs/source_usage.py +230 -0
  158. forma_core/jobs/store.py +476 -0
  159. forma_core/llm.py +3 -0
  160. forma_core/llm_providers.py +2682 -0
  161. forma_core/logs.py +107 -0
  162. forma_core/mechanics/__init__.py +1 -0
  163. forma_core/mechanics/gear_benchmark.py +85 -0
  164. forma_core/mechanics/mechanism_benchmarks.py +345 -0
  165. forma_core/mechanics/models.py +72 -0
  166. forma_core/mechanics/primitives.py +109 -0
  167. forma_core/mechanics/solid_cad.py +83 -0
  168. forma_core/observability.py +237 -0
  169. forma_core/openai_streams.py +780 -0
  170. forma_core/opencode/__init__.py +25 -0
  171. forma_core/opencode/architecture.py +82 -0
  172. forma_core/opencode/capabilities.py +130 -0
  173. forma_core/opencode/models.py +419 -0
  174. forma_core/opencode/persistence.py +62 -0
  175. forma_core/opencode/public_events.py +91 -0
  176. forma_core/opencode/schema.py +28 -0
  177. forma_core/opencode/store.py +874 -0
  178. forma_core/persistence/__init__.py +16 -0
  179. forma_core/persistence/base.py +38 -0
  180. forma_core/persistence/images.py +598 -0
  181. forma_core/persistence/migrations.py +200 -0
  182. forma_core/persistence/models.py +439 -0
  183. forma_core/persistence/project_artifacts.py +341 -0
  184. forma_core/persistence/project_reconciliation.py +1094 -0
  185. forma_core/persistence/providers/__init__.py +4 -0
  186. forma_core/persistence/providers/sqlite.py +114 -0
  187. forma_core/persistence/providers/supabase.py +31 -0
  188. forma_core/persistence/repositories/__init__.py +9 -0
  189. forma_core/persistence/repositories/base.py +335 -0
  190. forma_core/persistence/repositories/sqlite.py +1571 -0
  191. forma_core/persistence/repositories/supabase.py +1576 -0
  192. forma_core/persistence/schema.py +176 -0
  193. forma_core/processes/__init__.py +5 -0
  194. forma_core/processes/models.py +338 -0
  195. forma_core/processes/validation.py +141 -0
  196. forma_core/project_list_cache.py +316 -0
  197. forma_core/prompt_continuity.py +387 -0
  198. forma_core/providers/__init__.py +39 -0
  199. forma_core/providers/base.py +28 -0
  200. forma_core/providers/models.py +138 -0
  201. forma_core/providers/openai.py +92 -0
  202. forma_core/providers/openai_compatible.py +190 -0
  203. forma_core/providers/registry.py +68 -0
  204. forma_core/providers/registry_utils.py +46 -0
  205. forma_core/py.typed +1 -0
  206. forma_core/runtime.py +3 -0
  207. forma_core/selectors.py +36 -0
  208. forma_core/signups/__init__.py +5 -0
  209. forma_core/signups/models.py +49 -0
  210. forma_core/terminal/__init__.py +1 -0
  211. forma_core/terminal/dashboard.py +475 -0
  212. forma_core/terminal/images.py +156 -0
  213. forma_core/thermal/__init__.py +5 -0
  214. forma_core/thermal/models.py +361 -0
  215. forma_core/thermal/validation.py +175 -0
  216. forma_core/user_integrations.py +2069 -0
  217. forma_core/utils.py +291 -0
  218. forma_core/validation.py +83 -0
  219. forma_core/vertex_auth.py +92 -0
  220. forma_core/video_prompts.py +193 -0
  221. forma_core/video_review.py +1006 -0
  222. forma_core/wiring.py +356 -0
  223. forma_core/workers/__init__.py +120 -0
  224. forma_core/workers/contracts.py +183 -0
  225. forma_core/workers/generation.py +753 -0
  226. forma_core/workers/orchestration.py +805 -0
  227. forma_core/workers/registry.py +222 -0
  228. forma_core/workers/reverse_engineering.py +272 -0
  229. forma_core/workers/validation.py +291 -0
  230. forma_core/workspaces/__init__.py +5 -0
  231. forma_core/workspaces/chats/__init__.py +11 -0
  232. forma_core/workspaces/chats/models.py +48 -0
  233. forma_core/workspaces/context/__init__.py +15 -0
  234. forma_core/workspaces/context/agent.py +260 -0
  235. forma_core/workspaces/context/models.py +117 -0
  236. forma_core/workspaces/context/pdf.py +418 -0
  237. forma_core/workspaces/design_briefs/__init__.py +25 -0
  238. forma_core/workspaces/design_briefs/models.py +85 -0
  239. forma_core/workspaces/design_briefs/references.py +56 -0
  240. forma_core/workspaces/models.py +41 -0
  241. forma_core/workspaces/projects/__init__.py +88 -0
  242. forma_core/workspaces/projects/cad_generation.py +1016 -0
  243. forma_core/workspaces/projects/context_governance.py +365 -0
  244. forma_core/workspaces/projects/design_lifecycle.py +668 -0
  245. forma_core/workspaces/projects/fabrication/__init__.py +54 -0
  246. forma_core/workspaces/projects/fabrication/demo_printers.py +236 -0
  247. forma_core/workspaces/projects/fabrication/models.py +120 -0
  248. forma_core/workspaces/projects/fabrication/printer_config.py +205 -0
  249. forma_core/workspaces/projects/fabrication/slicers/__init__.py +7 -0
  250. forma_core/workspaces/projects/fabrication/slicers/base.py +25 -0
  251. forma_core/workspaces/projects/fabrication/slicers/cura.py +125 -0
  252. forma_core/workspaces/projects/fabrication/slicers/orca.py +208 -0
  253. forma_core/workspaces/projects/fabrication/slicing.py +202 -0
  254. forma_core/workspaces/projects/fabrication/validation.py +103 -0
  255. forma_core/workspaces/projects/gear_benchmark.py +6 -0
  256. forma_core/workspaces/projects/generation_mode.py +70 -0
  257. forma_core/workspaces/projects/identity.py +28 -0
  258. forma_core/workspaces/projects/iteration.py +680 -0
  259. forma_core/workspaces/projects/manifest.py +362 -0
  260. forma_core/workspaces/projects/mechanism_benchmarks.py +12 -0
  261. forma_core/workspaces/projects/models.py +913 -0
  262. forma_core/workspaces/projects/objects.py +731 -0
  263. forma_core/workspaces/projects/outcomes.py +47 -0
  264. forma_core/workspaces/projects/output.py +735 -0
  265. forma_core/workspaces/projects/resolver.py +397 -0
  266. forma_core/workspaces/projects/solid_cad.py +8 -0
  267. forma_core/workspaces/projects/state.py +622 -0
  268. forma_core/workspaces/readiness/__init__.py +28 -0
  269. forma_core/workspaces/readiness/evaluator.py +103 -0
  270. forma_core/workspaces/readiness/models.py +97 -0
  271. forma_core/workspaces/readiness/service.py +225 -0
  272. forma_core/workspaces/reverse_engineering/__init__.py +37 -0
  273. forma_core/workspaces/reverse_engineering/analyzer.py +246 -0
  274. forma_core/workspaces/reverse_engineering/models.py +128 -0
  275. forma_core/workspaces/validation/__init__.py +37 -0
  276. forma_core/workspaces/validation/evaluator.py +327 -0
  277. forma_core/workspaces/validation/models.py +146 -0
  278. forma_core/workspaces/validation/service.py +212 -0
  279. forma_core/workspaces/workflow/__init__.py +29 -0
  280. forma_core/workspaces/workflow/guard.py +33 -0
  281. forma_core/workspaces/workflow/models.py +77 -0
  282. forma_core/workspaces/workflow/service.py +287 -0
  283. openforma-0.4.0.dist-info/METADATA +247 -0
  284. openforma-0.4.0.dist-info/RECORD +288 -0
  285. openforma-0.4.0.dist-info/WHEEL +5 -0
  286. openforma-0.4.0.dist-info/entry_points.txt +4 -0
  287. openforma-0.4.0.dist-info/licenses/LICENSE +373 -0
  288. openforma-0.4.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,362 @@
1
+ """Portable project manifests used by the local-first Forma CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ import json
7
+ import mimetypes
8
+ from pathlib import Path
9
+ import re
10
+ from typing import Any, Mapping
11
+ from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
12
+
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+
15
+
16
+ PROJECT_MANIFEST_FORMAT = "forma-project"
17
+ PROJECT_MANIFEST_VERSION = 1
18
+ _SHA256_PATTERN = re.compile(r"^[0-9a-fA-F]{64}$")
19
+ _MEDIA_TYPE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*$")
20
+ _NON_PATH_KEYS = frozenset(
21
+ {
22
+ "filename",
23
+ "name",
24
+ "title",
25
+ "description",
26
+ "label",
27
+ "format",
28
+ "source",
29
+ "url",
30
+ "download_url",
31
+ "source_url",
32
+ }
33
+ )
34
+ _SECRET_FIELD_MARKERS = (
35
+ "api_key",
36
+ "apikey",
37
+ "authorization",
38
+ "password",
39
+ "secret",
40
+ "token",
41
+ )
42
+
43
+
44
+ def normalize_artifact_path(value: object) -> str:
45
+ """Return a safe, portable project-relative artifact path."""
46
+ raw = str(value or "").strip().replace("\\", "/")
47
+ if not raw:
48
+ raise ValueError("Artifact path must not be empty.")
49
+ if (
50
+ "\x00" in raw
51
+ or "://" in raw
52
+ or raw.startswith("/")
53
+ or re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", raw)
54
+ ):
55
+ raise ValueError(f"Artifact path must be project-relative: {value!r}")
56
+
57
+ parts = []
58
+ for part in raw.split("/"):
59
+ if part in {"", "."}:
60
+ continue
61
+ if part == "..":
62
+ raise ValueError(f"Artifact path may not escape the project directory: {value!r}")
63
+ parts.append(part)
64
+ if not parts:
65
+ raise ValueError("Artifact path must identify a file.")
66
+ return "/".join(parts)
67
+
68
+
69
+ def normalize_artifact_media_type(value: object) -> str:
70
+ """Normalize and validate an artifact media type without parameters."""
71
+ media_type = str(value or "").split(";", 1)[0].strip().lower()
72
+ if not media_type or not _MEDIA_TYPE_PATTERN.fullmatch(media_type):
73
+ raise ValueError(f"Invalid artifact media type: {value!r}")
74
+ return media_type
75
+
76
+
77
+ def infer_artifact_media_type(path: str) -> str:
78
+ """Infer a stable media type for common CAD files and ordinary documents."""
79
+ suffix = Path(path).suffix.lower()
80
+ if suffix in {".step", ".stp"}:
81
+ return "model/step"
82
+ if suffix == ".stl":
83
+ return "model/stl"
84
+ if suffix == ".3mf":
85
+ return "model/3mf"
86
+ if suffix in {".gcode", ".gc", ".gco"}:
87
+ return "text/x-gcode"
88
+ return mimetypes.guess_type(path)[0] or "application/octet-stream"
89
+
90
+
91
+ def validate_artifact_references(
92
+ artifacts: object,
93
+ *,
94
+ require_integrity: bool = True,
95
+ ) -> list[dict[str, Any]]:
96
+ """Normalize artifact declarations and reject unsafe or ambiguous entries."""
97
+ if artifacts is None:
98
+ return []
99
+ if not isinstance(artifacts, list):
100
+ raise ValueError("Project artifacts must be a list.")
101
+
102
+ normalized: list[dict[str, Any]] = []
103
+ seen_paths: set[str] = set()
104
+ for index, item in enumerate(artifacts):
105
+ if isinstance(item, BaseModel):
106
+ record = item.model_dump(mode="json")
107
+ elif isinstance(item, Mapping):
108
+ record = dict(item)
109
+ else:
110
+ raise ValueError(f"Project artifact {index + 1} must be an object.")
111
+ path = normalize_artifact_path(record.get("path"))
112
+ lower_path = path.lower()
113
+ if lower_path == "forma-project.json" or lower_path == ".forma" or lower_path.startswith(".forma/"):
114
+ raise ValueError(f"Project artifact path is reserved: {path}")
115
+ path_key = path.casefold()
116
+ if path_key in seen_paths:
117
+ raise ValueError(f"Project artifact path is duplicated: {path}")
118
+ seen_paths.add(path_key)
119
+ record["path"] = path
120
+
121
+ raw_sha256 = record.get("sha256")
122
+ if raw_sha256 is None or not str(raw_sha256).strip():
123
+ if require_integrity:
124
+ raise ValueError(f"Project artifact {path} must declare a SHA-256 hash.")
125
+ else:
126
+ sha256 = str(raw_sha256).strip().lower()
127
+ if not _SHA256_PATTERN.fullmatch(sha256):
128
+ raise ValueError(f"Project artifact {path} has an invalid SHA-256 hash.")
129
+ record["sha256"] = sha256
130
+
131
+ raw_media_type = record.get("media_type")
132
+ if raw_media_type is None or not str(raw_media_type).strip():
133
+ if require_integrity:
134
+ raise ValueError(f"Project artifact {path} must declare a media type.")
135
+ else:
136
+ record["media_type"] = normalize_artifact_media_type(raw_media_type)
137
+
138
+ if "size_bytes" in record and record["size_bytes"] is not None:
139
+ size = record["size_bytes"]
140
+ if isinstance(size, bool) or not isinstance(size, int) or size < 0:
141
+ raise ValueError(f"Project artifact {path} has an invalid size_bytes value.")
142
+ normalized.append(record)
143
+ return normalized
144
+
145
+
146
+ def rewrite_artifact_paths(value: Any, replacements: Mapping[str, str], *, _key: str | None = None) -> Any:
147
+ """Rewrite known project-file references while preserving display filenames."""
148
+ if isinstance(value, Mapping):
149
+ return {
150
+ str(key): rewrite_artifact_paths(item, replacements, _key=str(key))
151
+ for key, item in value.items()
152
+ }
153
+ if isinstance(value, list):
154
+ return [rewrite_artifact_paths(item, replacements, _key=_key) for item in value]
155
+ if isinstance(value, tuple):
156
+ return [rewrite_artifact_paths(item, replacements, _key=_key) for item in value]
157
+ if not isinstance(value, str) or (_key and _key.strip().lower() in _NON_PATH_KEYS):
158
+ return deepcopy(value)
159
+
160
+ candidates = (value, value.replace("\\", "/"))
161
+ for candidate in candidates:
162
+ replacement = replacements.get(candidate)
163
+ if replacement is not None:
164
+ return replacement
165
+ suffix_matches: list[tuple[int, str]] = []
166
+ for source, source_replacement in replacements.items():
167
+ normalized_source = str(source).replace("\\", "/").strip("/")
168
+ if normalized_source and candidate.rstrip("/").endswith(f"/{normalized_source}"):
169
+ suffix_matches.append((len(normalized_source), source_replacement))
170
+ if suffix_matches:
171
+ return max(suffix_matches, key=lambda match: match[0])[1]
172
+ return value
173
+
174
+
175
+ def _is_secret_field(name: object) -> bool:
176
+ normalized = str(name).strip().lower().replace("-", "_")
177
+ return normalized in {"key", "credential", "credentials"} or any(
178
+ marker in normalized for marker in _SECRET_FIELD_MARKERS
179
+ )
180
+
181
+
182
+ def redact_project_secrets(value: Any) -> Any:
183
+ """Return a JSON-compatible copy without credential-like fields."""
184
+ if isinstance(value, Mapping):
185
+ return {
186
+ str(key): redact_project_secrets(item)
187
+ for key, item in value.items()
188
+ if not _is_secret_field(key)
189
+ }
190
+ if isinstance(value, list):
191
+ return [redact_project_secrets(item) for item in value]
192
+ if isinstance(value, tuple):
193
+ return [redact_project_secrets(item) for item in value]
194
+ return deepcopy(value)
195
+
196
+
197
+ class ProjectArtifactReference(BaseModel):
198
+ model_config = ConfigDict(extra="allow")
199
+
200
+ path: str
201
+ sha256: str | None = None
202
+ media_type: str | None = None
203
+ size_bytes: int | None = Field(default=None, ge=0)
204
+
205
+
206
+ class ProjectManifest(BaseModel):
207
+ """Canonical, uploadable representation of one local Forma project."""
208
+
209
+ model_config = ConfigDict(extra="allow")
210
+
211
+ format: str = PROJECT_MANIFEST_FORMAT
212
+ version: int = Field(default=PROJECT_MANIFEST_VERSION, ge=1)
213
+ project_id: str = Field(min_length=1)
214
+ workspace_id: str | None = None
215
+ title: str = ""
216
+ prompt: str = ""
217
+ visibility: str = "public"
218
+ project_ir: dict[str, Any] = Field(default_factory=dict)
219
+ artifacts: list[ProjectArtifactReference] = Field(default_factory=list)
220
+
221
+ @classmethod
222
+ def from_document(cls, document: Mapping[str, Any]) -> "ProjectManifest":
223
+ """Accept both the canonical wrapper and legacy raw Hardware Intermediate Representation JSON."""
224
+ raw = dict(document)
225
+ nested = raw.get("project_ir")
226
+ if not isinstance(nested, Mapping):
227
+ nested = raw.get("hardware_ir")
228
+ project_ir = dict(nested) if isinstance(nested, Mapping) else raw
229
+ metadata = project_ir.get("assembly_metadata")
230
+ metadata = metadata if isinstance(metadata, Mapping) else {}
231
+ project_id = raw.get("project_id") or metadata.get("project_id") or str(uuid4())
232
+ overview = project_ir.get("overview")
233
+ overview = overview if isinstance(overview, Mapping) else {}
234
+ title = raw.get("title") or overview.get("title") or "Untitled Forma Project"
235
+ prompt = raw.get("prompt") or metadata.get("project_prompt") or ""
236
+ artifact_values = []
237
+ for item in raw.get("artifacts") or []:
238
+ if not isinstance(item, Mapping):
239
+ continue
240
+ artifact = dict(item)
241
+ artifact.setdefault("path", artifact.get("uri") or artifact.get("name") or "")
242
+ artifact_values.append(artifact)
243
+ return cls(
244
+ format=str(raw.get("format") or PROJECT_MANIFEST_FORMAT),
245
+ version=int(raw.get("version") or PROJECT_MANIFEST_VERSION),
246
+ project_id=str(project_id),
247
+ workspace_id=str(raw["workspace_id"]) if raw.get("workspace_id") else None,
248
+ title=str(title),
249
+ prompt=str(prompt),
250
+ visibility=str(raw.get("visibility") or "public").strip().lower(),
251
+ project_ir=project_ir,
252
+ artifacts=[ProjectArtifactReference.model_validate(item) for item in artifact_values],
253
+ )
254
+
255
+ def upload_payload(self) -> dict[str, Any]:
256
+ """Build the only payload shape that may cross the cloud boundary."""
257
+ return redact_project_secrets(self.model_dump(mode="json"))
258
+
259
+
260
+ def build_canonical_revision_record(
261
+ project_record: Mapping[str, Any],
262
+ revision_record: Mapping[str, Any],
263
+ ) -> dict[str, Any] | None:
264
+ """Build a unified revision when a CLI identifier and IR are canonicalizable."""
265
+ try:
266
+ project_id = UUID(str(project_record["project_id"]).strip())
267
+ revision_id = UUID(str(revision_record["revision_id"]).strip())
268
+ except (KeyError, TypeError, ValueError, AttributeError):
269
+ return None
270
+
271
+ manifest = revision_record.get("manifest_json")
272
+ if not isinstance(manifest, Mapping):
273
+ return None
274
+ try:
275
+ from forma_core.workspaces.projects.models import HardwareIntermediateRepresentation
276
+ from forma_core.workspaces.projects.state import ProjectRevision
277
+
278
+ state = HardwareIntermediateRepresentation.model_validate(manifest.get("project_ir") or {})
279
+ artifacts = []
280
+ for item in validate_artifact_references(manifest.get("artifacts"), require_integrity=False):
281
+ path = str(item["path"])
282
+ artifact = {
283
+ "artifact_id": str(item.get("sha256") or path),
284
+ "kind": "file",
285
+ "uri": path,
286
+ "media_type": item.get("media_type"),
287
+ "checksum": item.get("sha256"),
288
+ "metadata": {"size_bytes": item.get("size_bytes")} if item.get("size_bytes") is not None else {},
289
+ }
290
+ artifacts.append(artifact)
291
+ payload = {
292
+ "schema_version": "1.0",
293
+ "revision_id": str(revision_id),
294
+ "project_id": str(project_id),
295
+ "owner_user_id": str(project_record["owner_user_id"]),
296
+ "revision": int(revision_record["revision"]),
297
+ "parent_revision": max(1, int(revision_record["revision"]) - 1)
298
+ if int(revision_record["revision"]) > 1
299
+ else None,
300
+ "design_brief_id": str(uuid5(NAMESPACE_URL, f"forma-cli-brief:{project_id}")),
301
+ "design_brief_version": 1,
302
+ "source_job_id": f"cli:{revision_id}",
303
+ "created_at": revision_record["created_at"],
304
+ "state": state.model_dump(mode="json"),
305
+ "components": [item.model_dump(mode="json") for item in state.components],
306
+ "systems": [],
307
+ "artifacts": artifacts,
308
+ "assumptions": [],
309
+ }
310
+ ProjectRevision.model_validate(payload)
311
+ except (KeyError, TypeError, ValueError):
312
+ return None
313
+ return {
314
+ "id": str(revision_id),
315
+ "project_id": str(project_id),
316
+ "owner_user_id": str(project_record["owner_user_id"]),
317
+ "revision": int(revision_record["revision"]),
318
+ "parent_revision": payload["parent_revision"],
319
+ "design_brief_id": payload["design_brief_id"],
320
+ "design_brief_version": 1,
321
+ "source_job_id": payload["source_job_id"],
322
+ "payload_json": payload,
323
+ "created_at": revision_record["created_at"],
324
+ }
325
+
326
+
327
+ def load_project_manifest(path: str | Path) -> ProjectManifest:
328
+ project_path = Path(path)
329
+ with project_path.open(encoding="utf-8") as file:
330
+ document = json.load(file)
331
+ if not isinstance(document, Mapping):
332
+ raise ValueError(f"Project manifest must contain a JSON object: {project_path}")
333
+ return ProjectManifest.from_document(document)
334
+
335
+
336
+ def write_project_manifest(path: str | Path, manifest: ProjectManifest) -> None:
337
+ project_path = Path(path)
338
+ safe_payload = redact_project_secrets(manifest.model_dump(mode="json"))
339
+ project_path.parent.mkdir(parents=True, exist_ok=True)
340
+ temporary_path = project_path.with_suffix(f"{project_path.suffix}.tmp")
341
+ temporary_path.write_text(
342
+ json.dumps(safe_payload, indent=2, sort_keys=True) + "\n",
343
+ encoding="utf-8",
344
+ )
345
+ temporary_path.replace(project_path)
346
+
347
+
348
+ __all__ = [
349
+ "PROJECT_MANIFEST_FORMAT",
350
+ "PROJECT_MANIFEST_VERSION",
351
+ "ProjectArtifactReference",
352
+ "ProjectManifest",
353
+ "build_canonical_revision_record",
354
+ "infer_artifact_media_type",
355
+ "load_project_manifest",
356
+ "normalize_artifact_media_type",
357
+ "normalize_artifact_path",
358
+ "redact_project_secrets",
359
+ "rewrite_artifact_paths",
360
+ "validate_artifact_references",
361
+ "write_project_manifest",
362
+ ]
@@ -0,0 +1,12 @@
1
+ """Backward-compatible imports; mechanical implementation lives in mechanics."""
2
+
3
+ from forma_core.mechanics.mechanism_benchmarks import (
4
+ PrintInPlaceHingeBenchmark,
5
+ MonolithicFlexureBenchmark,
6
+ MechanismBenchmark,
7
+ mechanism_cad_source,
8
+ _print_in_place_hinge_source,
9
+ _monolithic_flexure_source,
10
+ SpurGearPairBenchmark,
11
+ gear_pair_source,
12
+ )