agent_os_kernel 3.1.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 (337) hide show
  1. agent_control_plane/__init__.py +662 -0
  2. agent_control_plane/a2a_adapter.py +543 -0
  3. agent_control_plane/adapter.py +417 -0
  4. agent_control_plane/agent_hibernation.py +394 -0
  5. agent_control_plane/agent_kernel.py +470 -0
  6. agent_control_plane/compliance.py +720 -0
  7. agent_control_plane/constraint_graphs.py +478 -0
  8. agent_control_plane/control_plane.py +854 -0
  9. agent_control_plane/example_executors.py +195 -0
  10. agent_control_plane/execution_engine.py +231 -0
  11. agent_control_plane/flight_recorder.py +846 -0
  12. agent_control_plane/governance_layer.py +435 -0
  13. agent_control_plane/hf_utils.py +563 -0
  14. agent_control_plane/interfaces/__init__.py +55 -0
  15. agent_control_plane/interfaces/kernel_interface.py +361 -0
  16. agent_control_plane/interfaces/plugin_interface.py +497 -0
  17. agent_control_plane/interfaces/protocol_interfaces.py +387 -0
  18. agent_control_plane/kernel_space.py +1009 -0
  19. agent_control_plane/langchain_adapter.py +424 -0
  20. agent_control_plane/lifecycle.py +3113 -0
  21. agent_control_plane/mcp_adapter.py +653 -0
  22. agent_control_plane/ml_safety.py +563 -0
  23. agent_control_plane/multimodal.py +727 -0
  24. agent_control_plane/mute_agent.py +422 -0
  25. agent_control_plane/observability.py +787 -0
  26. agent_control_plane/orchestrator.py +482 -0
  27. agent_control_plane/plugin_registry.py +750 -0
  28. agent_control_plane/policy_engine.py +954 -0
  29. agent_control_plane/process_isolation.py +777 -0
  30. agent_control_plane/shadow_mode.py +310 -0
  31. agent_control_plane/signals.py +493 -0
  32. agent_control_plane/supervisor_agents.py +430 -0
  33. agent_control_plane/time_travel_debugger.py +557 -0
  34. agent_control_plane/tool_registry.py +452 -0
  35. agent_control_plane/vfs.py +697 -0
  36. agent_kernel/__init__.py +69 -0
  37. agent_kernel/analyzer.py +435 -0
  38. agent_kernel/auditor.py +36 -0
  39. agent_kernel/completeness_auditor.py +237 -0
  40. agent_kernel/detector.py +203 -0
  41. agent_kernel/kernel.py +744 -0
  42. agent_kernel/memory_manager.py +85 -0
  43. agent_kernel/models.py +374 -0
  44. agent_kernel/nudge_mechanism.py +263 -0
  45. agent_kernel/outcome_analyzer.py +338 -0
  46. agent_kernel/patcher.py +582 -0
  47. agent_kernel/semantic_analyzer.py +316 -0
  48. agent_kernel/semantic_purge.py +349 -0
  49. agent_kernel/simulator.py +449 -0
  50. agent_kernel/teacher.py +85 -0
  51. agent_kernel/triage.py +152 -0
  52. agent_os/__init__.py +409 -0
  53. agent_os/_adversarial_impl.py +200 -0
  54. agent_os/_circuit_breaker_impl.py +232 -0
  55. agent_os/_mcp_metrics.py +193 -0
  56. agent_os/adversarial.py +20 -0
  57. agent_os/agents_compat.py +490 -0
  58. agent_os/audit_logger.py +135 -0
  59. agent_os/base_agent.py +651 -0
  60. agent_os/circuit_breaker.py +34 -0
  61. agent_os/cli/__init__.py +659 -0
  62. agent_os/cli/cmd_audit.py +128 -0
  63. agent_os/cli/cmd_init.py +152 -0
  64. agent_os/cli/cmd_policy.py +41 -0
  65. agent_os/cli/cmd_policy_gen.py +180 -0
  66. agent_os/cli/cmd_validate.py +258 -0
  67. agent_os/cli/mcp_scan.py +265 -0
  68. agent_os/cli/output.py +192 -0
  69. agent_os/cli/policy_checker.py +330 -0
  70. agent_os/compat.py +74 -0
  71. agent_os/constraint_graph.py +234 -0
  72. agent_os/content_governance.py +140 -0
  73. agent_os/context_budget.py +305 -0
  74. agent_os/credential_redactor.py +224 -0
  75. agent_os/diff_policy.py +89 -0
  76. agent_os/egress_policy.py +159 -0
  77. agent_os/escalation.py +276 -0
  78. agent_os/event_bus.py +124 -0
  79. agent_os/exceptions.py +180 -0
  80. agent_os/execution_context_policy.py +141 -0
  81. agent_os/github_enterprise.py +96 -0
  82. agent_os/health.py +20 -0
  83. agent_os/integrations/__init__.py +279 -0
  84. agent_os/integrations/a2a_adapter.py +279 -0
  85. agent_os/integrations/agent_lightning/__init__.py +30 -0
  86. agent_os/integrations/anthropic_adapter.py +420 -0
  87. agent_os/integrations/autogen_adapter.py +620 -0
  88. agent_os/integrations/base.py +1137 -0
  89. agent_os/integrations/compat.py +229 -0
  90. agent_os/integrations/config.py +98 -0
  91. agent_os/integrations/conversation_guardian.py +957 -0
  92. agent_os/integrations/crewai_adapter.py +467 -0
  93. agent_os/integrations/drift_detector.py +425 -0
  94. agent_os/integrations/dry_run.py +124 -0
  95. agent_os/integrations/escalation.py +582 -0
  96. agent_os/integrations/gemini_adapter.py +364 -0
  97. agent_os/integrations/google_adk_adapter.py +633 -0
  98. agent_os/integrations/guardrails_adapter.py +394 -0
  99. agent_os/integrations/health.py +197 -0
  100. agent_os/integrations/langchain_adapter.py +654 -0
  101. agent_os/integrations/llamafirewall.py +343 -0
  102. agent_os/integrations/llamaindex_adapter.py +188 -0
  103. agent_os/integrations/logging.py +191 -0
  104. agent_os/integrations/maf_adapter.py +631 -0
  105. agent_os/integrations/mistral_adapter.py +365 -0
  106. agent_os/integrations/openai_adapter.py +816 -0
  107. agent_os/integrations/openai_agents_sdk.py +406 -0
  108. agent_os/integrations/policy_compose.py +171 -0
  109. agent_os/integrations/profiling.py +144 -0
  110. agent_os/integrations/pydantic_ai_adapter.py +420 -0
  111. agent_os/integrations/rate_limiter.py +130 -0
  112. agent_os/integrations/rbac.py +143 -0
  113. agent_os/integrations/registry.py +113 -0
  114. agent_os/integrations/scope_guard.py +303 -0
  115. agent_os/integrations/semantic_kernel_adapter.py +769 -0
  116. agent_os/integrations/smolagents_adapter.py +629 -0
  117. agent_os/integrations/templates.py +178 -0
  118. agent_os/integrations/token_budget.py +134 -0
  119. agent_os/integrations/tool_aliases.py +190 -0
  120. agent_os/integrations/webhooks.py +177 -0
  121. agent_os/lite.py +208 -0
  122. agent_os/mcp_gateway.py +385 -0
  123. agent_os/mcp_message_signer.py +273 -0
  124. agent_os/mcp_protocols.py +161 -0
  125. agent_os/mcp_response_scanner.py +232 -0
  126. agent_os/mcp_security.py +924 -0
  127. agent_os/mcp_session_auth.py +231 -0
  128. agent_os/mcp_sliding_rate_limiter.py +184 -0
  129. agent_os/memory_guard.py +409 -0
  130. agent_os/metrics.py +134 -0
  131. agent_os/mute.py +428 -0
  132. agent_os/mute_agent.py +209 -0
  133. agent_os/policies/__init__.py +77 -0
  134. agent_os/policies/async_evaluator.py +275 -0
  135. agent_os/policies/backends.py +670 -0
  136. agent_os/policies/bridge.py +169 -0
  137. agent_os/policies/budget.py +85 -0
  138. agent_os/policies/cli.py +294 -0
  139. agent_os/policies/conflict_resolution.py +270 -0
  140. agent_os/policies/data_classification.py +252 -0
  141. agent_os/policies/evaluator.py +239 -0
  142. agent_os/policies/policy_schema.json +228 -0
  143. agent_os/policies/rate_limiting.py +145 -0
  144. agent_os/policies/schema.py +115 -0
  145. agent_os/policies/shared.py +331 -0
  146. agent_os/prompt_injection.py +694 -0
  147. agent_os/providers.py +182 -0
  148. agent_os/py.typed +0 -0
  149. agent_os/retry.py +81 -0
  150. agent_os/reversibility.py +251 -0
  151. agent_os/sandbox.py +432 -0
  152. agent_os/sandbox_provider.py +140 -0
  153. agent_os/secure_codegen.py +525 -0
  154. agent_os/security_skills.py +538 -0
  155. agent_os/semantic_policy.py +422 -0
  156. agent_os/server/__init__.py +15 -0
  157. agent_os/server/__main__.py +25 -0
  158. agent_os/server/app.py +277 -0
  159. agent_os/server/models.py +104 -0
  160. agent_os/shift_left_metrics.py +130 -0
  161. agent_os/stateless.py +742 -0
  162. agent_os/supervisor.py +148 -0
  163. agent_os/task_outcome.py +148 -0
  164. agent_os/transparency.py +181 -0
  165. agent_os/trust_root.py +128 -0
  166. agent_os_kernel-3.1.0.dist-info/METADATA +1269 -0
  167. agent_os_kernel-3.1.0.dist-info/RECORD +337 -0
  168. agent_os_kernel-3.1.0.dist-info/WHEEL +4 -0
  169. agent_os_kernel-3.1.0.dist-info/entry_points.txt +2 -0
  170. agent_os_kernel-3.1.0.dist-info/licenses/LICENSE +21 -0
  171. agent_os_observability/__init__.py +27 -0
  172. agent_os_observability/dashboards.py +898 -0
  173. agent_os_observability/metrics.py +398 -0
  174. agent_os_observability/server.py +223 -0
  175. agent_os_observability/tracer.py +232 -0
  176. agent_primitives/__init__.py +24 -0
  177. agent_primitives/failures.py +84 -0
  178. agent_primitives/py.typed +0 -0
  179. amb_core/__init__.py +177 -0
  180. amb_core/adapters/__init__.py +57 -0
  181. amb_core/adapters/aws_sqs_broker.py +376 -0
  182. amb_core/adapters/azure_servicebus_broker.py +340 -0
  183. amb_core/adapters/kafka_broker.py +260 -0
  184. amb_core/adapters/nats_broker.py +285 -0
  185. amb_core/adapters/rabbitmq_broker.py +235 -0
  186. amb_core/adapters/redis_broker.py +262 -0
  187. amb_core/broker.py +145 -0
  188. amb_core/bus.py +481 -0
  189. amb_core/cloudevents.py +509 -0
  190. amb_core/dlq.py +345 -0
  191. amb_core/hf_utils.py +536 -0
  192. amb_core/memory_broker.py +410 -0
  193. amb_core/models.py +141 -0
  194. amb_core/persistence.py +529 -0
  195. amb_core/schema.py +294 -0
  196. amb_core/tracing.py +358 -0
  197. atr/__init__.py +640 -0
  198. atr/access.py +348 -0
  199. atr/composition.py +645 -0
  200. atr/decorator.py +357 -0
  201. atr/executor.py +384 -0
  202. atr/health.py +557 -0
  203. atr/hf_utils.py +449 -0
  204. atr/injection.py +422 -0
  205. atr/metrics.py +440 -0
  206. atr/policies.py +403 -0
  207. atr/py.typed +2 -0
  208. atr/registry.py +452 -0
  209. atr/schema.py +480 -0
  210. atr/tools/safe/__init__.py +75 -0
  211. atr/tools/safe/calculator.py +467 -0
  212. atr/tools/safe/datetime_tool.py +443 -0
  213. atr/tools/safe/file_reader.py +402 -0
  214. atr/tools/safe/http_client.py +316 -0
  215. atr/tools/safe/json_parser.py +374 -0
  216. atr/tools/safe/text_tool.py +537 -0
  217. atr/tools/safe/toolkit.py +175 -0
  218. caas/__init__.py +162 -0
  219. caas/api/__init__.py +7 -0
  220. caas/api/server.py +1328 -0
  221. caas/caching.py +834 -0
  222. caas/cli.py +210 -0
  223. caas/conversation.py +223 -0
  224. caas/decay.py +72 -0
  225. caas/detection/__init__.py +9 -0
  226. caas/detection/detector.py +238 -0
  227. caas/enrichment.py +130 -0
  228. caas/gateway/__init__.py +27 -0
  229. caas/gateway/trust_gateway.py +474 -0
  230. caas/hf_utils.py +479 -0
  231. caas/ingestion/__init__.py +23 -0
  232. caas/ingestion/processors.py +253 -0
  233. caas/ingestion/structure_parser.py +188 -0
  234. caas/models.py +356 -0
  235. caas/pragmatic_truth.py +444 -0
  236. caas/routing/__init__.py +10 -0
  237. caas/routing/heuristic_router.py +58 -0
  238. caas/storage/__init__.py +9 -0
  239. caas/storage/store.py +389 -0
  240. caas/triad.py +213 -0
  241. caas/tuning/__init__.py +9 -0
  242. caas/tuning/tuner.py +329 -0
  243. caas/vfs/__init__.py +14 -0
  244. caas/vfs/filesystem.py +452 -0
  245. cmvk/__init__.py +218 -0
  246. cmvk/audit.py +402 -0
  247. cmvk/benchmarks.py +478 -0
  248. cmvk/constitutional.py +904 -0
  249. cmvk/hf_utils.py +301 -0
  250. cmvk/metrics.py +473 -0
  251. cmvk/profiles.py +300 -0
  252. cmvk/py.typed +0 -0
  253. cmvk/types.py +12 -0
  254. cmvk/verification.py +956 -0
  255. emk/__init__.py +89 -0
  256. emk/causal.py +352 -0
  257. emk/hf_utils.py +421 -0
  258. emk/indexer.py +83 -0
  259. emk/py.typed +0 -0
  260. emk/schema.py +204 -0
  261. emk/sleep_cycle.py +347 -0
  262. emk/store.py +281 -0
  263. iatp/__init__.py +166 -0
  264. iatp/attestation.py +461 -0
  265. iatp/cli.py +317 -0
  266. iatp/hf_utils.py +472 -0
  267. iatp/ipc_pipes.py +580 -0
  268. iatp/main.py +412 -0
  269. iatp/models/__init__.py +447 -0
  270. iatp/policy_engine.py +337 -0
  271. iatp/py.typed +2 -0
  272. iatp/recovery.py +321 -0
  273. iatp/security/__init__.py +270 -0
  274. iatp/sidecar/__init__.py +519 -0
  275. iatp/telemetry/__init__.py +164 -0
  276. iatp/tests/__init__.py +1 -0
  277. iatp/tests/test_attestation.py +370 -0
  278. iatp/tests/test_cli.py +131 -0
  279. iatp/tests/test_ed25519_attestation.py +211 -0
  280. iatp/tests/test_models.py +130 -0
  281. iatp/tests/test_policy_engine.py +347 -0
  282. iatp/tests/test_recovery.py +281 -0
  283. iatp/tests/test_security.py +222 -0
  284. iatp/tests/test_sidecar.py +167 -0
  285. iatp/tests/test_telemetry.py +175 -0
  286. mcp_kernel_server/__init__.py +28 -0
  287. mcp_kernel_server/cli.py +274 -0
  288. mcp_kernel_server/resources.py +217 -0
  289. mcp_kernel_server/server.py +564 -0
  290. mcp_kernel_server/tools.py +1174 -0
  291. mute_agent/__init__.py +68 -0
  292. mute_agent/core/__init__.py +1 -0
  293. mute_agent/core/execution_agent.py +166 -0
  294. mute_agent/core/handshake_protocol.py +201 -0
  295. mute_agent/core/reasoning_agent.py +238 -0
  296. mute_agent/knowledge_graph/__init__.py +1 -0
  297. mute_agent/knowledge_graph/graph_elements.py +65 -0
  298. mute_agent/knowledge_graph/multidimensional_graph.py +170 -0
  299. mute_agent/knowledge_graph/subgraph.py +224 -0
  300. mute_agent/listener/__init__.py +43 -0
  301. mute_agent/listener/adapters/__init__.py +31 -0
  302. mute_agent/listener/adapters/base_adapter.py +189 -0
  303. mute_agent/listener/adapters/caas_adapter.py +344 -0
  304. mute_agent/listener/adapters/control_plane_adapter.py +436 -0
  305. mute_agent/listener/adapters/iatp_adapter.py +332 -0
  306. mute_agent/listener/adapters/scak_adapter.py +251 -0
  307. mute_agent/listener/listener.py +610 -0
  308. mute_agent/listener/state_observer.py +436 -0
  309. mute_agent/listener/threshold_config.py +313 -0
  310. mute_agent/super_system/__init__.py +1 -0
  311. mute_agent/super_system/router.py +204 -0
  312. mute_agent/visualization/__init__.py +10 -0
  313. mute_agent/visualization/graph_debugger.py +502 -0
  314. nexus/README.md +60 -0
  315. nexus/__init__.py +51 -0
  316. nexus/arbiter.py +359 -0
  317. nexus/client.py +466 -0
  318. nexus/dmz.py +444 -0
  319. nexus/escrow.py +430 -0
  320. nexus/exceptions.py +286 -0
  321. nexus/pyproject.toml +36 -0
  322. nexus/registry.py +393 -0
  323. nexus/reputation.py +425 -0
  324. nexus/schemas/__init__.py +51 -0
  325. nexus/schemas/compliance.py +276 -0
  326. nexus/schemas/escrow.py +251 -0
  327. nexus/schemas/manifest.py +225 -0
  328. nexus/schemas/receipt.py +208 -0
  329. nexus/tests/__init__.py +0 -0
  330. nexus/tests/conftest.py +146 -0
  331. nexus/tests/test_arbiter.py +192 -0
  332. nexus/tests/test_dmz.py +194 -0
  333. nexus/tests/test_escrow.py +276 -0
  334. nexus/tests/test_exceptions.py +225 -0
  335. nexus/tests/test_registry.py +232 -0
  336. nexus/tests/test_reputation.py +328 -0
  337. nexus/tests/test_schemas.py +295 -0
@@ -0,0 +1,720 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ """
4
+ Compliance and Regulatory Framework
5
+
6
+ This module provides compliance mechanisms for various regulatory frameworks
7
+ including EU AI Act, SOC 2, FedRAMP, GDPR, and industry-specific regulations.
8
+
9
+ Research Foundations:
10
+ - EU AI Act (2024) - Risk-based classification and requirements
11
+ - SOC 2 Trust Service Criteria - Security, availability, confidentiality
12
+ - FedRAMP requirements for cloud service authorization
13
+ - GDPR Article 22 - Automated decision-making and profiling
14
+ - "Compliance by Design for AI Systems" (IEEE, 2024)
15
+ - Constitutional AI from Anthropic research
16
+
17
+ See docs/RESEARCH_FOUNDATION.md for complete references.
18
+ """
19
+
20
+ from typing import Any, Dict, List, Optional, Callable
21
+ from dataclasses import dataclass, field
22
+ from enum import Enum
23
+ from datetime import datetime, timedelta
24
+ import json
25
+
26
+
27
+ class RegulatoryFramework(Enum):
28
+ """Supported regulatory frameworks"""
29
+ EU_AI_ACT = "eu_ai_act"
30
+ SOC2 = "soc2"
31
+ FEDRAMP = "fedramp"
32
+ GDPR = "gdpr"
33
+ HIPAA = "hipaa"
34
+ PCI_DSS = "pci_dss"
35
+ ISO27001 = "iso27001"
36
+
37
+
38
+ class RiskCategory(Enum):
39
+ """EU AI Act risk categories"""
40
+ UNACCEPTABLE = "unacceptable"
41
+ HIGH_RISK = "high_risk"
42
+ LIMITED_RISK = "limited_risk"
43
+ MINIMAL_RISK = "minimal_risk"
44
+
45
+
46
+ class ConstitutionalPrinciple(Enum):
47
+ """Constitutional AI principles"""
48
+ HELPFULNESS = "helpfulness"
49
+ HARMLESSNESS = "harmlessness"
50
+ HONESTY = "honesty"
51
+ TRANSPARENCY = "transparency"
52
+ FAIRNESS = "fairness"
53
+ PRIVACY = "privacy"
54
+
55
+
56
+ @dataclass
57
+ class ComplianceRequirement:
58
+ """
59
+ A specific compliance requirement.
60
+
61
+ Attributes:
62
+ requirement_id: Unique identifier
63
+ framework: Which regulatory framework
64
+ title: Short description
65
+ description: Detailed requirement
66
+ validator: Function to check compliance
67
+ mandatory: Whether this is mandatory
68
+ control_id: Control identifier (e.g., SOC2-CC6.1)
69
+ """
70
+ requirement_id: str
71
+ framework: RegulatoryFramework
72
+ title: str
73
+ description: str
74
+ validator: Callable[[Dict[str, Any]], bool]
75
+ mandatory: bool = True
76
+ control_id: Optional[str] = None
77
+ metadata: Dict[str, Any] = field(default_factory=dict)
78
+
79
+
80
+ @dataclass
81
+ class ComplianceCheck:
82
+ """Result of a compliance check"""
83
+ compliant: bool
84
+ framework: RegulatoryFramework
85
+ checks_passed: int
86
+ checks_failed: int
87
+ failures: List[Dict[str, Any]]
88
+ recommendations: List[str]
89
+ timestamp: datetime = field(default_factory=datetime.now)
90
+
91
+
92
+ @dataclass
93
+ class ConstitutionalRule:
94
+ """
95
+ A constitutional rule inspired by Constitutional AI.
96
+
97
+ These are high-level principles that guide agent behavior,
98
+ evaluated before and after agent actions.
99
+ """
100
+ rule_id: str
101
+ principle: ConstitutionalPrinciple
102
+ rule_text: str
103
+ evaluator: Callable[[str, Dict[str, Any]], float] # Returns 0.0-1.0 compliance
104
+ severity: float = 1.0
105
+ examples: List[str] = field(default_factory=list)
106
+
107
+
108
+ class ComplianceEngine:
109
+ """
110
+ Compliance engine for regulatory adherence.
111
+
112
+ Features:
113
+ - Multi-framework compliance checking
114
+ - Automated control validation
115
+ - Audit trail generation
116
+ - Compliance reporting
117
+ - Risk assessment per EU AI Act
118
+
119
+ Usage:
120
+ engine = ComplianceEngine()
121
+
122
+ # Add requirements
123
+ engine.add_requirement(
124
+ framework=RegulatoryFramework.EU_AI_ACT,
125
+ title="Human oversight",
126
+ validator=check_human_oversight
127
+ )
128
+
129
+ # Check compliance
130
+ result = engine.check_compliance(
131
+ framework=RegulatoryFramework.EU_AI_ACT,
132
+ context=system_context
133
+ )
134
+ """
135
+
136
+ def __init__(self):
137
+ self._requirements: Dict[RegulatoryFramework, List[ComplianceRequirement]] = {}
138
+ self._audit_trail: List[Dict[str, Any]] = []
139
+ self._initialize_default_requirements()
140
+
141
+ def add_requirement(
142
+ self,
143
+ framework: RegulatoryFramework,
144
+ title: str,
145
+ description: str,
146
+ validator: Callable[[Dict[str, Any]], bool],
147
+ mandatory: bool = True,
148
+ control_id: Optional[str] = None
149
+ ) -> str:
150
+ """
151
+ Add a compliance requirement.
152
+
153
+ Args:
154
+ framework: Regulatory framework
155
+ title: Short description
156
+ description: Detailed requirement
157
+ validator: Function to check compliance
158
+ mandatory: Whether this is mandatory
159
+ control_id: Control identifier
160
+
161
+ Returns:
162
+ requirement_id
163
+ """
164
+ import uuid
165
+ requirement_id = str(uuid.uuid4())
166
+
167
+ requirement = ComplianceRequirement(
168
+ requirement_id=requirement_id,
169
+ framework=framework,
170
+ title=title,
171
+ description=description,
172
+ validator=validator,
173
+ mandatory=mandatory,
174
+ control_id=control_id
175
+ )
176
+
177
+ if framework not in self._requirements:
178
+ self._requirements[framework] = []
179
+
180
+ self._requirements[framework].append(requirement)
181
+ return requirement_id
182
+
183
+ def check_compliance(
184
+ self,
185
+ framework: RegulatoryFramework,
186
+ context: Dict[str, Any]
187
+ ) -> ComplianceCheck:
188
+ """
189
+ Check compliance with a regulatory framework.
190
+
191
+ Args:
192
+ framework: Framework to check against
193
+ context: System context for validation
194
+
195
+ Returns:
196
+ ComplianceCheck with results
197
+ """
198
+ requirements = self._requirements.get(framework, [])
199
+
200
+ passed = 0
201
+ failed = 0
202
+ failures = []
203
+ recommendations = []
204
+
205
+ for req in requirements:
206
+ try:
207
+ is_compliant = req.validator(context)
208
+
209
+ if is_compliant:
210
+ passed += 1
211
+ else:
212
+ failed += 1
213
+ failures.append({
214
+ "requirement_id": req.requirement_id,
215
+ "title": req.title,
216
+ "description": req.description,
217
+ "control_id": req.control_id,
218
+ "mandatory": req.mandatory
219
+ })
220
+
221
+ if req.mandatory:
222
+ recommendations.append(
223
+ f"CRITICAL: Fix mandatory requirement: {req.title}"
224
+ )
225
+
226
+ # Log to audit trail
227
+ self._audit_trail.append({
228
+ "type": "compliance_check",
229
+ "framework": framework.value,
230
+ "requirement": req.title,
231
+ "result": "pass" if is_compliant else "fail",
232
+ "timestamp": datetime.now().isoformat()
233
+ })
234
+
235
+ except Exception as e:
236
+ failed += 1
237
+ failures.append({
238
+ "requirement_id": req.requirement_id,
239
+ "title": req.title,
240
+ "error": str(e)
241
+ })
242
+
243
+ return ComplianceCheck(
244
+ compliant=failed == 0,
245
+ framework=framework,
246
+ checks_passed=passed,
247
+ checks_failed=failed,
248
+ failures=failures,
249
+ recommendations=recommendations
250
+ )
251
+
252
+ def assess_risk_category(
253
+ self,
254
+ system_description: Dict[str, Any]
255
+ ) -> RiskCategory:
256
+ """
257
+ Assess risk category per EU AI Act.
258
+
259
+ Args:
260
+ system_description: Description of the AI system
261
+
262
+ Returns:
263
+ RiskCategory classification
264
+ """
265
+ # Unacceptable risk systems (Article 5)
266
+ unacceptable_indicators = [
267
+ "social_scoring",
268
+ "subliminal_manipulation",
269
+ "exploit_vulnerabilities",
270
+ "biometric_categorization"
271
+ ]
272
+
273
+ for indicator in unacceptable_indicators:
274
+ if indicator in str(system_description).lower():
275
+ return RiskCategory.UNACCEPTABLE
276
+
277
+ # High-risk systems (Annex III)
278
+ high_risk_indicators = [
279
+ "critical_infrastructure",
280
+ "education",
281
+ "employment",
282
+ "essential_services",
283
+ "law_enforcement",
284
+ "migration",
285
+ "justice",
286
+ "biometric_identification"
287
+ ]
288
+
289
+ for indicator in high_risk_indicators:
290
+ if indicator in str(system_description).lower():
291
+ return RiskCategory.HIGH_RISK
292
+
293
+ # Limited risk (transparency obligations)
294
+ limited_risk_indicators = [
295
+ "chatbot",
296
+ "content_generation",
297
+ "deepfake"
298
+ ]
299
+
300
+ for indicator in limited_risk_indicators:
301
+ if indicator in str(system_description).lower():
302
+ return RiskCategory.LIMITED_RISK
303
+
304
+ return RiskCategory.MINIMAL_RISK
305
+
306
+ def generate_compliance_report(
307
+ self,
308
+ framework: RegulatoryFramework
309
+ ) -> Dict[str, Any]:
310
+ """
311
+ Generate a compliance report.
312
+
313
+ Args:
314
+ framework: Framework to report on
315
+
316
+ Returns:
317
+ Compliance report dictionary
318
+ """
319
+ requirements = self._requirements.get(framework, [])
320
+
321
+ # Get recent audit trail for this framework
322
+ recent_checks = [
323
+ entry for entry in self._audit_trail
324
+ if entry.get("framework") == framework.value
325
+ and datetime.fromisoformat(entry["timestamp"]) >
326
+ datetime.now() - timedelta(days=30)
327
+ ]
328
+
329
+ passed = sum(1 for c in recent_checks if c["result"] == "pass")
330
+ failed = sum(1 for c in recent_checks if c["result"] == "fail")
331
+
332
+ return {
333
+ "framework": framework.value,
334
+ "total_requirements": len(requirements),
335
+ "mandatory_requirements": sum(1 for r in requirements if r.mandatory),
336
+ "recent_checks": len(recent_checks),
337
+ "passed": passed,
338
+ "failed": failed,
339
+ "compliance_rate": (passed / len(recent_checks) * 100) if recent_checks else 0,
340
+ "generated_at": datetime.now().isoformat()
341
+ }
342
+
343
+ def get_audit_trail(
344
+ self,
345
+ framework: Optional[RegulatoryFramework] = None,
346
+ days: int = 30
347
+ ) -> List[Dict[str, Any]]:
348
+ """
349
+ Get audit trail entries.
350
+
351
+ Args:
352
+ framework: Optional framework filter
353
+ days: Number of days to look back
354
+
355
+ Returns:
356
+ List of audit trail entries
357
+ """
358
+ cutoff = datetime.now() - timedelta(days=days)
359
+
360
+ entries = [
361
+ entry for entry in self._audit_trail
362
+ if datetime.fromisoformat(entry["timestamp"]) > cutoff
363
+ ]
364
+
365
+ if framework:
366
+ entries = [
367
+ entry for entry in entries
368
+ if entry.get("framework") == framework.value
369
+ ]
370
+
371
+ return entries
372
+
373
+ def _initialize_default_requirements(self):
374
+ """Initialize default compliance requirements"""
375
+
376
+ # EU AI Act - High-Risk System Requirements
377
+ def check_human_oversight(context: Dict[str, Any]) -> bool:
378
+ """EU AI Act Article 14 - Human oversight"""
379
+ return context.get("human_oversight_enabled", False)
380
+
381
+ self.add_requirement(
382
+ framework=RegulatoryFramework.EU_AI_ACT,
383
+ title="Human oversight",
384
+ description="High-risk AI systems must be designed with human oversight",
385
+ validator=check_human_oversight,
386
+ mandatory=True,
387
+ control_id="EU-AI-Act-Art14"
388
+ )
389
+
390
+ def check_transparency(context: Dict[str, Any]) -> bool:
391
+ """EU AI Act Article 13 - Transparency"""
392
+ return context.get("provides_transparency_info", False)
393
+
394
+ self.add_requirement(
395
+ framework=RegulatoryFramework.EU_AI_ACT,
396
+ title="Transparency and information",
397
+ description="Users must be informed they are interacting with an AI system",
398
+ validator=check_transparency,
399
+ mandatory=True,
400
+ control_id="EU-AI-Act-Art13"
401
+ )
402
+
403
+ # SOC 2 - Common Criteria
404
+ def check_access_controls(context: Dict[str, Any]) -> bool:
405
+ """SOC 2 CC6.1 - Logical and physical access controls"""
406
+ return context.get("access_controls_implemented", False)
407
+
408
+ self.add_requirement(
409
+ framework=RegulatoryFramework.SOC2,
410
+ title="Access controls",
411
+ description="Logical and physical access controls restrict access to authorized users",
412
+ validator=check_access_controls,
413
+ mandatory=True,
414
+ control_id="CC6.1"
415
+ )
416
+
417
+ def check_monitoring(context: Dict[str, Any]) -> bool:
418
+ """SOC 2 CC7.2 - System monitoring"""
419
+ return context.get("monitoring_enabled", False)
420
+
421
+ self.add_requirement(
422
+ framework=RegulatoryFramework.SOC2,
423
+ title="System monitoring",
424
+ description="The entity monitors system components and operation of controls",
425
+ validator=check_monitoring,
426
+ mandatory=True,
427
+ control_id="CC7.2"
428
+ )
429
+
430
+ # GDPR
431
+ def check_data_minimization(context: Dict[str, Any]) -> bool:
432
+ """GDPR Article 5(1)(c) - Data minimization"""
433
+ collected = context.get("data_collected", [])
434
+ necessary = context.get("data_necessary", [])
435
+ return set(collected).issubset(set(necessary))
436
+
437
+ self.add_requirement(
438
+ framework=RegulatoryFramework.GDPR,
439
+ title="Data minimization",
440
+ description="Personal data must be adequate, relevant and limited to what is necessary",
441
+ validator=check_data_minimization,
442
+ mandatory=True,
443
+ control_id="GDPR-Art5-1-c"
444
+ )
445
+
446
+
447
+ class ConstitutionalAI:
448
+ """
449
+ Constitutional AI implementation for value alignment.
450
+
451
+ Based on Anthropic's Constitutional AI approach, this provides
452
+ a framework for aligning agent behavior with human values through
453
+ explicit constitutional rules.
454
+
455
+ Features:
456
+ - Define constitutional principles
457
+ - Evaluate actions against constitution
458
+ - Self-critique and revision
459
+ - Transparency in decision-making
460
+
461
+ Usage:
462
+ constitution = ConstitutionalAI()
463
+
464
+ # Add rules
465
+ constitution.add_rule(
466
+ principle=ConstitutionalPrinciple.HARMLESSNESS,
467
+ rule_text="Never assist with illegal activities",
468
+ evaluator=evaluate_harmlessness
469
+ )
470
+
471
+ # Evaluate
472
+ result = constitution.evaluate("User request text", context)
473
+ """
474
+
475
+ def __init__(self):
476
+ self._rules: List[ConstitutionalRule] = []
477
+ self._initialize_default_constitution()
478
+
479
+ def add_rule(
480
+ self,
481
+ principle: ConstitutionalPrinciple,
482
+ rule_text: str,
483
+ evaluator: Callable[[str, Dict[str, Any]], float],
484
+ severity: float = 1.0,
485
+ examples: Optional[List[str]] = None
486
+ ) -> str:
487
+ """
488
+ Add a constitutional rule.
489
+
490
+ Args:
491
+ principle: Which principle this enforces
492
+ rule_text: Human-readable rule description
493
+ evaluator: Function that evaluates compliance (0.0-1.0)
494
+ severity: How important this rule is
495
+ examples: Example applications of the rule
496
+
497
+ Returns:
498
+ rule_id
499
+ """
500
+ import uuid
501
+ rule_id = str(uuid.uuid4())
502
+
503
+ rule = ConstitutionalRule(
504
+ rule_id=rule_id,
505
+ principle=principle,
506
+ rule_text=rule_text,
507
+ evaluator=evaluator,
508
+ severity=severity,
509
+ examples=examples or []
510
+ )
511
+
512
+ self._rules.append(rule)
513
+ return rule_id
514
+
515
+ def evaluate(
516
+ self,
517
+ text: str,
518
+ context: Dict[str, Any]
519
+ ) -> Dict[str, Any]:
520
+ """
521
+ Evaluate text against constitutional rules.
522
+
523
+ Args:
524
+ text: Text to evaluate (prompt, response, etc.)
525
+ context: Additional context
526
+
527
+ Returns:
528
+ Evaluation results with compliance scores
529
+ """
530
+ results = []
531
+ total_score = 0.0
532
+ total_weight = 0.0
533
+ violations = []
534
+
535
+ for rule in self._rules:
536
+ try:
537
+ compliance_score = rule.evaluator(text, context)
538
+
539
+ results.append({
540
+ "rule_id": rule.rule_id,
541
+ "principle": rule.principle.value,
542
+ "rule_text": rule.rule_text,
543
+ "compliance_score": compliance_score,
544
+ "severity": rule.severity
545
+ })
546
+
547
+ total_score += compliance_score * rule.severity
548
+ total_weight += rule.severity
549
+
550
+ if compliance_score < 0.7: # Threshold for violation
551
+ violations.append({
552
+ "principle": rule.principle.value,
553
+ "rule_text": rule.rule_text,
554
+ "compliance_score": compliance_score
555
+ })
556
+
557
+ except Exception as e:
558
+ results.append({
559
+ "rule_id": rule.rule_id,
560
+ "error": str(e)
561
+ })
562
+
563
+ overall_compliance = (total_score / total_weight) if total_weight > 0 else 1.0
564
+
565
+ return {
566
+ "compliant": overall_compliance >= 0.7,
567
+ "overall_compliance": overall_compliance,
568
+ "rule_results": results,
569
+ "violations": violations,
570
+ "recommendations": self._generate_recommendations(violations)
571
+ }
572
+
573
+ def self_critique(
574
+ self,
575
+ proposed_response: str,
576
+ context: Dict[str, Any]
577
+ ) -> Dict[str, Any]:
578
+ """
579
+ Perform self-critique on a proposed response.
580
+
581
+ This is a key Constitutional AI technique where the system
582
+ evaluates its own outputs before presenting them.
583
+
584
+ Args:
585
+ proposed_response: Response to critique
586
+ context: Context including original prompt
587
+
588
+ Returns:
589
+ Critique results with suggested revisions
590
+ """
591
+ evaluation = self.evaluate(proposed_response, context)
592
+
593
+ revisions = []
594
+ if not evaluation["compliant"]:
595
+ for violation in evaluation["violations"]:
596
+ revisions.append(f"Revise to better align with: {violation['rule_text']}")
597
+
598
+ return {
599
+ "approved": evaluation["compliant"],
600
+ "compliance_score": evaluation["overall_compliance"],
601
+ "violations": evaluation["violations"],
602
+ "suggested_revisions": revisions
603
+ }
604
+
605
+ def _generate_recommendations(
606
+ self,
607
+ violations: List[Dict[str, Any]]
608
+ ) -> List[str]:
609
+ """Generate recommendations based on violations"""
610
+ if not violations:
611
+ return []
612
+
613
+ recommendations = ["Review and revise content to address constitutional violations:"]
614
+
615
+ for violation in violations:
616
+ recommendations.append(
617
+ f"- Align with principle: {violation['principle']} - {violation['rule_text']}"
618
+ )
619
+
620
+ return recommendations
621
+
622
+ def _initialize_default_constitution(self):
623
+ """Initialize default constitutional rules"""
624
+
625
+ def evaluate_harmlessness(text: str, context: Dict[str, Any]) -> float:
626
+ """Evaluate harmlessness principle"""
627
+ harmful_keywords = [
628
+ "violence", "harm", "illegal", "exploit",
629
+ "manipulate", "deceive", "dangerous"
630
+ ]
631
+ text_lower = text.lower()
632
+
633
+ violations = sum(1 for keyword in harmful_keywords if keyword in text_lower)
634
+ # Need at least 2 violations to fail
635
+ return max(0.0, 1.0 - (violations * 0.5))
636
+
637
+ self.add_rule(
638
+ principle=ConstitutionalPrinciple.HARMLESSNESS,
639
+ rule_text="Avoid content that could cause harm to individuals or society",
640
+ evaluator=evaluate_harmlessness,
641
+ severity=1.0,
642
+ examples=[
643
+ "Don't provide instructions for illegal activities",
644
+ "Don't generate content promoting violence",
645
+ "Don't help with harmful manipulations"
646
+ ]
647
+ )
648
+
649
+ def evaluate_honesty(text: str, context: Dict[str, Any]) -> float:
650
+ """Evaluate honesty principle"""
651
+ dishonest_indicators = [
652
+ "guarantee", "100% certain", "definitely will",
653
+ "impossible to", "never wrong"
654
+ ]
655
+ text_lower = text.lower()
656
+
657
+ violations = sum(1 for indicator in dishonest_indicators if indicator in text_lower)
658
+ return max(0.0, 1.0 - (violations * 0.25))
659
+
660
+ self.add_rule(
661
+ principle=ConstitutionalPrinciple.HONESTY,
662
+ rule_text="Be honest about capabilities, limitations, and uncertainty",
663
+ evaluator=evaluate_honesty,
664
+ severity=0.9,
665
+ examples=[
666
+ "Acknowledge when uncertain",
667
+ "Don't overstate capabilities",
668
+ "Be truthful about limitations"
669
+ ]
670
+ )
671
+
672
+ def evaluate_privacy(text: str, context: Dict[str, Any]) -> float:
673
+ """Evaluate privacy principle"""
674
+ # Check for PII exposure
675
+ import re
676
+ pii_patterns = [
677
+ r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', # email
678
+ r'\b\d{3}-\d{2}-\d{4}\b', # SSN
679
+ r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', # phone
680
+ ]
681
+
682
+ violations = sum(1 for pattern in pii_patterns if re.search(pattern, text))
683
+ return max(0.0, 1.0 - (violations * 0.3))
684
+
685
+ self.add_rule(
686
+ principle=ConstitutionalPrinciple.PRIVACY,
687
+ rule_text="Protect privacy and don't expose personal information",
688
+ evaluator=evaluate_privacy,
689
+ severity=1.0,
690
+ examples=[
691
+ "Don't include PII in responses",
692
+ "Respect data confidentiality",
693
+ "Follow privacy best practices"
694
+ ]
695
+ )
696
+
697
+ def get_constitution(self) -> List[Dict[str, Any]]:
698
+ """Get the full constitution as a readable format"""
699
+ return [
700
+ {
701
+ "principle": rule.principle.value,
702
+ "rule_text": rule.rule_text,
703
+ "severity": rule.severity,
704
+ "examples": rule.examples
705
+ }
706
+ for rule in self._rules
707
+ ]
708
+
709
+
710
+ def create_compliance_suite() -> Dict[str, Any]:
711
+ """
712
+ Create a complete compliance suite with multiple frameworks.
713
+
714
+ Returns:
715
+ Dictionary with compliance engine and constitutional AI
716
+ """
717
+ return {
718
+ "compliance_engine": ComplianceEngine(),
719
+ "constitutional_ai": ConstitutionalAI()
720
+ }