piton-cli 0.4.2__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.
piton/iac/scanner.py ADDED
@@ -0,0 +1,350 @@
1
+ """
2
+ `piton init` — Static Repository & MCP Config Scanner (Uber Argus Pattern).
3
+
4
+ Generates a Day-1 `piton.yaml` (defaulting to `mode: shadow`), `piton.lock`
5
+ (split structural/description hashes after Day-1 poisoning lint), and `.env.agent`
6
+ (format-preserving ghost tokens for zero-secret local prototyping) in <1 second.
7
+ """
8
+
9
+ import base64
10
+ import json
11
+ from pathlib import Path
12
+ import re
13
+ import secrets
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+ from urllib.parse import urlparse
16
+ import yaml
17
+ from pydantic import BaseModel, Field
18
+
19
+ from piton.iac.lockfile import build_lockfile_from_servers
20
+ from piton.iac.poisoning_lint import PoisoningFinding
21
+ from piton.iac.schema import (
22
+ AgentIaCConfig,
23
+ AgentMeta,
24
+ EnforcementMode,
25
+ IdentityConfig,
26
+ IdentityMode,
27
+ LocalDevCredentialSlot,
28
+ ManifestLockfile,
29
+ MCPServerPolicy,
30
+ ParameterBound,
31
+ RateLimitPolicy,
32
+ ToolPolicy,
33
+ ToolTier,
34
+ TrustTier,
35
+ )
36
+
37
+
38
+ MCP_CONFIG_CANDIDATES = (
39
+ ".cursor/mcp.json",
40
+ ".mcp.json",
41
+ "mcp.json",
42
+ "claude_desktop_config.json",
43
+ "mcp_servers.json",
44
+ )
45
+
46
+ ENV_TEMPLATE_CANDIDATES = (
47
+ ".env.example",
48
+ ".env.sample",
49
+ ".env.template",
50
+ )
51
+
52
+ # Env var name patterns -> (slot_key, ghost_format, default_upstream_url)
53
+ KNOWN_PROVIDER_MAP: Tuple[Tuple[str, str, str, str], ...] = (
54
+ ("STRIPE", "stripe_api", "stripe_test", "https://api.stripe.com"),
55
+ ("GITHUB", "github_api", "github", "https://api.github.com"),
56
+ ("SLACK", "slack_api", "slack", "https://slack.com/api"),
57
+ ("OPENAI", "openai_api", "openai", "https://api.openai.com"),
58
+ ("ANTHROPIC", "anthropic_api", "anthropic", "https://api.anthropic.com"),
59
+ ("ZENDESK", "zendesk_api", "generic", "https://example.zendesk.com"),
60
+ ("LINEAR", "linear_api", "generic", "https://api.linear.app"),
61
+ )
62
+
63
+ SECRET_ENV_SUFFIXES = ("_API_KEY", "_SECRET_KEY", "_SECRET", "_TOKEN", "_ACCESS_KEY")
64
+
65
+ BOUNDED_WRITE_KEYWORDS = (
66
+ "delete", "remove", "refund", "transfer", "wire", "payout", "charge",
67
+ "send_", "post_", "publish", "approve", "grant", "revoke", "drop",
68
+ )
69
+
70
+
71
+ def generate_format_preserving_ghost_token(ghost_format: str, slot_name: str = "slot") -> str:
72
+ """
73
+ Generates a harmless placeholder token that satisfies real client SDK prefix &
74
+ structural validators (e.g. Stripe `sk_test_`, GitHub `ghp_`, Slack `xoxb-`, JWT 3-part).
75
+ """
76
+ rand_hex = secrets.token_hex(12)
77
+ fmt = ghost_format.lower()
78
+ if fmt == "stripe_test":
79
+ return f"sk_test_pitonghost_{rand_hex}"
80
+ if fmt == "stripe_live":
81
+ return f"sk_live_pitonghost_{rand_hex}"
82
+ if fmt == "github":
83
+ return f"ghp_pitonghost{rand_hex[:24]}"
84
+ if fmt == "slack":
85
+ return f"xoxb-000000000000-000000000000-pitonghost{rand_hex[:14]}"
86
+ if fmt == "openai":
87
+ return f"sk-proj-pitonghost-{rand_hex}"
88
+ if fmt == "anthropic":
89
+ return f"sk-ant-api03-pitonghost-{rand_hex}"
90
+ if fmt == "jwt":
91
+ hdr = base64.urlsafe_b64encode(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()).decode().rstrip("=")
92
+ payload = base64.urlsafe_b64encode(
93
+ json.dumps({"sub": f"piton_ghost_{slot_name}", "exp": 4102444800}).encode()
94
+ ).decode().rstrip("=")
95
+ sig = base64.urlsafe_b64encode(f"pitonghost_{rand_hex}".encode()).decode().rstrip("=")
96
+ return f"{hdr}.{payload}.{sig}"
97
+ return f"piton_ghost_{slot_name}_{rand_hex}"
98
+
99
+
100
+ def _infer_trust_tier(server_name: str, url: Optional[str]) -> TrustTier:
101
+ if url:
102
+ host = (urlparse(url).hostname or "").lower()
103
+ if host in ("localhost", "127.0.0.1", "::1") or host.endswith((".internal", ".local", ".corp", ".lan")):
104
+ return TrustTier.INTERNAL
105
+ if ".internal." in host:
106
+ return TrustTier.INTERNAL
107
+ # Explicit external public URL -> always third_party unless host itself is internal
108
+ if host:
109
+ return TrustTier.THIRD_PARTY
110
+ lower_name = server_name.lower()
111
+ if any(tok in lower_name for tok in ("internal", "local")):
112
+ return TrustTier.INTERNAL
113
+ return TrustTier.THIRD_PARTY
114
+
115
+
116
+ def _classify_tool_policy(tool: Dict[str, Any]) -> ToolPolicy:
117
+ name = str(tool.get("name") or "").lower()
118
+ is_bounded = any(kw in name for kw in BOUNDED_WRITE_KEYWORDS)
119
+ if not is_bounded:
120
+ if any(name.startswith(p) for p in ("update_", "edit_", "create_", "draft_", "set_")):
121
+ return ToolPolicy(tier=ToolTier.REVERSIBLE_WRITE)
122
+ return ToolPolicy(tier=ToolTier.READ)
123
+
124
+ bounds: Dict[str, ParameterBound] = {}
125
+ props = (tool.get("inputSchema") or {}).get("properties") or {}
126
+ if isinstance(props, dict):
127
+ for pname, pdef in props.items():
128
+ if not isinstance(pdef, dict):
129
+ continue
130
+ plower = pname.lower()
131
+ if plower in ("amount", "total", "price", "refund_amount") and pdef.get("type") in ("number", "integer"):
132
+ bounds[pname] = ParameterBound(min=0.01, max=100.0)
133
+ elif "email" in plower or "domain" in plower or "recipient" in plower:
134
+ bounds[pname] = ParameterBound(allow_domains=["example.com"])
135
+
136
+ return ToolPolicy(
137
+ tier=ToolTier.BOUNDED_WRITE,
138
+ idempotency_key="required",
139
+ parameter_bounds=bounds,
140
+ rate_limit=RateLimitPolicy(max_calls_per_trace=5),
141
+ )
142
+
143
+
144
+ class InitScanResult(BaseModel):
145
+ config: AgentIaCConfig
146
+ lockfile: ManifestLockfile
147
+ ghost_env: Dict[str, str] = Field(default_factory=dict)
148
+ poisoning_findings: List[PoisoningFinding] = Field(default_factory=list)
149
+ discovered_files: List[str] = Field(default_factory=list)
150
+
151
+
152
+ def scan_repository(
153
+ repo_root: Path,
154
+ agent_id: Optional[str] = None,
155
+ owner: str = "platform-team@example.com",
156
+ live_server_tools: Optional[Dict[str, List[Dict[str, Any]]]] = None,
157
+ allow_poisoned: bool = False,
158
+ ) -> InitScanResult:
159
+ """
160
+ Statically scans a repository for MCP server configs and env secret templates,
161
+ runs Day-1 poisoning lint on any discovered/live tool manifests, and produces
162
+ `piton.yaml` (shadow mode), `piton.lock`, and `.env.agent`.
163
+ """
164
+ repo_root = Path(repo_root).resolve()
165
+ resolved_agent_id = agent_id or re.sub(r"[^a-zA-Z0-9_-]+", "-", repo_root.name).strip("-").lower() or "agent"
166
+
167
+ discovered_files: List[str] = []
168
+ mcp_servers: Dict[str, MCPServerPolicy] = {}
169
+ servers_for_lock: Dict[str, Tuple[TrustTier, Optional[str], List[Dict[str, Any]]]] = {}
170
+ local_creds: Dict[str, LocalDevCredentialSlot] = {}
171
+ ghost_env: Dict[str, str] = {}
172
+
173
+ # 1. Discover MCP configurations
174
+ for rel in MCP_CONFIG_CANDIDATES:
175
+ candidate = repo_root / rel
176
+ if not candidate.is_file():
177
+ continue
178
+ try:
179
+ raw = json.loads(candidate.read_text(encoding="utf-8"))
180
+ except Exception:
181
+ continue
182
+ discovered_files.append(rel)
183
+ servers_dict = raw.get("mcpServers") or raw.get("servers") or {}
184
+ if not isinstance(servers_dict, dict):
185
+ continue
186
+ for srv_name, srv_cfg in servers_dict.items():
187
+ if not isinstance(srv_cfg, dict):
188
+ continue
189
+ url = srv_cfg.get("url")
190
+ cmd = srv_cfg.get("command")
191
+ args = [str(a) for a in (srv_cfg.get("args") or [])]
192
+ trust = _infer_trust_tier(srv_name, url)
193
+
194
+ tools_list: List[Dict[str, Any]] = []
195
+ if live_server_tools and srv_name in live_server_tools:
196
+ tools_list = live_server_tools[srv_name]
197
+ elif isinstance(srv_cfg.get("tools"), list):
198
+ tools_list = srv_cfg["tools"]
199
+
200
+ tool_policies = {
201
+ str(t["name"]): _classify_tool_policy(t)
202
+ for t in tools_list
203
+ if isinstance(t, dict) and t.get("name")
204
+ }
205
+
206
+ mcp_servers[srv_name] = MCPServerPolicy(
207
+ url=url,
208
+ command=cmd,
209
+ args=args,
210
+ trust_tier=trust,
211
+ tools=tool_policies,
212
+ )
213
+ servers_for_lock[srv_name] = (trust, url, tools_list)
214
+
215
+ # Also include any live_server_tools passed directly that weren't in a static JSON file
216
+ if live_server_tools:
217
+ for srv_name, tools_list in live_server_tools.items():
218
+ if srv_name not in mcp_servers:
219
+ trust = _infer_trust_tier(srv_name, None)
220
+ mcp_servers[srv_name] = MCPServerPolicy(
221
+ trust_tier=trust,
222
+ tools={
223
+ str(t["name"]): _classify_tool_policy(t)
224
+ for t in tools_list
225
+ if isinstance(t, dict) and t.get("name")
226
+ },
227
+ )
228
+ servers_for_lock[srv_name] = (trust, None, tools_list)
229
+
230
+ # 2. Discover credential slots from .env.example / docker-compose templates (never commit raw prod .env)
231
+ env_var_names: List[str] = []
232
+ for rel in ENV_TEMPLATE_CANDIDATES:
233
+ candidate = repo_root / rel
234
+ if not candidate.is_file():
235
+ continue
236
+ discovered_files.append(rel)
237
+ for line in candidate.read_text(encoding="utf-8").splitlines():
238
+ stripped = line.strip()
239
+ if not stripped or stripped.startswith("#") or "=" not in stripped:
240
+ continue
241
+ var = stripped.split("=", 1)[0].strip()
242
+ if var and any(var.upper().endswith(sfx) for sfx in SECRET_ENV_SUFFIXES):
243
+ env_var_names.append(var)
244
+
245
+ for dc_name in ("docker-compose.yml", "docker-compose.yaml"):
246
+ dc_path = repo_root / dc_name
247
+ if not dc_path.is_file():
248
+ continue
249
+ try:
250
+ dc_data = yaml.safe_load(dc_path.read_text(encoding="utf-8")) or {}
251
+ except Exception:
252
+ continue
253
+ discovered_files.append(dc_name)
254
+ for svc in (dc_data.get("services") or {}).values():
255
+ if not isinstance(svc, dict):
256
+ continue
257
+ env_section = svc.get("environment")
258
+ if isinstance(env_section, dict):
259
+ for k in env_section.keys():
260
+ if any(str(k).upper().endswith(sfx) for sfx in SECRET_ENV_SUFFIXES):
261
+ env_var_names.append(str(k))
262
+ elif isinstance(env_section, list):
263
+ for item in env_section:
264
+ k = str(item).split("=", 1)[0].strip()
265
+ if any(k.upper().endswith(sfx) for sfx in SECRET_ENV_SUFFIXES):
266
+ env_var_names.append(k)
267
+
268
+ for var in sorted(set(env_var_names)):
269
+ var_up = var.upper()
270
+ slot_key = var.lower()
271
+ ghost_fmt = "generic"
272
+ upstream = "https://api.example.com"
273
+ for prefix, mapped_slot, mapped_fmt, mapped_url in KNOWN_PROVIDER_MAP:
274
+ if prefix in var_up:
275
+ slot_key = mapped_slot
276
+ ghost_fmt = mapped_fmt
277
+ upstream = mapped_url
278
+ break
279
+ if "JWT" in var_up:
280
+ ghost_fmt = "jwt"
281
+
282
+ host = urlparse(upstream).hostname or "api.example.com"
283
+ local_creds[slot_key] = LocalDevCredentialSlot(
284
+ ghost_format=ghost_fmt,
285
+ source=f"env://{var}",
286
+ upstream_base_url=upstream,
287
+ allowed_hosts=[host],
288
+ allowed_methods=["GET", "POST"],
289
+ allowed_path_prefixes=["/"],
290
+ follow_redirects=False,
291
+ redact_in_responses=True,
292
+ )
293
+ ghost_env[var] = generate_format_preserving_ghost_token(ghost_fmt, slot_key)
294
+ ghost_env[f"{var}_BASE_URL"] = f"http://localhost:8080/gw/{slot_key}"
295
+
296
+ lockfile, poisoning_findings = build_lockfile_from_servers(
297
+ servers_for_lock, allow_poisoned=allow_poisoned
298
+ )
299
+
300
+ # Ensure Day-1 quarantined tools are also excluded from piton.yaml allowlist
301
+ if not allow_poisoned:
302
+ for srv_name, srv_pol in mcp_servers.items():
303
+ pinned_srv = lockfile.servers.get(srv_name)
304
+ if pinned_srv is not None:
305
+ srv_pol.tools = {
306
+ tname: tpol
307
+ for tname, tpol in srv_pol.tools.items()
308
+ if tname in pinned_srv.tools
309
+ }
310
+
311
+ config = AgentIaCConfig(
312
+ version="1",
313
+ agent=AgentMeta(id=resolved_agent_id, owner=owner, mode=EnforcementMode.SHADOW),
314
+ identity=IdentityConfig(mode=IdentityMode.OIDC_OBO, require_delegated_sub=True),
315
+ local_dev_credentials=local_creds,
316
+ mcp_servers=mcp_servers,
317
+ )
318
+
319
+ return InitScanResult(
320
+ config=config,
321
+ lockfile=lockfile,
322
+ ghost_env=ghost_env,
323
+ poisoning_findings=poisoning_findings,
324
+ discovered_files=discovered_files,
325
+ )
326
+
327
+
328
+ def write_init_artifacts(repo_root: Path, result: InitScanResult) -> Dict[str, Path]:
329
+ """Writes `piton.yaml`, `piton.lock`, and `.env.agent` to the repository root."""
330
+ repo_root = Path(repo_root).resolve()
331
+ yaml_path = repo_root / "piton.yaml"
332
+ lock_path = repo_root / "piton.lock"
333
+ env_path = repo_root / ".env.agent"
334
+
335
+ result.config.save_file(yaml_path)
336
+ result.lockfile.save_file(lock_path)
337
+
338
+ env_lines = [
339
+ "# Auto-generated by `piton init` — safe format-preserving ghost handles (ZERO real secrets)",
340
+ "# Real secrets stay in the host/gateway environment and are swapped at the boundary.",
341
+ ]
342
+ for k, v in sorted(result.ghost_env.items()):
343
+ env_lines.append(f"{k}={v}")
344
+ env_path.write_text("\n".join(env_lines) + "\n", encoding="utf-8")
345
+
346
+ return {
347
+ "piton.yaml": yaml_path,
348
+ "piton.lock": lock_path,
349
+ ".env.agent": env_path,
350
+ }
piton/iac/schema.py ADDED
@@ -0,0 +1,256 @@
1
+ """
2
+ Declarative Agent IaC (`piton.yaml`) and Split-Hash MCP Manifest Lockfile (`piton.lock`) Schemas.
3
+
4
+ Design guarantees:
5
+ - Human intent & parameter-bounded policies live in `piton.yaml` (committed to git).
6
+ - Machine-managed SHA-256 hashes live in `piton.lock` (eliminating YAML merge conflicts).
7
+ - Production identity defaults to fail-closed OIDC/OBO delegation (`oidc_obo`) with RS256/ES256
8
+ JWKS verification and stateless W3C `traceparent` correlation (MCP 2026-07-28 compatible).
9
+ """
10
+
11
+ from enum import Enum
12
+ import hashlib
13
+ import json
14
+ from pathlib import Path
15
+ import time
16
+ from typing import Any, Dict, List, Optional
17
+ import yaml
18
+ from pydantic import BaseModel, Field
19
+
20
+
21
+ def normalize_json_numbers(obj: Any) -> Any:
22
+ """
23
+ Normalizes whole-number floats (`50.0` -> `50`, `0.0` -> `0`) across nested JSON structures
24
+ so Python Pydantic serialization matches Go `encoding/json` bit-for-bit.
25
+ """
26
+ if isinstance(obj, bool) or obj is None:
27
+ return obj
28
+ if isinstance(obj, float) and obj.is_integer():
29
+ return int(obj)
30
+ if isinstance(obj, dict):
31
+ return {k: normalize_json_numbers(v) for k, v in obj.items()}
32
+ if isinstance(obj, list):
33
+ return [normalize_json_numbers(v) for v in obj]
34
+ return obj
35
+
36
+
37
+ class EnforcementMode(str, Enum):
38
+ SHADOW = "shadow"
39
+ ENFORCE = "enforce"
40
+
41
+
42
+ class IdentityMode(str, Enum):
43
+ OIDC_OBO = "oidc_obo"
44
+ LOCAL_DEV = "local_dev"
45
+
46
+
47
+ class TrustTier(str, Enum):
48
+ INTERNAL = "internal"
49
+ THIRD_PARTY = "third_party"
50
+
51
+
52
+ class ToolTier(str, Enum):
53
+ READ = "read"
54
+ REVERSIBLE_WRITE = "reversible_write"
55
+ BOUNDED_WRITE = "bounded_write"
56
+
57
+
58
+ class BoundExceededAction(str, Enum):
59
+ MRTR_ESCALATE = "mrtr_escalate" # MCP 2026-07-28 out-of-band elicitation
60
+ BLOCK = "block"
61
+ WARN = "warn"
62
+
63
+
64
+ class AgentMeta(BaseModel):
65
+ id: str = Field(..., description="Unique agent identifier")
66
+ owner: str = Field(default="platform-team@example.com", description="Owning engineering team or email")
67
+ mode: EnforcementMode = Field(default=EnforcementMode.SHADOW, description="shadow (observe) or enforce")
68
+
69
+
70
+ class IdentityConfig(BaseModel):
71
+ mode: IdentityMode = Field(default=IdentityMode.OIDC_OBO)
72
+ issuer: Optional[str] = Field(default=None, description="OIDC issuer URL (Okta / Entra / Auth0)")
73
+ jwks_url: Optional[str] = Field(default=None, description="Explicit JWKS URL (auto-discovered from issuer if omitted)")
74
+ audience: Optional[str] = Field(default=None, description="Expected JWT aud claim")
75
+ verify_jwt_signature: bool = Field(
76
+ default=True,
77
+ description="Cryptographically verify RS256/ES256 JWTs via JWKS whenever issuer or jwks_url is configured",
78
+ )
79
+ allow_trusted_headers: bool = Field(
80
+ default=False,
81
+ description="Explicit opt-in for trusting upstream IdP-injected X-OBO-Principal headers inside an authenticated mesh",
82
+ )
83
+ require_delegated_sub: bool = Field(
84
+ default=True,
85
+ description="Require OBO user+agent principal claims in production enforce mode",
86
+ )
87
+ correlate_header: str = Field(
88
+ default="traceparent",
89
+ description="Stateless MCP 2026-07-28 correlation header (W3C traceparent)",
90
+ )
91
+
92
+
93
+ class LocalDevCredentialSlot(BaseModel):
94
+ """Local-dev-only zero-secret credential slot using format-preserving ghost tokens."""
95
+ ghost_format: str = Field(
96
+ default="generic",
97
+ description="Format template: stripe_test, stripe_live, github, slack, openai, jwt, generic",
98
+ )
99
+ source: str = Field(..., description="env://VAR_NAME or file:///path/to/secret")
100
+ upstream_base_url: str = Field(..., description="Target HTTPS base URL")
101
+ allowed_hosts: List[str] = Field(default_factory=list)
102
+ allowed_methods: List[str] = Field(default_factory=lambda: ["GET", "POST"])
103
+ allowed_path_prefixes: List[str] = Field(default_factory=lambda: ["/"])
104
+ follow_redirects: bool = Field(default=False, description="Never leak credentials across 3xx redirects")
105
+ redact_in_responses: bool = Field(default=True)
106
+
107
+
108
+ class ParameterBound(BaseModel):
109
+ """Deterministic argument-level constraint (Progent/Cedar-style bounded autonomy)."""
110
+ required: bool = Field(default=True, description="Fail closed if this bounded parameter is omitted")
111
+ min: Optional[float] = None
112
+ max: Optional[float] = None
113
+ enum: Optional[List[Any]] = None
114
+ allow_domains: Optional[List[str]] = None
115
+ deny_domains: Optional[List[str]] = None
116
+ regex: Optional[str] = None
117
+ max_length: Optional[int] = None
118
+
119
+
120
+ class RateLimitPolicy(BaseModel):
121
+ max_calls_per_trace: Optional[int] = Field(default=None, ge=1)
122
+ max_calls_per_hour: Optional[int] = Field(
123
+ default=None,
124
+ ge=1,
125
+ description="Rolling 1h per-principal call ceiling (stops cross-trace smurfing)",
126
+ )
127
+ max_sum_per_hour: Optional[float] = Field(
128
+ default=None,
129
+ gt=0,
130
+ description="Rolling 1h cumulative numeric ceiling keyed on verified OBO principal",
131
+ )
132
+ sum_parameter: str = Field(default="amount", description="Argument field summed for max_sum_per_hour")
133
+
134
+
135
+ class ToolPolicy(BaseModel):
136
+ tier: ToolTier = Field(default=ToolTier.READ)
137
+ idempotency_key: Optional[str] = Field(
138
+ default=None,
139
+ description="Set to 'required' to enforce single-use idempotency on bounded writes",
140
+ )
141
+ parameter_bounds: Dict[str, ParameterBound] = Field(default_factory=dict)
142
+ rate_limit: Optional[RateLimitPolicy] = None
143
+ response_projection: Optional[List[str]] = Field(
144
+ default=None,
145
+ description="Optional field allowlist (dot-paths supported) projected from MCP tool responses to cut token cost & exfiltration surface",
146
+ )
147
+ on_bound_exceeded: BoundExceededAction = Field(default=BoundExceededAction.MRTR_ESCALATE)
148
+
149
+
150
+ class MCPServerPolicy(BaseModel):
151
+ url: Optional[str] = None
152
+ command: Optional[str] = Field(default=None, description="STDIO command if discovered locally")
153
+ args: List[str] = Field(default_factory=list)
154
+ trust_tier: TrustTier = Field(default=TrustTier.THIRD_PARTY)
155
+ strict_unknown_tools: bool = Field(
156
+ default=True,
157
+ description="Fail closed on unlisted tools for this server in enforce mode",
158
+ )
159
+ tools: Dict[str, ToolPolicy] = Field(default_factory=dict)
160
+
161
+
162
+ class AgentIaCConfig(BaseModel):
163
+ """Top-level `piton.yaml` schema."""
164
+ version: str = Field(default="1")
165
+ agent: AgentMeta
166
+ identity: IdentityConfig = Field(default_factory=IdentityConfig)
167
+ local_dev_credentials: Dict[str, LocalDevCredentialSlot] = Field(default_factory=dict)
168
+ mcp_servers: Dict[str, MCPServerPolicy] = Field(default_factory=dict)
169
+
170
+ def canonical_sha256(self) -> str:
171
+ payload = normalize_json_numbers(self.model_dump(mode="json", exclude_none=True))
172
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
173
+ return hashlib.sha256(canonical).hexdigest()
174
+
175
+ def to_yaml(self) -> str:
176
+ return yaml.safe_dump(
177
+ self.model_dump(mode="json", exclude_none=True),
178
+ sort_keys=False,
179
+ default_flow_style=False,
180
+ )
181
+
182
+ @classmethod
183
+ def from_yaml(cls, raw_yaml: str) -> "AgentIaCConfig":
184
+ data = yaml.safe_load(raw_yaml) or {}
185
+ return cls.model_validate(data)
186
+
187
+ @classmethod
188
+ def load_file(cls, path: Path) -> "AgentIaCConfig":
189
+ return cls.from_yaml(path.read_text(encoding="utf-8"))
190
+
191
+ def save_file(self, path: Path) -> None:
192
+ path.parent.mkdir(parents=True, exist_ok=True)
193
+ path.write_text(self.to_yaml(), encoding="utf-8")
194
+
195
+
196
+ # =============================================================================
197
+ # Split-Hash MCP Manifest Lockfile (`piton.lock`)
198
+ # =============================================================================
199
+
200
+ class PinnedToolEntry(BaseModel):
201
+ """
202
+ Separates structural schema pin (`name` + canonical `inputSchema`) from prose
203
+ description pin (`description`) so benign internal docstring edits warn instead
204
+ of causing outages, while schema mutations or third-party rug pulls hard-block.
205
+ """
206
+ structural_sha256: str
207
+ description_sha256: str
208
+ description_preview: str = ""
209
+ poisoning_lint_passed: bool = True
210
+ poisoning_warnings: List[str] = Field(default_factory=list)
211
+
212
+
213
+ class PinnedServerManifest(BaseModel):
214
+ trust_tier: TrustTier = TrustTier.THIRD_PARTY
215
+ url: Optional[str] = None
216
+ tools: Dict[str, PinnedToolEntry] = Field(default_factory=dict)
217
+
218
+
219
+ class ManifestLockfile(BaseModel):
220
+ """Top-level `piton.lock` schema."""
221
+ version: str = Field(default="1")
222
+ generated_at: float = Field(default_factory=time.time)
223
+ servers: Dict[str, PinnedServerManifest] = Field(default_factory=dict)
224
+
225
+ def canonical_sha256(self) -> str:
226
+ # Exclude timestamp so identical pin sets yield identical compliance ledger hashes
227
+ payload = normalize_json_numbers(
228
+ {
229
+ "version": self.version,
230
+ "servers": {
231
+ srv_name: srv.model_dump(mode="json", exclude_none=True)
232
+ for srv_name, srv in sorted(self.servers.items())
233
+ },
234
+ }
235
+ )
236
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
237
+ return hashlib.sha256(canonical).hexdigest()
238
+
239
+ def to_json(self) -> str:
240
+ return json.dumps(self.model_dump(mode="json"), indent=2, sort_keys=True) + "\n"
241
+
242
+ @classmethod
243
+ def from_json(cls, raw_json: str) -> "ManifestLockfile":
244
+ return cls.from_dict(json.loads(raw_json))
245
+
246
+ @classmethod
247
+ def from_dict(cls, data: Dict[str, Any]) -> "ManifestLockfile":
248
+ return cls.model_validate(data)
249
+
250
+ @classmethod
251
+ def load_file(cls, path: Path) -> "ManifestLockfile":
252
+ return cls.from_json(path.read_text(encoding="utf-8"))
253
+
254
+ def save_file(self, path: Path) -> None:
255
+ path.parent.mkdir(parents=True, exist_ok=True)
256
+ path.write_text(self.to_json(), encoding="utf-8")