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,138 @@
1
+ """Read-only local project metadata API for CLI verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from hashlib import sha256
6
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
7
+ import json
8
+ from pathlib import Path
9
+ from typing import Any
10
+ from urllib.parse import unquote, urlparse
11
+
12
+ from forma_core.database import get_project_identity
13
+
14
+ from forma_cli.local import project_root, read_project, status_project
15
+
16
+
17
+ def _file_metadata(root: Path, path: str | None, media_type: str | None = None) -> dict[str, Any]:
18
+ raw_path = Path(path).expanduser() if path else None
19
+ resolved = raw_path if raw_path and raw_path.is_absolute() else root / raw_path if raw_path else None
20
+ resolved = resolved.resolve() if resolved else None
21
+ exists = bool(resolved and resolved.is_file())
22
+ payload: dict[str, Any] = {
23
+ "path": str(resolved) if resolved else None,
24
+ "relative_path": str(resolved.relative_to(root)) if resolved and resolved.is_relative_to(root) else path,
25
+ "exists": exists,
26
+ }
27
+ if media_type:
28
+ payload["media_type"] = media_type
29
+ if exists and resolved:
30
+ data = resolved.read_bytes()
31
+ payload["bytes"] = len(data)
32
+ payload["sha256"] = sha256(data).hexdigest()
33
+ else:
34
+ payload["bytes"] = 0
35
+ payload["sha256"] = None
36
+ return payload
37
+
38
+
39
+ def project_metadata(path: str | Path | None = None) -> dict[str, Any]:
40
+ """Return verification metadata without making an HTTP/API request."""
41
+ root = project_root(path)
42
+ manifest = read_project(root)
43
+ ir = manifest.project_ir if isinstance(manifest.project_ir, dict) else {}
44
+ overview = ir.get("overview") if isinstance(ir.get("overview"), dict) else {}
45
+ mechanical = ir.get("mechanical") if isinstance(ir.get("mechanical"), dict) else {}
46
+ cad = ir.get("cad_model") if isinstance(ir.get("cad_model"), dict) else {}
47
+ project_id = manifest.project_id
48
+
49
+ try:
50
+ stored = get_project_identity(project_id)
51
+ database = {
52
+ "present": stored is not None,
53
+ "owner_user_id": stored.get("owner_user_id") if stored else None,
54
+ "status": stored.get("status") if stored else None,
55
+ "visibility": stored.get("visibility") if stored else None,
56
+ }
57
+ except Exception as exc:
58
+ stored = None
59
+ database = {"present": False, "error": str(exc)}
60
+
61
+ artifacts = []
62
+ for artifact in manifest.artifacts:
63
+ artifacts.append(_file_metadata(root, artifact.path, artifact.media_type))
64
+
65
+ cad_path = _file_metadata(root, cad.get("path"), "model/step") if cad else None
66
+ preview_path = _file_metadata(root, cad.get("preview_path"), "model/stl") if cad else None
67
+ meshes = cad.get("meshes") if isinstance(cad.get("meshes"), list) else []
68
+ mesh_vertices = sum(
69
+ len(mesh.get("vertices", []))
70
+ for mesh in meshes
71
+ if isinstance(mesh, dict) and isinstance(mesh.get("vertices"), list)
72
+ )
73
+ status = status_project(root)
74
+ return {
75
+ "project_id": project_id,
76
+ "title": manifest.title or overview.get("title"),
77
+ "prompt": manifest.prompt,
78
+ "manifest_path": str(root / "forma-project.json"),
79
+ "database": database,
80
+ "hardware": {
81
+ "components": len(ir.get("components", [])) if isinstance(ir.get("components"), list) else 0,
82
+ "nets": len(ir.get("nets", [])) if isinstance(ir.get("nets"), list) else 0,
83
+ "placements": len(mechanical.get("component_placements", [])),
84
+ },
85
+ "cad": {
86
+ "present": bool(cad),
87
+ "adapter": cad.get("adapter") if cad else None,
88
+ "format": cad.get("format") if cad else None,
89
+ "meshes": len(meshes),
90
+ "mesh_vertices": mesh_vertices,
91
+ "step": cad_path,
92
+ "preview": preview_path,
93
+ },
94
+ "artifacts": artifacts,
95
+ "validation": status["validation"],
96
+ "valid": status["valid"],
97
+ }
98
+
99
+
100
+ class _MetadataHandler(BaseHTTPRequestHandler):
101
+ project_path: str | Path = "."
102
+
103
+ def do_GET(self) -> None: # noqa: N802 - stdlib handler API
104
+ parsed = urlparse(self.path)
105
+ if parsed.path not in {"/metadata", "/metadata/"}:
106
+ project_id = unquote(parsed.path.removeprefix("/metadata/")).strip("/")
107
+ if project_id and project_id != project_metadata(self.project_path)["project_id"]:
108
+ self.send_error(404, "Project not found")
109
+ return
110
+ try:
111
+ payload = project_metadata(self.project_path)
112
+ body = json.dumps(payload, indent=2, sort_keys=True).encode("utf-8")
113
+ except Exception as exc:
114
+ body = json.dumps({"error": str(exc)}).encode("utf-8")
115
+ self.send_response(500)
116
+ self.send_header("Content-Type", "application/json")
117
+ self.send_header("Content-Length", str(len(body)))
118
+ self.end_headers()
119
+ self.wfile.write(body)
120
+ return
121
+ self.send_response(200)
122
+ self.send_header("Content-Type", "application/json")
123
+ self.send_header("Cache-Control", "no-store")
124
+ self.send_header("Content-Length", str(len(body)))
125
+ self.end_headers()
126
+ self.wfile.write(body)
127
+
128
+ def log_message(self, format: str, *args: Any) -> None:
129
+ return None
130
+
131
+
132
+ def serve_metadata_api(path: str | Path | None, host: str, port: int) -> None:
133
+ handler = type("ProjectMetadataHandler", (_MetadataHandler,), {"project_path": path or "."})
134
+ with ThreadingHTTPServer((host, port), handler) as server:
135
+ server.serve_forever()
136
+
137
+
138
+ __all__ = ["project_metadata", "serve_metadata_api"]
@@ -0,0 +1,182 @@
1
+ """Local artifact preparation and integrity checks for cloud project sync."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import dataclass
7
+ from pathlib import Path, PureWindowsPath
8
+ from typing import Any
9
+
10
+ from forma_cli.local import LocalProjectError
11
+ from forma_core.workspaces.projects.manifest import (
12
+ ProjectManifest,
13
+ infer_artifact_media_type,
14
+ normalize_artifact_media_type,
15
+ normalize_artifact_path,
16
+ redact_project_secrets,
17
+ rewrite_artifact_paths,
18
+ )
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class LocalProjectArtifact:
23
+ """A validated local file ready to be transferred."""
24
+
25
+ path: str
26
+ source_path: Path
27
+ sha256: str
28
+ media_type: str
29
+ size_bytes: int
30
+
31
+
32
+ def _portable_path(root: Path, value: object, *, require_file: bool = True) -> tuple[str, Path]:
33
+ raw = str(value or "").strip()
34
+ candidate = Path(raw).expanduser()
35
+ windows_absolute = PureWindowsPath(raw).is_absolute() or bool(PureWindowsPath(raw).drive)
36
+ if candidate.is_absolute() or windows_absolute:
37
+ source = candidate.resolve()
38
+ try:
39
+ relative = source.relative_to(root)
40
+ except ValueError as exc:
41
+ raise LocalProjectError(
42
+ f"Project artifact must be inside the project directory: {value!r}"
43
+ ) from exc
44
+ portable = relative.as_posix()
45
+ else:
46
+ portable = normalize_artifact_path(raw)
47
+ source = (root / Path(*portable.split("/"))).resolve()
48
+ try:
49
+ source.relative_to(root)
50
+ except ValueError as exc:
51
+ raise LocalProjectError(
52
+ f"Project artifact must be inside the project directory: {value!r}"
53
+ ) from exc
54
+ if require_file and not source.is_file():
55
+ raise LocalProjectError(f"Project artifact does not exist: {source}")
56
+ return portable, source
57
+
58
+
59
+ def _file_digest(path: Path) -> tuple[str, int]:
60
+ digest = hashlib.sha256()
61
+ size = 0
62
+ with path.open("rb") as file:
63
+ while chunk := file.read(1024 * 1024):
64
+ digest.update(chunk)
65
+ size += len(chunk)
66
+ return digest.hexdigest(), size
67
+
68
+
69
+ def canonical_project_upload_payload(root: str | Path, manifest: ProjectManifest) -> dict[str, Any]:
70
+ """Canonicalize local file paths without requiring artifact bytes to exist."""
71
+ project_root = Path(root).expanduser().resolve()
72
+ payload = manifest.upload_payload()
73
+ references: list[dict[str, Any]] = []
74
+ replacements: dict[str, str] = {}
75
+ for artifact in manifest.artifacts:
76
+ portable, source = _portable_path(project_root, artifact.path, require_file=False)
77
+ lower_portable = portable.lower()
78
+ if lower_portable == "forma-project.json" or lower_portable == ".forma" or lower_portable.startswith(".forma/"):
79
+ raise LocalProjectError(f"Project artifact path is reserved: {portable}")
80
+ reference = redact_project_secrets(artifact.model_dump(mode="json"))
81
+ reference["path"] = portable
82
+ if reference.get("sha256"):
83
+ reference["sha256"] = str(reference["sha256"]).strip().lower()
84
+ if reference.get("media_type"):
85
+ reference["media_type"] = normalize_artifact_media_type(reference["media_type"])
86
+ references.append(reference)
87
+ replacements[str(artifact.path)] = portable
88
+ replacements[str(artifact.path).replace("\\", "/")] = portable
89
+ replacements[str(source)] = portable
90
+ replacements[source.as_posix()] = portable
91
+ payload["artifacts"] = references
92
+ payload["project_ir"] = rewrite_artifact_paths(payload.get("project_ir", {}), replacements)
93
+ return payload
94
+
95
+
96
+ def prepare_project_upload(
97
+ root: str | Path,
98
+ manifest: ProjectManifest,
99
+ ) -> tuple[dict[str, Any], list[LocalProjectArtifact]]:
100
+ """Validate referenced files and return a portable upload manifest."""
101
+ project_root = Path(root).expanduser().resolve()
102
+ payload = canonical_project_upload_payload(project_root, manifest)
103
+ references: list[dict[str, Any]] = []
104
+ prepared: list[LocalProjectArtifact] = []
105
+ seen_paths: set[str] = set()
106
+ replacements: dict[str, str] = {}
107
+
108
+ for artifact in manifest.artifacts:
109
+ portable, source = _portable_path(project_root, artifact.path)
110
+ lower_portable = portable.lower()
111
+ if lower_portable == "forma-project.json" or lower_portable == ".forma" or lower_portable.startswith(".forma/"):
112
+ raise LocalProjectError(f"Project artifact path is reserved: {portable}")
113
+ portable_key = portable.casefold()
114
+ if portable_key in seen_paths:
115
+ raise LocalProjectError(f"Project artifact path is duplicated: {portable}")
116
+ seen_paths.add(portable_key)
117
+ sha256, size_bytes = _file_digest(source)
118
+ declared_sha256 = (artifact.sha256 or "").strip().lower()
119
+ if declared_sha256 and declared_sha256 != sha256:
120
+ raise LocalProjectError(
121
+ f"Project artifact hash mismatch for {portable}: "
122
+ f"manifest declares {declared_sha256}, local file is {sha256}."
123
+ )
124
+ try:
125
+ media_type = normalize_artifact_media_type(artifact.media_type) if artifact.media_type else None
126
+ except ValueError as exc:
127
+ raise LocalProjectError(f"Project artifact {portable} has an invalid media type.") from exc
128
+ media_type = media_type or infer_artifact_media_type(portable)
129
+ reference = redact_project_secrets(artifact.model_dump(mode="json"))
130
+ reference.update(
131
+ {
132
+ "path": portable,
133
+ "sha256": sha256,
134
+ "media_type": media_type,
135
+ "size_bytes": size_bytes,
136
+ }
137
+ )
138
+ references.append(reference)
139
+ prepared.append(
140
+ LocalProjectArtifact(
141
+ path=portable,
142
+ source_path=source,
143
+ sha256=sha256,
144
+ media_type=media_type,
145
+ size_bytes=size_bytes,
146
+ )
147
+ )
148
+ replacements[str(artifact.path)] = portable
149
+ replacements[str(artifact.path).replace("\\", "/")] = portable
150
+ replacements[str(source)] = portable
151
+ replacements[source.as_posix()] = portable
152
+
153
+ payload["artifacts"] = references
154
+ payload["project_ir"] = rewrite_artifact_paths(payload.get("project_ir", {}), replacements)
155
+ return payload, prepared
156
+
157
+
158
+ def file_digest(path: str | Path) -> str:
159
+ """Return a file SHA-256 for working-tree conflict checks."""
160
+ digest, _size = _file_digest(Path(path))
161
+ return digest
162
+
163
+
164
+ def artifact_target(root: str | Path, path: str) -> Path:
165
+ """Resolve a remote artifact path beneath the local project root."""
166
+ project_root = Path(root).expanduser().resolve()
167
+ portable = normalize_artifact_path(path)
168
+ target = project_root / Path(*portable.split("/"))
169
+ try:
170
+ target.resolve().relative_to(project_root)
171
+ except ValueError as exc:
172
+ raise LocalProjectError(f"Project artifact target escapes the project directory: {path!r}") from exc
173
+ return target
174
+
175
+
176
+ __all__ = [
177
+ "LocalProjectArtifact",
178
+ "artifact_target",
179
+ "canonical_project_upload_payload",
180
+ "file_digest",
181
+ "prepare_project_upload",
182
+ ]