maigp-server 5.0.0__tar.gz

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 (51) hide show
  1. maigp_server-5.0.0/.gitignore +45 -0
  2. maigp_server-5.0.0/PKG-INFO +136 -0
  3. maigp_server-5.0.0/README.md +112 -0
  4. maigp_server-5.0.0/aigp_server/__init__.py +60 -0
  5. maigp_server-5.0.0/aigp_server/anticipation.py +75 -0
  6. maigp_server-5.0.0/aigp_server/au_rules.py +101 -0
  7. maigp_server-5.0.0/aigp_server/circuit_breaker.py +102 -0
  8. maigp_server-5.0.0/aigp_server/config.py +81 -0
  9. maigp_server-5.0.0/aigp_server/euai_rules.py +163 -0
  10. maigp_server-5.0.0/aigp_server/governance_engine.py +352 -0
  11. maigp_server-5.0.0/aigp_server/hmac_auth.py +54 -0
  12. maigp_server-5.0.0/aigp_server/ihl_rules.py +160 -0
  13. maigp_server-5.0.0/aigp_server/jp_rules.py +78 -0
  14. maigp_server-5.0.0/aigp_server/providers/__init__.py +0 -0
  15. maigp_server-5.0.0/aigp_server/providers/consent/__init__.py +5 -0
  16. maigp_server-5.0.0/aigp_server/providers/consent/consent_engine.py +80 -0
  17. maigp_server-5.0.0/aigp_server/providers/consent/static/__init__.py +0 -0
  18. maigp_server-5.0.0/aigp_server/providers/enforcement/__init__.py +6 -0
  19. maigp_server-5.0.0/aigp_server/providers/enforcement/azure/__init__.py +0 -0
  20. maigp_server-5.0.0/aigp_server/providers/enforcement/bedrock/__init__.py +0 -0
  21. maigp_server-5.0.0/aigp_server/providers/enforcement/enforcement_adapter_base.py +37 -0
  22. maigp_server-5.0.0/aigp_server/providers/enforcement/enforcement_adapter_factory.py +26 -0
  23. maigp_server-5.0.0/aigp_server/providers/enforcement/gcp/__init__.py +0 -0
  24. maigp_server-5.0.0/aigp_server/providers/key_store/__init__.py +7 -0
  25. maigp_server-5.0.0/aigp_server/providers/key_store/key_store_base.py +37 -0
  26. maigp_server-5.0.0/aigp_server/providers/key_store/key_store_factory.py +24 -0
  27. maigp_server-5.0.0/aigp_server/providers/key_store/kms/__init__.py +0 -0
  28. maigp_server-5.0.0/aigp_server/providers/key_store/local/__init__.py +0 -0
  29. maigp_server-5.0.0/aigp_server/providers/key_store/local/local_key_store.py +41 -0
  30. maigp_server-5.0.0/aigp_server/providers/pii/__init__.py +7 -0
  31. maigp_server-5.0.0/aigp_server/providers/pii/pii_detector_base.py +33 -0
  32. maigp_server-5.0.0/aigp_server/providers/pii/pii_detector_factory.py +24 -0
  33. maigp_server-5.0.0/aigp_server/providers/pii/presidio/__init__.py +0 -0
  34. maigp_server-5.0.0/aigp_server/providers/pii/regex/__init__.py +0 -0
  35. maigp_server-5.0.0/aigp_server/providers/pii/regex/regex_detector.py +39 -0
  36. maigp_server-5.0.0/aigp_server/providers/scope/__init__.py +6 -0
  37. maigp_server-5.0.0/aigp_server/providers/scope/circuit_breaker.py +102 -0
  38. maigp_server-5.0.0/aigp_server/providers/scope/scope_manager.py +99 -0
  39. maigp_server-5.0.0/aigp_server/providers/storage/__init__.py +9 -0
  40. maigp_server-5.0.0/aigp_server/providers/storage/dynamodb/__init__.py +0 -0
  41. maigp_server-5.0.0/aigp_server/providers/storage/memory/__init__.py +0 -0
  42. maigp_server-5.0.0/aigp_server/providers/storage/memory/memory_storage_provider.py +74 -0
  43. maigp_server-5.0.0/aigp_server/providers/storage/storage_provider_base.py +65 -0
  44. maigp_server-5.0.0/aigp_server/providers/storage/storage_provider_factory.py +27 -0
  45. maigp_server-5.0.0/aigp_server/routes.py +221 -0
  46. maigp_server-5.0.0/aigp_server/routes_v3.py +222 -0
  47. maigp_server-5.0.0/aigp_server/scope_manager.py +99 -0
  48. maigp_server-5.0.0/aigp_server/store.py +78 -0
  49. maigp_server-5.0.0/aigp_server/universal_rules.py +79 -0
  50. maigp_server-5.0.0/aigp_server/verification_engine.py +162 -0
  51. maigp_server-5.0.0/pyproject.toml +35 -0
@@ -0,0 +1,45 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
8
+ .eggs/
9
+
10
+ # Node
11
+ node_modules/
12
+ dist/
13
+
14
+ # Go
15
+ bin/
16
+
17
+ # Rust
18
+ target/
19
+
20
+ # .NET
21
+ bin/
22
+ obj/
23
+
24
+ # Java
25
+ *.class
26
+ out/
27
+
28
+ # IDE
29
+ .idea/
30
+ .vscode/
31
+ .kiro/
32
+ *.swp
33
+
34
+ # OS
35
+ .DS_Store
36
+ Thumbs.db
37
+
38
+ # Secrets (never commit)
39
+ .env
40
+ *.pem
41
+ *.key
42
+ *.pdf
43
+ BACKLOG/
44
+ patent/
45
+ docs/.archive/
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: maigp-server
3
+ Version: 5.0.0
4
+ Summary: MAIGP Governance Server — Mediated AI Governance Protocol engine (scope envelopes, circuit breakers, delegation)
5
+ Project-URL: Homepage, https://github.com/owner-spec/aigp-protocol
6
+ Project-URL: Repository, https://github.com/owner-spec/aigp-protocol
7
+ Author-email: Evan Erwee <evan@erwee.com>
8
+ License: Proprietary
9
+ Keywords: agentic,ai,aigp,circuit-breaker,governance,maigp,mediated,protocol,scope-envelope
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: Other/Proprietary License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Security
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Requires-Python: <3.14,>=3.11
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest; extra == 'dev'
22
+ Requires-Dist: pytest-asyncio; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # aigp-server — AIGP Governance Engine
26
+
27
+ Reference governance server for the AI Governance Protocol (AIGP) v4.0. Provider-based architecture with jurisdictional AI governance.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install aigp-server
33
+ ```
34
+
35
+ ## What It Does
36
+
37
+ The governance server evaluates AI requests against 5 jurisdictional rule engines in strict priority order:
38
+
39
+ ```
40
+ IHL (RFC-027) → EU AI Act (RFC-028) → AU Strategy (RFC-029) → Japan Act (RFC-030) → Universal (RFC-031)
41
+ ```
42
+
43
+ First DENY wins. 35 governance rules total.
44
+
45
+ ## Quick Start
46
+
47
+ ```python
48
+ from aigp_server import GovernanceEngine, AigpRouter, ServerConfig
49
+
50
+ # Configure
51
+ config = ServerConfig(
52
+ storage={"provider": "memory"}, # or "dynamodb"
53
+ mode="REPORT", # REPORT (fail-open) or ENFORCE (fail-closed)
54
+ )
55
+ components = config.build()
56
+
57
+ # Create engine + router
58
+ engine = GovernanceEngine(components.store, components.scope_mgr, components.circuit_breaker, mode="REPORT")
59
+ router = AigpRouter(engine, hmac_secret="your-secret")
60
+
61
+ # Declare jurisdictional context
62
+ await engine.declare_universal_context("my-app", {"active": True, "principles": "ALL"})
63
+
64
+ # Handle requests (framework-agnostic — returns (status_code, response_dict))
65
+ status, resp = await router.handle_tool_request(headers, body)
66
+ ```
67
+
68
+ ## Jurisdictional Governance (v4.0)
69
+
70
+ | Route | Method | RFC |
71
+ |-------|--------|-----|
72
+ | `/api/v1/context/declare` | POST | RFC-027 (IHL) |
73
+ | `/api/v1/regulatory/declare` | POST | RFC-028 (EU AI Act) |
74
+ | `/api/v1/african/declare` | POST | RFC-029 (AU Strategy) |
75
+ | `/api/v1/japanese/declare` | POST | RFC-030 (Japan Act) |
76
+ | `/api/v1/universal/declare` | POST | RFC-031 (Universal) |
77
+
78
+ Each has a corresponding GET endpoint: `/api/v1/{context}/{app_id}`
79
+
80
+ ## Rule Engines
81
+
82
+ | File | Rules | Scope |
83
+ |------|:-----:|-------|
84
+ | `ihl_rules.py` | 6 | Non-derogable IHL protections |
85
+ | `euai_rules.py` | 7 | Risk classification, conformity, FRIA |
86
+ | `au_rules.py` | 6 | Data sovereignty, cultural preservation |
87
+ | `jp_rules.py` | 6 | Innovation enablement, safety, transparency |
88
+ | `universal_rules.py` | 10 | Baseline: human authority, accountability, non-discrimination |
89
+
90
+ ## Provider Architecture
91
+
92
+ ```
93
+ aigp_server/
94
+ ├── governance_engine.py Core engine — 5-layer evaluation
95
+ ├── routes.py Framework-agnostic HTTP handlers
96
+ ├── ihl_rules.py RFC-027
97
+ ├── euai_rules.py RFC-028
98
+ ├── au_rules.py RFC-029
99
+ ├── jp_rules.py RFC-030
100
+ ├── universal_rules.py RFC-031
101
+ ├── hmac_auth.py HMAC-SHA256 request signing
102
+ ├── config.py Provider configuration
103
+ ├── providers/
104
+ │ ├── storage/ memory, dynamodb
105
+ │ ├── scope/ ScopeEnvelopeManager, CircuitBreakerService
106
+ │ ├── enforcement/ bedrock, azure, gcp adapters
107
+ │ ├── pii/ regex, presidio, comprehend
108
+ │ ├── key_store/ local, kms, vault
109
+ │ └── consent/ Tier-aware tokenization
110
+ ```
111
+
112
+ ## Agentic Governance Handlers
113
+
114
+ | Handler | Purpose | Decision |
115
+ |---------|---------|----------|
116
+ | `handle_tool_request` | Per-tool CHECK | ALLOW / DENY |
117
+ | `handle_plan_submit` | Plan approval | APPROVED / REJECTED |
118
+ | `handle_step_complete` | Budget decrement | recorded |
119
+ | `handle_escalate` | Human escalation | Creates pending task |
120
+ | `handle_delegate` | Agent-to-agent scoping | Scope narrowing |
121
+ | `handle_memory_write` | Classification check | ALLOW / DENY |
122
+
123
+ ## Implementing Your Own
124
+
125
+ This is a **reference implementation**. To build your own governance server:
126
+
127
+ 1. `pip install aigp-server` for the engine + rules
128
+ 2. Wire `AigpRouter` handlers into your HTTP framework (FastAPI, Flask, Express, etc.)
129
+ 3. Implement `StorageProviderBase` for your database
130
+ 4. Deploy behind your own infrastructure
131
+
132
+ The `aigp-client` SDK (all 8 languages) talks to any server implementing the AIGP HTTP contract.
133
+
134
+ ## License
135
+
136
+ Proprietary — © 2025-2026 Evan Erwee. All rights reserved.
@@ -0,0 +1,112 @@
1
+ # aigp-server — AIGP Governance Engine
2
+
3
+ Reference governance server for the AI Governance Protocol (AIGP) v4.0. Provider-based architecture with jurisdictional AI governance.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install aigp-server
9
+ ```
10
+
11
+ ## What It Does
12
+
13
+ The governance server evaluates AI requests against 5 jurisdictional rule engines in strict priority order:
14
+
15
+ ```
16
+ IHL (RFC-027) → EU AI Act (RFC-028) → AU Strategy (RFC-029) → Japan Act (RFC-030) → Universal (RFC-031)
17
+ ```
18
+
19
+ First DENY wins. 35 governance rules total.
20
+
21
+ ## Quick Start
22
+
23
+ ```python
24
+ from aigp_server import GovernanceEngine, AigpRouter, ServerConfig
25
+
26
+ # Configure
27
+ config = ServerConfig(
28
+ storage={"provider": "memory"}, # or "dynamodb"
29
+ mode="REPORT", # REPORT (fail-open) or ENFORCE (fail-closed)
30
+ )
31
+ components = config.build()
32
+
33
+ # Create engine + router
34
+ engine = GovernanceEngine(components.store, components.scope_mgr, components.circuit_breaker, mode="REPORT")
35
+ router = AigpRouter(engine, hmac_secret="your-secret")
36
+
37
+ # Declare jurisdictional context
38
+ await engine.declare_universal_context("my-app", {"active": True, "principles": "ALL"})
39
+
40
+ # Handle requests (framework-agnostic — returns (status_code, response_dict))
41
+ status, resp = await router.handle_tool_request(headers, body)
42
+ ```
43
+
44
+ ## Jurisdictional Governance (v4.0)
45
+
46
+ | Route | Method | RFC |
47
+ |-------|--------|-----|
48
+ | `/api/v1/context/declare` | POST | RFC-027 (IHL) |
49
+ | `/api/v1/regulatory/declare` | POST | RFC-028 (EU AI Act) |
50
+ | `/api/v1/african/declare` | POST | RFC-029 (AU Strategy) |
51
+ | `/api/v1/japanese/declare` | POST | RFC-030 (Japan Act) |
52
+ | `/api/v1/universal/declare` | POST | RFC-031 (Universal) |
53
+
54
+ Each has a corresponding GET endpoint: `/api/v1/{context}/{app_id}`
55
+
56
+ ## Rule Engines
57
+
58
+ | File | Rules | Scope |
59
+ |------|:-----:|-------|
60
+ | `ihl_rules.py` | 6 | Non-derogable IHL protections |
61
+ | `euai_rules.py` | 7 | Risk classification, conformity, FRIA |
62
+ | `au_rules.py` | 6 | Data sovereignty, cultural preservation |
63
+ | `jp_rules.py` | 6 | Innovation enablement, safety, transparency |
64
+ | `universal_rules.py` | 10 | Baseline: human authority, accountability, non-discrimination |
65
+
66
+ ## Provider Architecture
67
+
68
+ ```
69
+ aigp_server/
70
+ ├── governance_engine.py Core engine — 5-layer evaluation
71
+ ├── routes.py Framework-agnostic HTTP handlers
72
+ ├── ihl_rules.py RFC-027
73
+ ├── euai_rules.py RFC-028
74
+ ├── au_rules.py RFC-029
75
+ ├── jp_rules.py RFC-030
76
+ ├── universal_rules.py RFC-031
77
+ ├── hmac_auth.py HMAC-SHA256 request signing
78
+ ├── config.py Provider configuration
79
+ ├── providers/
80
+ │ ├── storage/ memory, dynamodb
81
+ │ ├── scope/ ScopeEnvelopeManager, CircuitBreakerService
82
+ │ ├── enforcement/ bedrock, azure, gcp adapters
83
+ │ ├── pii/ regex, presidio, comprehend
84
+ │ ├── key_store/ local, kms, vault
85
+ │ └── consent/ Tier-aware tokenization
86
+ ```
87
+
88
+ ## Agentic Governance Handlers
89
+
90
+ | Handler | Purpose | Decision |
91
+ |---------|---------|----------|
92
+ | `handle_tool_request` | Per-tool CHECK | ALLOW / DENY |
93
+ | `handle_plan_submit` | Plan approval | APPROVED / REJECTED |
94
+ | `handle_step_complete` | Budget decrement | recorded |
95
+ | `handle_escalate` | Human escalation | Creates pending task |
96
+ | `handle_delegate` | Agent-to-agent scoping | Scope narrowing |
97
+ | `handle_memory_write` | Classification check | ALLOW / DENY |
98
+
99
+ ## Implementing Your Own
100
+
101
+ This is a **reference implementation**. To build your own governance server:
102
+
103
+ 1. `pip install aigp-server` for the engine + rules
104
+ 2. Wire `AigpRouter` handlers into your HTTP framework (FastAPI, Flask, Express, etc.)
105
+ 3. Implement `StorageProviderBase` for your database
106
+ 4. Deploy behind your own infrastructure
107
+
108
+ The `aigp-client` SDK (all 8 languages) talks to any server implementing the AIGP HTTP contract.
109
+
110
+ ## License
111
+
112
+ Proprietary — © 2025-2026 Evan Erwee. All rights reserved.
@@ -0,0 +1,60 @@
1
+ """AIGP Server — Agentic Governance Engine with provider-based architecture.
2
+
3
+ Usage (new — config-driven):
4
+ from aigp_server import ServerConfig
5
+
6
+ config = ServerConfig(
7
+ storage={"provider": "memory"},
8
+ pii={"provider": "regex"},
9
+ key_store={"provider": "local"},
10
+ mode="ENFORCE",
11
+ )
12
+ components = config.build()
13
+ engine = GovernanceEngine(components.store, components.scope_mgr, components.circuit_breaker, mode="ENFORCE")
14
+ router = AigpRouter(engine, hmac_secret="...")
15
+
16
+ Usage (backward compat — still works):
17
+ from aigp_server import GovernanceEngine, GovernanceStore, AigpRouter
18
+
19
+ class MyStore(GovernanceStore): ...
20
+ store = MyStore()
21
+ engine = GovernanceEngine(store, ScopeEnvelopeManager(store), CircuitBreakerService(store))
22
+ router = AigpRouter(engine)
23
+ """
24
+
25
+ __version__ = "0.2.0"
26
+
27
+ # Backward compat — original flat imports
28
+ from .governance_engine import GovernanceEngine
29
+ from .routes import AigpRouter
30
+ from .hmac_auth import verify_hmac, sign_request
31
+
32
+ # Provider-based (new)
33
+ from .providers.storage import StorageProviderBase, GovernanceStore
34
+ from .providers.scope import ScopeEnvelopeManager, CircuitBreakerService, TEMPLATES
35
+ from .providers.enforcement import EnforcementAdapterBase
36
+ from .providers.pii import PiiDetectorBase, PiiEntity
37
+ from .providers.key_store import KeyStoreBase
38
+ from .providers.consent import ConsentEngine, TokenMap
39
+ from .config import ServerConfig, ServerComponents
40
+
41
+ __all__ = [
42
+ # Engine + Router
43
+ "GovernanceEngine", "AigpRouter",
44
+ # Auth
45
+ "verify_hmac", "sign_request",
46
+ # Storage
47
+ "StorageProviderBase", "GovernanceStore",
48
+ # Scope
49
+ "ScopeEnvelopeManager", "CircuitBreakerService", "TEMPLATES",
50
+ # Enforcement
51
+ "EnforcementAdapterBase",
52
+ # PII
53
+ "PiiDetectorBase", "PiiEntity",
54
+ # Key Store
55
+ "KeyStoreBase",
56
+ # Consent
57
+ "ConsentEngine", "TokenMap",
58
+ # Config
59
+ "ServerConfig", "ServerComponents",
60
+ ]
@@ -0,0 +1,75 @@
1
+ """Anticipation Store — manages ANTICIPATE lifecycle (RFC-032 Phase 1)."""
2
+
3
+ from datetime import datetime, timezone
4
+ from uuid import uuid4
5
+
6
+ from .providers.storage.storage_provider_base import StorageProviderBase
7
+
8
+
9
+ class AnticipationStore:
10
+ """Stores and manages ANTICIPATE declarations with seal semantics."""
11
+
12
+ def __init__(self, db: StorageProviderBase):
13
+ self._db = db
14
+ self._anticipations: dict[str, dict] = {} # anticipation_id → record
15
+
16
+ async def create(self, msg: dict) -> dict:
17
+ """Create a new ANTICIPATE declaration. Returns the stored record."""
18
+ ant_id = msg.get("anticipation_id", f"ant-{uuid4().hex[:12]}")
19
+ record = {
20
+ "anticipation_id": ant_id,
21
+ "app_id": msg["app_id"],
22
+ "agent_id": msg["agent_id"],
23
+ "plan_id": msg.get("plan_id"),
24
+ "scope_envelope_id": msg.get("scope_envelope_id"),
25
+ "session_id": msg.get("session_id"),
26
+ "expectations": msg["expectations"],
27
+ "grading_policy": msg["grading_policy"],
28
+ "status": "OPEN",
29
+ "created_at": datetime.now(timezone.utc).isoformat(),
30
+ "sealed_at": None,
31
+ }
32
+ self._anticipations[ant_id] = record
33
+ await self._db.put_audit(msg["agent_id"], "ANTICIPATE_CREATED", "OPEN", {"anticipation_id": ant_id})
34
+ return record
35
+
36
+ async def seal(self, anticipation_id: str) -> bool:
37
+ """Seal an anticipation (immutable after first execution event). Returns True if sealed."""
38
+ record = self._anticipations.get(anticipation_id)
39
+ if not record or record["status"] != "OPEN":
40
+ return False
41
+ record["status"] = "SEALED"
42
+ record["sealed_at"] = datetime.now(timezone.utc).isoformat()
43
+ await self._db.put_audit(record["agent_id"], "ANTICIPATE_SEALED", "SEALED", {"anticipation_id": anticipation_id})
44
+ return True
45
+
46
+ def is_sealed(self, anticipation_id: str) -> bool:
47
+ record = self._anticipations.get(anticipation_id)
48
+ return record is not None and record["status"] == "SEALED"
49
+
50
+ def get(self, anticipation_id: str) -> dict | None:
51
+ return self._anticipations.get(anticipation_id)
52
+
53
+ def find_for_session(self, session_id: str) -> list[dict]:
54
+ return [r for r in self._anticipations.values() if r.get("session_id") == session_id]
55
+
56
+ def find_for_plan(self, plan_id: str) -> list[dict]:
57
+ return [r for r in self._anticipations.values() if r.get("plan_id") == plan_id]
58
+
59
+ async def seal_open_for_session(self, session_id: str) -> list[str]:
60
+ """Seal all OPEN anticipations for a session. Returns sealed IDs."""
61
+ sealed = []
62
+ for record in self._anticipations.values():
63
+ if record.get("session_id") == session_id and record["status"] == "OPEN":
64
+ if await self.seal(record["anticipation_id"]):
65
+ sealed.append(record["anticipation_id"])
66
+ return sealed
67
+
68
+ async def seal_open_for_agent(self, agent_id: str) -> list[str]:
69
+ """Seal all OPEN anticipations for an agent. Returns sealed IDs."""
70
+ sealed = []
71
+ for record in self._anticipations.values():
72
+ if record.get("agent_id") == agent_id and record["status"] == "OPEN":
73
+ if await self.seal(record["anticipation_id"]):
74
+ sealed.append(record["anticipation_id"])
75
+ return sealed
@@ -0,0 +1,101 @@
1
+ """AU Continental AI Strategy Rules — RFC-029 Wave 2.
2
+
3
+ These rules implement the African Union's Continental AI Strategy
4
+ requirements for data sovereignty, local benefit, cultural preservation,
5
+ inclusion, community consent, and equitable partnerships.
6
+
7
+ Legal basis: AU Continental AI Strategy (2024), Malabo Convention (2014).
8
+ """
9
+
10
+ import logging
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ AU_RULES = [
15
+ {"id": "AU-001", "name": "DATA_RESIDENCY", "description": "African data must reside within declared jurisdiction unless cross-border framework is declared."},
16
+ {"id": "AU-002", "name": "LOCAL_BENEFIT", "description": "AI systems must demonstrate local benefit when local_first or ubuntu_principle is active."},
17
+ {"id": "AU-003", "name": "CULTURAL_PRESERVATION", "description": "Indigenous knowledge and cultural norms must be preserved."},
18
+ {"id": "AU-004", "name": "INCLUSION_MANDATE", "description": "Declared beneficiary groups must be served; exclusion is prohibited."},
19
+ {"id": "AU-005", "name": "COMMUNITY_CONSENT", "description": "Community consent is required when cultural_sensitivity.community_consent_required is true."},
20
+ {"id": "AU-006", "name": "EQUITABLE_PARTNERSHIP", "description": "Non-African providers must demonstrate equitable partnership with local entities."},
21
+ ]
22
+
23
+ # AU member states (ISO 3166-1 alpha-2)
24
+ AU_MEMBER_STATES = {
25
+ "DZ", "AO", "BJ", "BW", "BF", "BI", "CV", "CM", "CF", "TD",
26
+ "KM", "CG", "CD", "CI", "DJ", "EG", "GQ", "ER", "SZ", "ET",
27
+ "GA", "GM", "GH", "GN", "GW", "KE", "LS", "LR", "LY", "MG",
28
+ "MW", "ML", "MR", "MU", "MZ", "NA", "NE", "NG", "RW", "ST",
29
+ "SN", "SC", "SL", "SO", "ZA", "SS", "SD", "TZ", "TG", "TN",
30
+ "UG", "ZM", "ZW",
31
+ }
32
+
33
+
34
+ async def evaluate_au_rules(request: dict, context: dict) -> dict | None:
35
+ """Evaluate AU Continental AI Strategy rules against a request.
36
+
37
+ Returns a DENY decision dict if a rule triggers, or None to allow.
38
+ """
39
+ if not context or not context.get("active"):
40
+ return None
41
+
42
+ data_sov = context.get("data_sovereignty", {})
43
+ cultural = context.get("cultural_sensitivity", {})
44
+
45
+ # AU-001: Data residency — if residency declared but request targets outside
46
+ if data_sov.get("residency"):
47
+ dest = request.get("data_destination", "")
48
+ if dest and dest not in AU_MEMBER_STATES and not data_sov.get("cross_border_framework"):
49
+ return _deny("AU-001", "DATA_RESIDENCY",
50
+ f"Data destination '{dest}' is outside AU member states without a declared cross-border framework.")
51
+
52
+ # AU-002: Local benefit — ubuntu_principle or local_first requires benefit declaration
53
+ if context.get("ubuntu_principle") or context.get("local_first"):
54
+ if not request.get("local_benefit_declared") and request.get("provider_jurisdiction"):
55
+ prov = request["provider_jurisdiction"]
56
+ if prov not in AU_MEMBER_STATES:
57
+ return _deny("AU-002", "LOCAL_BENEFIT",
58
+ f"Provider jurisdiction '{prov}' is non-African. local_benefit_declared required when ubuntu_principle/local_first is active.")
59
+
60
+ # AU-003: Cultural preservation
61
+ if cultural.get("indigenous_knowledge_preserved"):
62
+ if request.get("training_data_source") == "scraped" and not request.get("indigenous_consent"):
63
+ return _deny("AU-003", "CULTURAL_PRESERVATION",
64
+ "Scraped training data requires indigenous_consent when indigenous_knowledge_preserved is active.")
65
+
66
+ # AU-004: Inclusion mandate
67
+ beneficiaries = context.get("beneficiary_groups", [])
68
+ if beneficiaries and request.get("excluded_groups"):
69
+ excluded = set(request["excluded_groups"])
70
+ overlap = excluded & set(beneficiaries)
71
+ if overlap:
72
+ return _deny("AU-004", "INCLUSION_MANDATE",
73
+ f"Beneficiary groups {overlap} are explicitly excluded. Inclusion mandate violated.")
74
+
75
+ # AU-005: Community consent
76
+ if cultural.get("community_consent_required"):
77
+ if not request.get("community_consent_obtained"):
78
+ return _deny("AU-005", "COMMUNITY_CONSENT",
79
+ "community_consent_required is true but community_consent_obtained is missing from request.")
80
+
81
+ # AU-006: Equitable partnership
82
+ if request.get("provider_jurisdiction") and request["provider_jurisdiction"] not in AU_MEMBER_STATES:
83
+ if data_sov.get("african_data_for_african_benefit"):
84
+ if not request.get("partnership_declaration"):
85
+ return _deny("AU-006", "EQUITABLE_PARTNERSHIP",
86
+ "Non-African provider operating on African data must declare an equitable partnership.")
87
+
88
+ return None
89
+
90
+
91
+ def _deny(rule_id: str, rule_name: str, reason: str) -> dict:
92
+ """Construct an AU DENY decision. Non-overridable when context is active."""
93
+ logger.warning("AU DENY [%s]: %s", rule_id, reason)
94
+ return {
95
+ "decision": "DENY",
96
+ "reason": reason,
97
+ "au_rule": rule_id,
98
+ "au_rule_name": rule_name,
99
+ "non_derogable": True,
100
+ "override_allowed": False,
101
+ }
@@ -0,0 +1,102 @@
1
+ """Circuit Breaker — halts anomalous agents, cascades to delegation chains."""
2
+
3
+ import logging
4
+ from datetime import datetime, timezone, timedelta
5
+
6
+ from .store import GovernanceStore
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ CLOSED, OPEN, HALF_OPEN = "CLOSED", "OPEN", "HALF_OPEN"
11
+
12
+ DEFAULT_CONFIG = {
13
+ "error_rate_threshold": 0.5,
14
+ "time_window_seconds": 60,
15
+ "cooldown_seconds": 30,
16
+ "max_probe_requests": 3,
17
+ "recovery_conditions": {"consecutive_successes": 3},
18
+ }
19
+
20
+
21
+ def _now() -> str:
22
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
23
+
24
+
25
+ def _expiry(seconds: int) -> str:
26
+ return (datetime.now(timezone.utc) + timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
27
+
28
+
29
+ class CircuitBreakerService:
30
+ def __init__(self, db: GovernanceStore):
31
+ self.db = db
32
+
33
+ async def is_open(self, agent_id: str) -> bool:
34
+ state = await self.db.get_circuit_breaker(agent_id)
35
+ if not state:
36
+ return False
37
+ if state.get("state") == OPEN:
38
+ if _now() > state.get("cooldown_until", ""):
39
+ await self.db.update_circuit_breaker(agent_id, {"state": HALF_OPEN})
40
+ return False
41
+ return True
42
+ return False
43
+
44
+ async def get_state(self, agent_id: str) -> str:
45
+ state = await self.db.get_circuit_breaker(agent_id)
46
+ return state.get("state", CLOSED) if state else CLOSED
47
+
48
+ async def record_outcome(self, agent_id: str, success: bool):
49
+ state = await self.db.get_circuit_breaker(agent_id) or {
50
+ "state": CLOSED, "errors": 0, "total": 0, "consecutive_successes": 0,
51
+ }
52
+ state["total"] += 1
53
+ if not success:
54
+ state["errors"] += 1
55
+ state["consecutive_successes"] = 0
56
+ else:
57
+ state["consecutive_successes"] += 1
58
+
59
+ current = state.get("state", CLOSED)
60
+ config = await self._get_config(agent_id)
61
+
62
+ if current == CLOSED and state["total"] >= 5:
63
+ if state["errors"] / state["total"] > config["error_rate_threshold"]:
64
+ await self._trip(agent_id, config)
65
+ return
66
+
67
+ if current == HALF_OPEN and success:
68
+ if state["consecutive_successes"] >= config["recovery_conditions"]["consecutive_successes"]:
69
+ await self._reset(agent_id)
70
+ return
71
+
72
+ if current == HALF_OPEN and not success:
73
+ await self._trip(agent_id, config)
74
+ return
75
+
76
+ await self.db.put_circuit_breaker(agent_id, state)
77
+
78
+ async def manual_reset(self, agent_id: str):
79
+ await self._reset(agent_id)
80
+
81
+ async def _trip(self, agent_id: str, config: dict):
82
+ await self.db.put_circuit_breaker(agent_id, {
83
+ "state": OPEN,
84
+ "tripped_at": _now(),
85
+ "cooldown_until": _expiry(config["cooldown_seconds"]),
86
+ "errors": 0, "total": 0, "consecutive_successes": 0,
87
+ })
88
+ logger.warning("Circuit breaker TRIPPED for agent %s", agent_id)
89
+ # Cascade to delegates
90
+ for d in await self.db.get_delegates(agent_id):
91
+ if target := d.get("target_agent_id"):
92
+ await self._trip(target, config)
93
+ await self.db.put_task({"type": "CIRCUIT_BREAKER", "agent_id": agent_id, "status": "PENDING"})
94
+
95
+ async def _reset(self, agent_id: str):
96
+ await self.db.put_circuit_breaker(agent_id, {
97
+ "state": CLOSED, "errors": 0, "total": 0, "consecutive_successes": 0,
98
+ })
99
+
100
+ async def _get_config(self, agent_id: str) -> dict:
101
+ agent = await self.db.get_agent(agent_id)
102
+ return agent.get("circuit_breaker_config", DEFAULT_CONFIG) if agent else DEFAULT_CONFIG