petter2025 commited on
Commit
d688dc2
·
verified ·
1 Parent(s): c00fe73

Create intents.py

Browse files
Files changed (1) hide show
  1. infrastructure/intents.py +168 -0
infrastructure/intents.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # agentic_reliability_framework/infrastructure/intents.py
2
+ """
3
+ Infrastructure Intent Schema – Algebraic Data Types for Change Requests.
4
+
5
+ This module defines a family of intents as a discriminated union. Each intent
6
+ represents a proposed infrastructure action. Intents are immutable, self-validating,
7
+ and carry provenance for auditability.
8
+
9
+ The design follows principles of domain-driven design and knowledge engineering,
10
+ using strong typing and semantic constraints to prevent invalid states.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import uuid
16
+ from datetime import datetime
17
+ from enum import Enum
18
+ from typing import Annotated, Any, Dict, Literal, Optional, Union
19
+
20
+ from pydantic import BaseModel, Field, field_validator
21
+ from pydantic.functional_validators import AfterValidator
22
+
23
+ # -----------------------------------------------------------------------------
24
+ # Domain Primitives (NewTypes for type safety)
25
+ # -----------------------------------------------------------------------------
26
+ # These are simple wrappers that enforce type checks at runtime only if validators are added.
27
+ # Here we use them as markers; actual validation occurs in field validators.
28
+ Region = str
29
+ Size = str
30
+ Principal = str
31
+ ResourceScope = str
32
+ ServiceName = str
33
+ ChangeScope = Literal["single_instance", "canary", "global"]
34
+ Environment = Literal["dev", "staging", "prod", "test"]
35
+
36
+ # -----------------------------------------------------------------------------
37
+ # Enums for fixed sets (but extensible via new variants)
38
+ # -----------------------------------------------------------------------------
39
+ class ResourceType(str, Enum):
40
+ """Azure resource types with semantic meaning."""
41
+ VM = "vm"
42
+ STORAGE_ACCOUNT = "storage_account"
43
+ DATABASE = "database"
44
+ KUBERNETES_CLUSTER = "kubernetes_cluster"
45
+ FUNCTION_APP = "function_app"
46
+ VIRTUAL_NETWORK = "virtual_network"
47
+
48
+ # We could add methods here to return associated pricing categories, etc.
49
+
50
+ class PermissionLevel(str, Enum):
51
+ """Access permission levels in increasing order of privilege."""
52
+ READ = "read"
53
+ WRITE = "write"
54
+ ADMIN = "admin"
55
+
56
+ # -----------------------------------------------------------------------------
57
+ # Knowledge Base Stubs (simulated – in production would be loaded from external source)
58
+ # -----------------------------------------------------------------------------
59
+ # These are used for semantic validation. In a real system, they would be fetched
60
+ # from Azure APIs or a configuration service.
61
+ VALID_AZURE_REGIONS = {
62
+ "eastus", "eastus2", "westus", "westeurope", "northeurope",
63
+ "southeastasia", "eastasia", "japaneast", "brazilsouth"
64
+ }
65
+
66
+ # Mapping of resource type to plausible size patterns (simplified)
67
+ RESOURCE_SIZE_PATTERNS = {
68
+ ResourceType.VM: {"Standard_D2s_v3", "Standard_D4s_v3", "Standard_D8s_v3", "Standard_D16s_v3"},
69
+ ResourceType.STORAGE_ACCOUNT: {"50GB", "100GB", "1TB", "10TB"},
70
+ ResourceType.DATABASE: {"Basic", "Standard", "Premium"},
71
+ ResourceType.KUBERNETES_CLUSTER: {"Small", "Medium", "Large"},
72
+ ResourceType.FUNCTION_APP: {"Consumption", "Premium"},
73
+ ResourceType.VIRTUAL_NETWORK: {"default"},
74
+ }
75
+
76
+ # -----------------------------------------------------------------------------
77
+ # Base Intent Class
78
+ # -----------------------------------------------------------------------------
79
+ class Intent(BaseModel):
80
+ """Abstract base for all intents, providing common fields."""
81
+ intent_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="Unique identifier for this intent")
82
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="Time the intent was created")
83
+ requester: Principal = Field(..., description="User or service principal requesting the action")
84
+ provenance: Dict[str, Any] = Field(
85
+ default_factory=dict,
86
+ description="Metadata about how the intent was generated (e.g., agent ID, session)"
87
+ )
88
+
89
+ class Config:
90
+ frozen = True # immutable after creation
91
+ extra = "forbid" # no extra fields
92
+
93
+ # -----------------------------------------------------------------------------
94
+ # Specific Intent Types
95
+ # -----------------------------------------------------------------------------
96
+ class ProvisionResourceIntent(Intent):
97
+ """Request to provision a new Azure resource."""
98
+ intent_type: Literal["provision_resource"] = "provision_resource"
99
+ resource_type: ResourceType
100
+ region: Region
101
+ size: Size
102
+ configuration: Dict[str, Any] = Field(default_factory=dict)
103
+ environment: Environment
104
+
105
+ @field_validator("region")
106
+ def validate_region(cls, v: Region) -> Region:
107
+ if v not in VALID_AZURE_REGIONS:
108
+ raise ValueError(f"Unknown Azure region: {v}")
109
+ return v
110
+
111
+ @field_validator("size")
112
+ def validate_size(cls, v: Size, info) -> Size:
113
+ # info.data contains previously validated fields
114
+ resource_type = info.data.get("resource_type")
115
+ if resource_type and resource_type in RESOURCE_SIZE_PATTERNS:
116
+ if v not in RESOURCE_SIZE_PATTERNS[resource_type]:
117
+ raise ValueError(f"Invalid size '{v}' for resource type {resource_type}")
118
+ return v
119
+
120
+ class DeployConfigurationIntent(Intent):
121
+ """Request to change configuration of an existing service."""
122
+ intent_type: Literal["deploy_config"] = "deploy_config"
123
+ service_name: ServiceName
124
+ change_scope: ChangeScope
125
+ deployment_target: Environment
126
+ risk_level_hint: Optional[Annotated[float, Field(ge=0, le=1)]] = None
127
+ configuration: Dict[str, Any] = Field(default_factory=dict)
128
+
129
+ # Optional: validate that service_name follows naming conventions
130
+ @field_validator("service_name")
131
+ def validate_service_name(cls, v: ServiceName) -> ServiceName:
132
+ if not v or len(v) < 3:
133
+ raise ValueError("Service name must be at least 3 characters")
134
+ return v
135
+
136
+ class GrantAccessIntent(Intent):
137
+ """Request to grant a permission to a principal."""
138
+ intent_type: Literal["grant_access"] = "grant_access"
139
+ principal: Principal
140
+ permission_level: PermissionLevel
141
+ resource_scope: ResourceScope
142
+ justification: Optional[str] = None
143
+
144
+ # Validate resource_scope format (simplified)
145
+ @field_validator("resource_scope")
146
+ def validate_resource_scope(cls, v: ResourceScope) -> ResourceScope:
147
+ if not v.startswith("/"):
148
+ raise ValueError("Resource scope must start with '/'")
149
+ return v
150
+
151
+ # -----------------------------------------------------------------------------
152
+ # Discriminated Union of All Intents
153
+ # -----------------------------------------------------------------------------
154
+ InfrastructureIntent = Annotated[
155
+ Union[ProvisionResourceIntent, DeployConfigurationIntent, GrantAccessIntent],
156
+ Field(discriminator="intent_type")
157
+ ]
158
+
159
+ __all__ = [
160
+ "ResourceType",
161
+ "PermissionLevel",
162
+ "Environment",
163
+ "ChangeScope",
164
+ "ProvisionResourceIntent",
165
+ "DeployConfigurationIntent",
166
+ "GrantAccessIntent",
167
+ "InfrastructureIntent",
168
+ ]