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,84 @@
1
+ """Electrical domain using the existing pin, net, bus and power contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from pydantic import Field, model_validator
8
+
9
+ from forma_core.domains.base import ComponentView, DomainDocument, DomainModel, Text, unique
10
+ from .primitives import BusConnection, ConnectionNet, PinDefinition, PinMappingEntry, PowerRail
11
+
12
+
13
+ class ElectricalContext(DomainModel):
14
+ """Electrical inputs, deliberately excluding geometry and biological context."""
15
+
16
+ scope: Text
17
+ supply_requirements: list[Text] = Field(min_length=1)
18
+ load_requirements: list[Text] = Field(min_length=1)
19
+ interface_requirements: list[Text] = Field(min_length=1)
20
+
21
+
22
+ class ElectricalPart(DomainModel):
23
+ """Electrical facts for a shared part identity."""
24
+
25
+ part_definition_id: Text
26
+ name: str = ""
27
+ part_number: str = ""
28
+ category: str = "Component"
29
+ pins: list[PinDefinition] = Field(default_factory=list)
30
+ electrical_specs: dict[str, Any] = Field(default_factory=dict)
31
+
32
+
33
+ class ElectricalIR(DomainDocument):
34
+ """Standalone logical electrical design; foundation for issue #17.
35
+
36
+ No PCB geometry, harness routing or certification is implied by validity.
37
+ Stable object IDs are separate from legacy display reference designators.
38
+ """
39
+
40
+ domain: Literal["electrical"] = "electrical"
41
+ schema_version: Literal["1.0"] = "1.0"
42
+ parts: list[ElectricalPart] = Field(default_factory=list)
43
+ components: list[ComponentView] = Field(default_factory=list)
44
+ nets: list[ConnectionNet] = Field(default_factory=list)
45
+ buses: list[BusConnection] = Field(default_factory=list)
46
+ pin_mappings: list[PinMappingEntry] = Field(default_factory=list)
47
+ power_rails: list[PowerRail] = Field(default_factory=list)
48
+ estimated_current_draw_ma: float | None = Field(None, ge=0)
49
+
50
+ @model_validator(mode="after")
51
+ def validate_references(self) -> ElectricalIR:
52
+ """Reject ambiguous identities, dangling endpoints, buses and rail sources."""
53
+ for values, label in [
54
+ ([p.part_definition_id for p in self.parts], "electrical part ID"),
55
+ ([c.object_id for c in self.components], "electrical object ID"),
56
+ ([c.ref_des for c in self.components], "electrical ref_des"),
57
+ ([n.net_id for n in self.nets], "net ID"),
58
+ ([b.bus_id for b in self.buses], "bus ID"),
59
+ ([r.rail_id for r in self.power_rails], "rail ID"),
60
+ ]:
61
+ unique(values, label)
62
+ parts = {p.part_definition_id: p for p in self.parts}
63
+ components = {c.ref_des: c for c in self.components}
64
+ for part in self.parts:
65
+ unique([pin.pin_id for pin in part.pins], "pin ID")
66
+ for component in self.components:
67
+ if component.part_definition_id not in parts:
68
+ raise ValueError(f"Unknown electrical part '{component.part_definition_id}'.")
69
+ for net in self.nets:
70
+ unique([f"{pin.ref_des}:{pin.pin_id}" for pin in net.pins], "net endpoint")
71
+ for pin in net.pins:
72
+ component = components.get(pin.ref_des)
73
+ if component is None:
74
+ raise ValueError(f"Unknown electrical component '{pin.ref_des}'.")
75
+ if pin.pin_id not in {p.pin_id for p in parts[component.part_definition_id].pins}:
76
+ raise ValueError(f"Unknown pin '{pin.ref_des}.{pin.pin_id}'.")
77
+ nets = {n.net_id for n in self.nets}
78
+ for bus in self.buses:
79
+ if any(net not in nets for net in bus.nets):
80
+ raise ValueError(f"Bus '{bus.bus_id}' references an unknown net.")
81
+ for rail in self.power_rails:
82
+ if rail.source_component not in components:
83
+ raise ValueError(f"Rail '{rail.rail_id}' references an unknown source.")
84
+ return self
@@ -0,0 +1,43 @@
1
+ """Existing domain value types, re-exported by the legacy project model."""
2
+
3
+ from typing import Any, List, Literal, Mapping, Optional
4
+ from pydantic import BaseModel, Field, field_validator
5
+
6
+
7
+ class PinDefinition(BaseModel):
8
+ pin_id: str = Field(..., description="Unique pin identifier, e.g., '1', 'GND', 'D13'")
9
+ name: str = Field(..., description="Pin functional name, e.g., 'VCC', 'TX', 'GPIO4'")
10
+ pin_type: str = Field(..., description="Type of pin: Power, Ground, Digital, Analog, I2C, SPI, UART, PWM, Passive")
11
+ voltage: Optional[float] = Field(None, description="Operating voltage of the pin in Volts, e.g., 3.3 or 5.0")
12
+ description: Optional[str] = Field(None, description="Detailed description of the pin function")
13
+ direction: Optional[str] = Field(None, description="Signal direction such as input, output, or bidirectional")
14
+ power_role: Optional[str] = Field(None, description="Power role such as input, source, regulated_output, or return")
15
+ interface: Optional[str] = Field(None, description="Logical interface such as I2C, SPI, UART, PWM, or analog")
16
+
17
+ class PinReference(BaseModel):
18
+ ref_des: str = Field(..., description="Component reference designator, e.g., 'U1'")
19
+ pin_id: str = Field(..., description="Pin ID on the target component, e.g., 'GND' or '12'")
20
+
21
+ class ConnectionNet(BaseModel):
22
+ net_id: str = Field(..., description="Unique ID for the electrical net, e.g., 'NET_VCC', 'NET_I2C_SDA'")
23
+ name: str = Field(..., description="Friendly net name, e.g., '3.3V Power Rail', 'I2C Data'")
24
+ net_type: str = Field(..., description="Net type: Power, Ground, Analog, Digital, I2C, SPI, UART, PWM")
25
+ voltage: Optional[float] = Field(None, description="Expected voltage of this net, e.g., 3.3")
26
+ pins: List[PinReference] = Field(default_factory=list, description="All component pins tied to this net")
27
+
28
+ class PinMappingEntry(BaseModel):
29
+ mcu_pin: str = Field(..., description="MCU pin identifier, e.g., 'GPIO23'")
30
+ connected_to: str = Field(..., description="Name of the sensor pin/function connected, e.g., 'DHT22 Data'")
31
+ net_name: str = Field(..., description="Electrical net name, e.g., 'DHT_SDA_NET'")
32
+
33
+ class BusConnection(BaseModel):
34
+ bus_id: str = Field(..., description="Unique ID for the digital communication bus, e.g., 'BUS_I2C_1'")
35
+ bus_type: str = Field(..., description="Bus type: I2C, SPI, UART, CAN")
36
+ clock_frequency_hz: Optional[float] = Field(None, description="Operating bus speed if applicable")
37
+ nets: List[str] = Field(default_factory=list, description="Electrical net IDs associated with this bus")
38
+
39
+ class PowerRail(BaseModel):
40
+ rail_id: str = Field(..., description="Unique ID for power rail, e.g., 'RAIL_3V3'")
41
+ voltage: float = Field(..., description="Nominal operating voltage in Volts")
42
+ max_current_capacity_ma: float = Field(..., description="Maximum continuous current capacity in mA")
43
+ source_component: str = Field(..., description="Reference designator of the power source component")
@@ -0,0 +1,340 @@
1
+ """Existing low-voltage circuit rules, independent of HardwareIR construction."""
2
+ from __future__ import annotations
3
+ from typing import List, Dict, Set, Optional, Protocol
4
+ from forma_core.electronics.primitives import PinDefinition, ConnectionNet
5
+ from forma_core.domains.diagnostics import ValidationIssue
6
+
7
+ class ComponentInstance(Protocol):
8
+ """Only the component fields consumed by the existing electrical rules."""
9
+ ref_des: str
10
+ name: str
11
+ part_number: str
12
+ category: str
13
+ rationale: str
14
+ pins: list[PinDefinition]
15
+
16
+ class FunctionalRequirements(Protocol):
17
+ """Requirements projection consumed by capability coverage checks."""
18
+ requirements: list[str]
19
+
20
+ REQUIREMENT_CAPABILITIES = (
21
+ ("soil-moisture sensing", ("soil moisture", "soil-moisture"), ("soil moisture", "soil-moisture", "capacitive moisture")),
22
+ ("ambient-light sensing", ("ambient light", "light sensing", "light sensor", "lux"), ("ambient light", "light sensor", "photoresistor", "ldr", "bh1750", "lux sensor")),
23
+ ("temperature sensing", ("temperature",), ("temperature", "dht11", "dht22", "bmp280", "thermistor")),
24
+ ("humidity sensing", ("humidity",), ("humidity", "dht11", "dht22", "bme280")),
25
+ ("distance sensing", ("distance", "proximity", "ultrasonic"), ("distance", "ultrasonic", "hc-sr04", "vl53")),
26
+ ("motion sensing", ("motion sensing", "accelerometer", "gyroscope", "imu"), ("motion", "accelerometer", "gyroscope", "mpu6050", "imu")),
27
+ ("pressure sensing", ("barometric", "air pressure", "pressure sensor"), ("barometric", "pressure", "bmp280", "bme280")),
28
+ ("visual display", ("display", "oled", "lcd", "screen"), ("display", "oled", "lcd", "ssd1306")),
29
+ ("audible alert", ("buzzer", "audible alert", "beeper", "speaker"), ("buzzer", "piezo", "speaker", "beeper")),
30
+ ("status LED", ("status led", "indicator led"), (" led", "led-", "status indicator")),
31
+ ("220-ohm current limiting", ("220-ohm", "220 ohm", "220r"), ("220 ohm", "220r", "resistor-220")),
32
+ ("10k pull-up resistance", ("10k pull-up", "10k pull up", "10k resistor"), ("10k ohm", "resistor-10k")),
33
+ ("servo actuation", ("servo",), ("servo", "sg90")),
34
+ ("relay switching", ("relay",), ("relay",)),
35
+ ("USB-C connectivity", ("usb-c", "usb c", "type-c", "type c"), ("usb-c", "usb c", "type-c", "type c")),
36
+ )
37
+
38
+
39
+ def validate_requirement_coverage(
40
+ requirements: Optional[FunctionalRequirements],
41
+ components: List[ComponentInstance],
42
+ *,
43
+ prompt: str = "",
44
+ ) -> List[ValidationIssue]:
45
+ """Report requested hardware capabilities that have no matching BOM component."""
46
+ if requirements is None and not prompt.strip():
47
+ return []
48
+ requirement_text = " ".join(
49
+ [prompt, *((requirements.requirements if requirements else []) or [])]
50
+ ).lower()
51
+ component_text = " ".join(
52
+ f" {component.part_number} {component.name} {component.category} {component.rationale} "
53
+ for component in components
54
+ ).lower()
55
+ issues: List[ValidationIssue] = []
56
+ for label, request_phrases, component_phrases in REQUIREMENT_CAPABILITIES:
57
+ if not any(phrase in requirement_text for phrase in request_phrases):
58
+ continue
59
+ if any(phrase in component_text for phrase in component_phrases):
60
+ continue
61
+ issues.append(ValidationIssue(
62
+ severity="WARNING",
63
+ category="Requirement Coverage",
64
+ description=f"The project requests {label}, but the selected BOM has no component that provides it.",
65
+ troubleshooting=(
66
+ f"Add a catalog component that provides {label}, or explicitly mark this requirement as unsupported "
67
+ "instead of presenting the design as complete."
68
+ ),
69
+ ))
70
+ return issues
71
+
72
+
73
+ def validate_circuit(
74
+ components: List[ComponentInstance],
75
+ nets: List[ConnectionNet],
76
+ requirements: Optional[FunctionalRequirements] = None,
77
+ *,
78
+ prompt: str = "",
79
+ ) -> List[ValidationIssue]:
80
+ """
81
+ Runs automated electrical and logical validation checks on the structured Hardware Intermediate Representation netlist.
82
+ Returns a list of ValidationIssues (Errors and Warnings) with troubleshooting advice.
83
+ """
84
+ issues: List[ValidationIssue] = validate_requirement_coverage(requirements, components, prompt=prompt)
85
+
86
+ # Mechanical BOM items have no electrical terminals. Unknown categories are
87
+ # not an exemption: an unmodelled module cannot be electrically verified.
88
+ mechanical_categories = {"mechanical", "enclosure", "fastener", "fasteners", "structural", "3d print"}
89
+ electrical_components = [
90
+ comp for comp in components
91
+ if comp.pins or comp.category.strip().lower() not in mechanical_categories
92
+ ]
93
+ for comp in electrical_components:
94
+ if not comp.pins:
95
+ issues.append(ValidationIssue(
96
+ severity="CRITICAL",
97
+ category="Missing Pin Definitions",
98
+ description=f"Component '{comp.name}' ({comp.ref_des}) has no declared electrical pins and cannot be validated.",
99
+ troubleshooting="Declare the part's physical terminals, including module power and interface connections. Use a mechanical category only for non-electrical parts.",
100
+ ))
101
+ if electrical_components and not nets:
102
+ issues.append(ValidationIssue(
103
+ severity="CRITICAL",
104
+ category="Missing Electrical Nets",
105
+ description="The project contains electrical components but no electrical netlist.",
106
+ troubleshooting="Define the actual power, ground, and signal connections. Power-rail descriptions and assembly instructions do not replace a netlist.",
107
+ ))
108
+
109
+ # Pre-index component pin attributes for fast lookup
110
+ # key: (ref_des, pin_id) -> PinDefinition
111
+ pin_lookup: Dict[tuple, PinDefinition] = {}
112
+ component_lookup: Dict[str, ComponentInstance] = {}
113
+
114
+ for comp in components:
115
+ component_lookup[comp.ref_des] = comp
116
+ for pin in comp.pins:
117
+ pin_lookup[(comp.ref_des, pin.pin_id)] = pin
118
+
119
+ # Reject malformed endpoints before applying electrical rules. This keeps
120
+ # provider hallucinations and duplicate references visible instead of
121
+ # silently omitting them from the pin lookup below.
122
+ for net in nets:
123
+ if not net.pins:
124
+ issues.append(ValidationIssue(
125
+ severity="CRITICAL",
126
+ category="Empty Net",
127
+ description=f"Net '{net.name}' ({net.net_id}) contains no endpoints.",
128
+ troubleshooting="Add at least one declared component pin or remove the empty net.",
129
+ ))
130
+ seen_endpoints: set[tuple[str, str]] = set()
131
+ for pin_ref in net.pins:
132
+ endpoint = (pin_ref.ref_des, pin_ref.pin_id)
133
+ if endpoint in seen_endpoints:
134
+ issues.append(ValidationIssue(
135
+ severity="CRITICAL",
136
+ category="Duplicate Endpoint",
137
+ description=(
138
+ f"Endpoint '{pin_ref.ref_des}.{pin_ref.pin_id}' appears more than once "
139
+ f"in net '{net.net_id}'."
140
+ ),
141
+ troubleshooting="List each physical endpoint at most once per net.",
142
+ ))
143
+ seen_endpoints.add(endpoint)
144
+ if pin_ref.ref_des not in component_lookup:
145
+ issues.append(ValidationIssue(
146
+ severity="CRITICAL",
147
+ category="Unknown Component Reference",
148
+ description=(
149
+ f"Net '{net.net_id}' references unknown component "
150
+ f"'{pin_ref.ref_des}'."
151
+ ),
152
+ troubleshooting="Choose a component reference declared in the project BOM.",
153
+ ))
154
+ elif endpoint not in pin_lookup:
155
+ issues.append(ValidationIssue(
156
+ severity="CRITICAL",
157
+ category="Unknown Pin Reference",
158
+ description=(
159
+ f"Net '{net.net_id}' references undeclared pin "
160
+ f"'{pin_ref.pin_id}' on component '{pin_ref.ref_des}'."
161
+ ),
162
+ troubleshooting="Choose a pin declared by the component's shared part definition.",
163
+ ))
164
+
165
+ # Pin to Nets reverse lookup to find pin conflict issues
166
+ # key: (ref_des, pin_id) -> List of net_ids
167
+ pin_to_nets: Dict[tuple, List[str]] = {}
168
+ for net in nets:
169
+ for pin_ref in net.pins:
170
+ key = (pin_ref.ref_des, pin_ref.pin_id)
171
+ if key not in pin_to_nets:
172
+ pin_to_nets[key] = []
173
+ pin_to_nets[key].append(net.net_id)
174
+
175
+ # ----------------------------------------------------
176
+ # Rule 1: Short Circuit Checker (Power directly to Ground)
177
+ # ----------------------------------------------------
178
+ for net in nets:
179
+ has_power = False
180
+ has_ground = False
181
+ power_pins = []
182
+ ground_pins = []
183
+
184
+ for pin_ref in net.pins:
185
+ pin = pin_lookup.get((pin_ref.ref_des, pin_ref.pin_id))
186
+ if pin:
187
+ if pin.pin_type.lower() == "power":
188
+ has_power = True
189
+ power_pins.append(f"{pin_ref.ref_des}.{pin_ref.pin_id}")
190
+ elif pin.pin_type.lower() == "ground":
191
+ has_ground = True
192
+ ground_pins.append(f"{pin_ref.ref_des}.{pin_ref.pin_id}")
193
+
194
+ if has_power and has_ground:
195
+ issues.append(ValidationIssue(
196
+ severity="CRITICAL",
197
+ category="Short Circuit",
198
+ description=f"Direct electrical short detected in net '{net.name}' ({net.net_id}). "
199
+ f"Power pins [{', '.join(power_pins)}] are connected directly to Ground pins [{', '.join(ground_pins)}].",
200
+ troubleshooting="Separate the power rail connections from the ground reference rail. Power pins must only connect to other power nodes, never directly to GND."
201
+ ))
202
+
203
+ # ----------------------------------------------------
204
+ # Rule 2: Voltage Mismatch Checker
205
+ # ----------------------------------------------------
206
+ for net in nets:
207
+ voltages: Set[float] = set()
208
+ connected_pins = []
209
+
210
+ for pin_ref in net.pins:
211
+ pin = pin_lookup.get((pin_ref.ref_des, pin_ref.pin_id))
212
+ if pin and pin.voltage is not None:
213
+ # Store pin name and operating voltage
214
+ voltages.add(pin.voltage)
215
+ connected_pins.append(f"{pin_ref.ref_des}.{pin_ref.pin_id} ({pin.voltage}V)")
216
+
217
+ # If we have multiple different positive voltages on the same signal rail
218
+ if len(voltages) > 1:
219
+ max_v = max(voltages)
220
+ min_v = min(voltages)
221
+ # If the difference is significant (e.g. 5.0V and 3.3V on the same net)
222
+ if max_v - min_v > 0.5:
223
+ issues.append(ValidationIssue(
224
+ severity="WARNING",
225
+ category="Voltage Mismatch",
226
+ description=f"Potential voltage mismatch in net '{net.name}' ({net.net_id}). "
227
+ f"Pins with different voltages are connected on the same net: {', '.join(connected_pins)}.",
228
+ troubleshooting=f"Use an active level-shifter (e.g., TXB0104) to bridge logic between {min_v}V and {max_v}V lines, or use a component operating at compatible voltages."
229
+ ))
230
+
231
+ # ----------------------------------------------------
232
+ # Rule 3: Floating / Unpowered IC Check
233
+ # ----------------------------------------------------
234
+ # Identify which components are active ICs (MCUs, Sensors, Actuators, Displays)
235
+ for ref_des, comp in component_lookup.items():
236
+ if comp.category.lower() in ["microcontroller", "sensor", "display", "actuator"]:
237
+ # Check if this component has power & ground pins and if they are connected
238
+ has_power_pin = False
239
+ has_ground_pin = False
240
+ power_connected = False
241
+ ground_connected = False
242
+
243
+ p_pin_ids = []
244
+ g_pin_ids = []
245
+
246
+ for pin in comp.pins:
247
+ if pin.pin_type.lower() == "power":
248
+ has_power_pin = True
249
+ p_pin_ids.append(pin.pin_id)
250
+ # Check if this specific pin is in any net
251
+ if (ref_des, pin.pin_id) in pin_to_nets:
252
+ power_connected = True
253
+ elif pin.pin_type.lower() == "ground":
254
+ has_ground_pin = True
255
+ g_pin_ids.append(pin.pin_id)
256
+ if (ref_des, pin.pin_id) in pin_to_nets:
257
+ ground_connected = True
258
+
259
+ # If it has pins but they're not connected
260
+ if has_power_pin and not power_connected:
261
+ issues.append(ValidationIssue(
262
+ severity="CRITICAL",
263
+ category="Unpowered IC",
264
+ description=f"Active component '{comp.name}' ({ref_des}) is unpowered. "
265
+ f"None of its power pins [{', '.join(p_pin_ids)}] are connected to an active power net.",
266
+ troubleshooting=f"Connect one of the VCC/Power pins on {ref_des} to the main power rail (e.g., 3.3V or 5V net)."
267
+ ))
268
+ if has_ground_pin and not ground_connected:
269
+ issues.append(ValidationIssue(
270
+ severity="CRITICAL",
271
+ category="Unpowered IC",
272
+ description=f"Active component '{comp.name}' ({ref_des}) has no ground reference. "
273
+ f"None of its ground pins [{', '.join(g_pin_ids)}] are tied to the GND net.",
274
+ troubleshooting=f"Connect the GND/Ground pin on {ref_des} to the common system Ground net (GND)."
275
+ ))
276
+
277
+ # ----------------------------------------------------
278
+ # Rule 4: Pin Reuse Confli
279
+ # ----------------------------------------------------
280
+ for (ref_des, pin_id), net_ids in pin_to_nets.items():
281
+ # Exclude passive/power/ground buses which naturally share pins
282
+ pin = pin_lookup.get((ref_des, pin_id))
283
+ if pin and pin.pin_type.lower() not in ["power", "ground", "passive"]:
284
+ if len(net_ids) > 1:
285
+ comp = component_lookup.get(ref_des)
286
+ comp_name = comp.name if comp else ref_des
287
+ issues.append(ValidationIssue(
288
+ severity="CRITICAL",
289
+ category="Pin Conflict",
290
+ description=f"Pin reuse conflict detected! Pin '{pin_id}' on '{comp_name}' ({ref_des}) "
291
+ f"is connected to multiple independent signal nets: {', '.join(net_ids)}.",
292
+ troubleshooting=f"Reassign pin '{pin_id}' to only belong to a single signal net. Signal pins cannot be shared directly across separate signal/communication lines."
293
+ ))
294
+
295
+ # ----------------------------------------------------
296
+ # Rule 5: Over-Current Warn Check (Power-Hungry Actuators)
297
+ # ----------------------------------------------------
298
+ has_mcu = False
299
+ mcu_ref = None
300
+ high_draw_actuator_refs: Dict[str, str] = {}
301
+
302
+ for ref_des, comp in component_lookup.items():
303
+ if comp.category.lower() == "microcontroller":
304
+ has_mcu = True
305
+ mcu_ref = ref_des
306
+ else:
307
+ component_text = f"{comp.name} {comp.part_number}".lower()
308
+ is_high_draw_actuator = (
309
+ comp.part_number in ["Relay-5V-1Ch", "SG90-Servo"]
310
+ or any(keyword in component_text for keyword in ["relay", "servo", "motor", "pump"])
311
+ )
312
+ if is_high_draw_actuator:
313
+ high_draw_actuator_refs[ref_des] = f"{comp.name} ({ref_des})"
314
+
315
+ if has_mcu and high_draw_actuator_refs:
316
+ for net in nets:
317
+ if net.net_type.lower() != "power" or net.voltage != 3.3:
318
+ continue
319
+
320
+ contains_mcu_power_pin = False
321
+ powered_actuators = []
322
+ for pin_ref in net.pins:
323
+ pin = pin_lookup.get((pin_ref.ref_des, pin_ref.pin_id))
324
+ if not pin or pin.pin_type.lower() != "power":
325
+ continue
326
+ if pin_ref.ref_des == mcu_ref:
327
+ contains_mcu_power_pin = True
328
+ elif pin_ref.ref_des in high_draw_actuator_refs:
329
+ powered_actuators.append(high_draw_actuator_refs[pin_ref.ref_des])
330
+
331
+ if contains_mcu_power_pin and powered_actuators:
332
+ issues.append(ValidationIssue(
333
+ severity="WARNING",
334
+ category="Overcurrent Risk",
335
+ description=f"High-power actuator(s) [{', '.join(powered_actuators)}] are powered from the same 3.3V low-current output "
336
+ f"net '{net.name}' as the MCU ({mcu_ref}). Relays and servo motors draw peak currents that can crash the microcontroller or burn out its internal voltage regulator.",
337
+ troubleshooting="Isolate the actuator power. Connect the servo/relay power pin to a dedicated 5V input rail or external power source, sharing only the ground reference (GND) with the MCU."
338
+ ))
339
+
340
+ return issues