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,365 @@
1
+ """Deterministic, domain-scoped context sharing for project objects.
2
+
3
+ Project namespaces are the source of truth for ownership. This module adds the
4
+ policy boundary around those namespaces so an agent receives an explicit
5
+ projection instead of the complete project object.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from copy import deepcopy
11
+ import re
12
+ from typing import Any, Literal, Mapping
13
+
14
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
15
+
16
+
17
+ CONTEXT_GOVERNANCE_SCHEMA_VERSION = "1.0"
18
+ ContextShareMode = Literal["none", "summary", "full"]
19
+ _NAMESPACE_PATTERN = re.compile(r"^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)+$")
20
+
21
+
22
+ def _normalize_namespace(value: str) -> str:
23
+ normalized = str(value or "").strip().lower()
24
+ if not _NAMESPACE_PATTERN.fullmatch(normalized):
25
+ raise ValueError("Context namespaces must be dotted, for example product.mech.")
26
+ return normalized
27
+
28
+
29
+ class ContextShareRule(BaseModel):
30
+ """One explicit source-to-recipient sharing decision.
31
+
32
+ ``allowed_attributes`` is an allowlist. An empty field list means the
33
+ complete attribute value; it does not mean all attributes are allowed.
34
+ """
35
+
36
+ model_config = ConfigDict(extra="forbid")
37
+
38
+ source_namespace: str
39
+ recipient_namespace: str
40
+ mode: ContextShareMode = "summary"
41
+ allowed_attributes: dict[str, list[str]] = Field(default_factory=dict)
42
+ reason: str = Field(..., min_length=1)
43
+
44
+ @field_validator("source_namespace", "recipient_namespace", mode="before")
45
+ @classmethod
46
+ def normalize_namespaces(cls, value: str) -> str:
47
+ return _normalize_namespace(value)
48
+
49
+ @field_validator("allowed_attributes", mode="before")
50
+ @classmethod
51
+ def normalize_attribute_allowlist(cls, value: Any) -> dict[str, list[str]]:
52
+ if value is None:
53
+ return {}
54
+ if not isinstance(value, Mapping):
55
+ raise ValueError("allowed_attributes must be an object of attribute names to field names.")
56
+ normalized: dict[str, list[str]] = {}
57
+ for attribute, fields in value.items():
58
+ name = str(attribute or "").strip()
59
+ if not name:
60
+ raise ValueError("Context attribute names must not be empty.")
61
+ if fields is None:
62
+ normalized[name] = []
63
+ continue
64
+ if isinstance(fields, str):
65
+ fields = [fields]
66
+ if not isinstance(fields, list):
67
+ raise ValueError(f"Context fields for '{name}' must be a list.")
68
+ normalized[name] = [str(field).strip() for field in fields if str(field).strip()]
69
+ return normalized
70
+
71
+ @model_validator(mode="after")
72
+ def require_grant_for_shared_mode(self) -> "ContextShareRule":
73
+ if self.mode != "none" and not self.allowed_attributes:
74
+ raise ValueError("A shared context rule must declare allowed_attributes.")
75
+ return self
76
+
77
+
78
+ class ContextGovernancePolicy(BaseModel):
79
+ """Versioned allowlist for context handoffs between project agents."""
80
+
81
+ model_config = ConfigDict(extra="forbid")
82
+
83
+ schema_version: Literal["1.0"] = CONTEXT_GOVERNANCE_SCHEMA_VERSION
84
+ default_mode: Literal["none"] = "none"
85
+ rules: list[ContextShareRule] = Field(default_factory=list)
86
+
87
+ @model_validator(mode="after")
88
+ def require_unique_rules(self) -> "ContextGovernancePolicy":
89
+ keys = [(rule.source_namespace, rule.recipient_namespace) for rule in self.rules]
90
+ if len(keys) != len(set(keys)):
91
+ raise ValueError("Context governance rules must have unique source and recipient namespaces.")
92
+ return self
93
+
94
+ def rule_for(self, source_namespace: str, recipient_namespace: str) -> ContextShareRule | None:
95
+ source = _normalize_namespace(source_namespace)
96
+ recipient = _normalize_namespace(recipient_namespace)
97
+ return next(
98
+ (
99
+ rule
100
+ for rule in self.rules
101
+ if rule.source_namespace == source and rule.recipient_namespace == recipient
102
+ ),
103
+ None,
104
+ )
105
+
106
+ def recipient_manifest(self, recipient_namespace: str) -> dict[str, Any]:
107
+ recipient = _normalize_namespace(recipient_namespace)
108
+ return {
109
+ "schema_version": self.schema_version,
110
+ "recipient_namespace": recipient,
111
+ "default_mode": self.default_mode,
112
+ "same_namespace_access": "full",
113
+ "grants": {
114
+ rule.source_namespace: {
115
+ "mode": rule.mode,
116
+ "allowed_attributes": deepcopy(rule.allowed_attributes),
117
+ "reason": rule.reason,
118
+ }
119
+ for rule in self.rules
120
+ if rule.recipient_namespace == recipient and rule.mode != "none"
121
+ },
122
+ }
123
+
124
+
125
+ class ContextProjection(BaseModel):
126
+ """Auditable context passed to one recipient agent."""
127
+
128
+ model_config = ConfigDict(extra="forbid")
129
+
130
+ schema_version: Literal["1.0"] = CONTEXT_GOVERNANCE_SCHEMA_VERSION
131
+ object_id: str
132
+ object_version: int = Field(ge=1)
133
+ recipient_namespace: str
134
+ namespaces: dict[str, dict[str, Any]] = Field(default_factory=dict)
135
+ allowed_sources: list[str] = Field(default_factory=list)
136
+ denied_sources: list[str] = Field(default_factory=list)
137
+ omitted_attributes: dict[str, list[str]] = Field(default_factory=dict)
138
+ policy: dict[str, Any] = Field(default_factory=dict)
139
+
140
+
141
+ def project_context_for_agent(
142
+ project_object: Any,
143
+ recipient_namespace: str,
144
+ *,
145
+ policy: ContextGovernancePolicy | None = None,
146
+ ) -> dict[str, Any]:
147
+ """Return only context permitted for ``recipient_namespace``.
148
+
149
+ The result includes a receipt so downstream workers can record which
150
+ namespaces were allowed or denied. Unknown recipients and missing rules
151
+ are denied; no prompt or model call is involved in this decision.
152
+ """
153
+
154
+ active_policy = policy if policy is not None else DEFAULT_CONTEXT_GOVERNANCE_POLICY
155
+ recipient = _normalize_namespace(recipient_namespace)
156
+ object_id = str(_read(project_object, "object_id") or "")
157
+ object_version = _positive_int(_read(project_object, "version"), default=1)
158
+ raw_namespaces = _read(project_object, "namespaces") or []
159
+
160
+ projected: dict[str, dict[str, Any]] = {}
161
+ allowed_sources: list[str] = []
162
+ denied_sources: list[str] = []
163
+ omitted_attributes: dict[str, list[str]] = {}
164
+ for raw_namespace in raw_namespaces:
165
+ source = str(_read(raw_namespace, "name") or "").strip().lower()
166
+ if not source:
167
+ continue
168
+ payload = _read(raw_namespace, "payload") or {}
169
+ if not isinstance(payload, Mapping):
170
+ payload = {}
171
+
172
+ if source == recipient:
173
+ mode = "full"
174
+ allowed_attributes = {str(key): [] for key in payload}
175
+ else:
176
+ rule = active_policy.rule_for(source, recipient)
177
+ mode = rule.mode if rule else active_policy.default_mode
178
+ allowed_attributes = rule.allowed_attributes if rule else {}
179
+
180
+ if mode == "none":
181
+ denied_sources.append(source)
182
+ omitted_attributes[source] = sorted(str(attribute) for attribute in payload)
183
+ continue
184
+
185
+ selected: dict[str, Any] = {}
186
+ omitted: list[str] = []
187
+ for attribute, fields in allowed_attributes.items():
188
+ if attribute not in payload:
189
+ continue
190
+ if _is_secret_key(attribute):
191
+ omitted.append(attribute)
192
+ continue
193
+ selected[attribute] = _select_fields(payload[attribute], fields)
194
+ omitted.extend(_omitted_paths(attribute, payload[attribute], fields))
195
+ omitted.extend(str(attribute) for attribute in payload if attribute not in allowed_attributes)
196
+ if omitted:
197
+ omitted_attributes[source] = sorted(set(omitted))
198
+ if selected:
199
+ projected[source] = selected
200
+ allowed_sources.append(source)
201
+ else:
202
+ denied_sources.append(source)
203
+
204
+ projection = ContextProjection(
205
+ object_id=object_id,
206
+ object_version=object_version,
207
+ recipient_namespace=recipient,
208
+ namespaces=projected,
209
+ allowed_sources=sorted(set(allowed_sources)),
210
+ denied_sources=sorted(set(denied_sources)),
211
+ omitted_attributes=omitted_attributes,
212
+ policy=active_policy.recipient_manifest(recipient),
213
+ )
214
+ return projection.model_dump(mode="json")
215
+
216
+
217
+ def _read(value: Any, key: str) -> Any:
218
+ if isinstance(value, Mapping):
219
+ return value.get(key)
220
+ return getattr(value, key, None)
221
+
222
+
223
+ def _positive_int(value: Any, *, default: int) -> int:
224
+ try:
225
+ return max(1, int(value))
226
+ except (TypeError, ValueError):
227
+ return default
228
+
229
+
230
+ def _select_fields(value: Any, fields: list[str]) -> Any:
231
+ if not fields:
232
+ return _sanitize(value)
233
+ allowed = set(fields)
234
+ if isinstance(value, Mapping):
235
+ return {
236
+ str(key): _sanitize(item)
237
+ for key, item in value.items()
238
+ if str(key) in allowed and not _is_secret_key(key)
239
+ }
240
+ if isinstance(value, list):
241
+ return [
242
+ {
243
+ str(key): _sanitize(item)
244
+ for key, item in item_value.items()
245
+ if str(key) in allowed and not _is_secret_key(key)
246
+ }
247
+ if isinstance(item_value, Mapping)
248
+ else _sanitize(item_value)
249
+ for item_value in value
250
+ ]
251
+ return _sanitize(value)
252
+
253
+
254
+ def _omitted_paths(prefix: str, value: Any, fields: list[str]) -> list[str]:
255
+ if not fields:
256
+ return []
257
+ allowed = set(fields)
258
+ if isinstance(value, Mapping):
259
+ return [
260
+ f"{prefix}.{key}"
261
+ for key in value
262
+ if str(key) not in allowed or _is_secret_key(key)
263
+ ]
264
+ if isinstance(value, list):
265
+ paths: set[str] = set()
266
+ for item in value:
267
+ if isinstance(item, Mapping):
268
+ paths.update(_omitted_paths(f"{prefix}[]", item, fields))
269
+ return sorted(paths)
270
+ return []
271
+
272
+
273
+ def _sanitize(value: Any) -> Any:
274
+ if isinstance(value, Mapping):
275
+ return {
276
+ str(key): _sanitize(item)
277
+ for key, item in value.items()
278
+ if not _is_secret_key(key)
279
+ }
280
+ if isinstance(value, list):
281
+ return [_sanitize(item) for item in value]
282
+ if isinstance(value, tuple):
283
+ return [_sanitize(item) for item in value]
284
+ if isinstance(value, str) and value.startswith("data:"):
285
+ return f"<redacted inline data: {len(value)} chars>"
286
+ return deepcopy(value)
287
+
288
+
289
+ def _is_secret_key(value: Any) -> bool:
290
+ normalized = str(value).strip().lower().replace("-", "_")
291
+ return normalized in {"key", "credential", "credentials"} or any(
292
+ marker in normalized
293
+ for marker in ("api_key", "apikey", "authorization", "password", "secret", "token")
294
+ )
295
+
296
+
297
+ def _rule(source: str, recipient: str, attributes: dict[str, list[str]], reason: str) -> ContextShareRule:
298
+ return ContextShareRule(
299
+ source_namespace=source,
300
+ recipient_namespace=recipient,
301
+ allowed_attributes=attributes,
302
+ reason=reason,
303
+ )
304
+
305
+
306
+ _SUMMARY_OVERVIEW = {
307
+ "overview": ["title", "description", "difficulty", "estimated_cost", "category"],
308
+ "requirements": ["requirements", "power_needs", "operating_voltage", "physical_constraints", "safety_notes"],
309
+ "constraints": [],
310
+ }
311
+ _COMPONENT_SUMMARY = {
312
+ "components": ["ref_des", "part_definition_id", "part_number", "name", "category", "rationale", "configuration"]
313
+ }
314
+ _NET_SUMMARY = {"nets": ["net_id", "name", "net_type", "voltage", "component_refs"]}
315
+
316
+
317
+ def _default_rules() -> list[ContextShareRule]:
318
+ domain_recipients = (
319
+ "product.architecture",
320
+ "product.electrical",
321
+ "product.bom",
322
+ "product.mech",
323
+ "product.firmware",
324
+ "product.visuals",
325
+ "product.validation",
326
+ "product.assembly",
327
+ )
328
+ rules = [
329
+ _rule("product.overview", recipient, _SUMMARY_OVERVIEW, "Product intent and constraints are shared with every domain specialist.")
330
+ for recipient in domain_recipients
331
+ ]
332
+ rules.extend(
333
+ _rule("product.architecture", recipient, {"system_architecture": []}, "The architecture agent routes the shared system hierarchy.")
334
+ for recipient in domain_recipients
335
+ if recipient != "product.architecture"
336
+ )
337
+ rules.extend([
338
+ _rule("product.electrical", "product.mech", _COMPONENT_SUMMARY, "Mechanical placement needs component identity, not electrical pins."),
339
+ _rule("product.electrical", "product.bom", _COMPONENT_SUMMARY, "BOM planning needs procurement identity, not pin-level data."),
340
+ _rule("product.electrical", "product.firmware", {**_COMPONENT_SUMMARY, "pin_mappings": [], "buses": []}, "Firmware needs hardware interface assignments."),
341
+ _rule("product.electrical", "product.assembly", {**_COMPONENT_SUMMARY, **_NET_SUMMARY}, "Assembly needs build-level connectivity without pin disclosure."),
342
+ _rule("product.electrical", "product.validation", {"part_definitions": [], "components": [], "nets": [], "buses": [], "pin_mappings": [], "power_rails": []}, "Validation owns electrical safety checks and requires the complete electrical state."),
343
+ _rule("product.mech", "product.bom", {"mechanical": [], "fabrication_notes": []}, "BOM planning may use mechanical sourcing and fabrication costs."),
344
+ _rule("product.mech", "product.visuals", {"mechanical": [], "cad_model": [], "fabrication_notes": []}, "Visuals must render the canonical mechanical form rather than inventing it."),
345
+ _rule("product.mech", "product.validation", {"mechanical": [], "fabrication_notes": []}, "Validation checks physical constraints and fabrication risks."),
346
+ _rule("product.mech", "product.assembly", {"mechanical": [], "fabrication_notes": []}, "Assembly needs the canonical mechanical build context."),
347
+ _rule("product.validation", "product.assembly", {"validation": []}, "Assembly must receive safety gates and blocking findings."),
348
+ _rule("product.assembly", "project.docs", {"assembly": []}, "Documentation projects the approved builder-facing sequence."),
349
+ _rule("product.bom", "project.docs", {"bom": []}, "Documentation may publish the approved procurement view."),
350
+ ])
351
+ return rules
352
+
353
+
354
+ DEFAULT_CONTEXT_GOVERNANCE_POLICY = ContextGovernancePolicy(rules=_default_rules())
355
+
356
+
357
+ __all__ = [
358
+ "CONTEXT_GOVERNANCE_SCHEMA_VERSION",
359
+ "ContextGovernancePolicy",
360
+ "ContextProjection",
361
+ "ContextShareMode",
362
+ "ContextShareRule",
363
+ "DEFAULT_CONTEXT_GOVERNANCE_POLICY",
364
+ "project_context_for_agent",
365
+ ]