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/cli.py ADDED
@@ -0,0 +1,716 @@
1
+ """
2
+ Unified Piton Control Loop CLI (`piton`).
3
+
4
+ Commands:
5
+ - `piton init [--repo .]` — Scan repo MCP configs & env templates, run Day-1 poisoning lint,
6
+ and generate `piton.yaml` (shadow mode), `piton.lock`, and `.env.agent`.
7
+ - `piton lock [--diff | --update] [--manifest <json>]` — Verify or update split-hash MCP pins
8
+ with GitHub PR-ready markdown diff output for CI gates.
9
+ - `piton replay --config piton.yaml --traces .piton/traces.jsonl [--simulate-enforce]`
10
+ — Replay recorded shadow traces against candidate policies to reach 0% false blocks before enforcement.
11
+ - `piton ledger-verify --traces .piton/traces.jsonl` — Verify HMAC chain integrity of
12
+ the version-pinned decision ledger.
13
+ - `piton top --traces .piton/traces.jsonl` — Stream/display live flight-recorder events.
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ from pathlib import Path
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from typing import Any, Dict, List, Optional
25
+ import urllib.request
26
+
27
+ from piton.iac.agent_config_lint import scan_agent_supply_chain
28
+ from piton.iac.lockfile import (
29
+ DriftAction,
30
+ DriftKind,
31
+ ManifestDriftItem,
32
+ build_lockfile_from_servers,
33
+ detect_cross_server_shadowing,
34
+ diff_lockfiles,
35
+ render_diff_markdown,
36
+ verify_tools_list,
37
+ )
38
+ from piton.iac.mcp_probe import probe_configured_servers, wrap_stdio_mcp
39
+ from piton.iac.scanner import scan_repository, write_init_artifacts
40
+ from piton.iac.replay import (
41
+ SignedDecisionLedger,
42
+ export_cedar_policies,
43
+ export_cel_policies,
44
+ load_otel_or_ledger_records,
45
+ replay_traces,
46
+ )
47
+ from piton.iac.schema import AgentIaCConfig, ManifestLockfile, TrustTier
48
+
49
+
50
+ def _default_config_name() -> str:
51
+ return "piton.yaml"
52
+
53
+
54
+ def _default_lock_name() -> str:
55
+ return "piton.lock"
56
+
57
+
58
+ def _cmd_scan(args: argparse.Namespace) -> int:
59
+ """
60
+ Fast, zero-config static scan for AI coding-agent supply-chain attacks:
61
+ - `.claude/settings.json` hook RCE (`curl|sh`, reverse shells, credential exfil, unsafe Bash wildcards)
62
+ - `.vscode/tasks.json` `folderOpen` autorun RCE
63
+ - `.cursor/rules/*`, `.cursorrules`, `CLAUDE.md`, `AGENTS.md`, skills/commands Unicode & prompt-injection poisoning
64
+ """
65
+ repo = Path(args.repo).resolve()
66
+ cfg_scan = scan_agent_supply_chain(repo)
67
+
68
+ if getattr(args, "json", False):
69
+ print(cfg_scan.model_dump_json(indent=2))
70
+ return 1 if cfg_scan.critical_or_high_count > 0 else 0
71
+
72
+ print(f"Piton Supply-Chain Scan — repo='{repo.name}'")
73
+ print(f" Scanned agent files: {', '.join(cfg_scan.scanned_files) or 'none'}")
74
+ if not cfg_scan.findings:
75
+ print(" Status: CLEAN (0 findings)")
76
+ return 0
77
+
78
+ print(f" Status: FLAGGED ({len(cfg_scan.findings)} finding(s), {cfg_scan.critical_or_high_count} CRITICAL/HIGH)")
79
+ for f in cfg_scan.findings:
80
+ print(f" - [{f.severity.value.upper()}] {f.tool_name} ({f.field_path}) [{f.rule_id}]: {f.message}")
81
+ if f.matched_snippet:
82
+ print(f" snippet: {f.matched_snippet}")
83
+ return 1 if cfg_scan.critical_or_high_count > 0 else 0
84
+
85
+
86
+ def _cmd_init(args: argparse.Namespace) -> int:
87
+ repo = Path(args.repo).resolve()
88
+ live_tools: Optional[Dict[str, List[Dict[str, Any]]]] = None
89
+ if args.manifest:
90
+ live_tools = json.loads(Path(args.manifest).read_text(encoding="utf-8"))
91
+ elif args.probe:
92
+ # First pass discovers MCP server URLs/commands from repo configs, then probes them live!
93
+ pre = scan_repository(repo_root=repo, agent_id=args.agent_id, owner=args.owner)
94
+ probed, probe_errs = probe_configured_servers(pre.config, timeout=args.probe_timeout)
95
+ live_tools = probed
96
+ for srv_name, err in probe_errs.items():
97
+ print(f"[warn] Live probe failed for MCP server '{srv_name}': {err}", file=sys.stderr)
98
+
99
+ res = scan_repository(
100
+ repo_root=repo,
101
+ agent_id=args.agent_id,
102
+ owner=args.owner,
103
+ live_server_tools=live_tools,
104
+ allow_poisoned=args.allow_poisoned,
105
+ )
106
+ paths = write_init_artifacts(repo, res)
107
+
108
+ agent_cfg_scan = scan_agent_supply_chain(repo)
109
+ print(f"Piton initialized for agent '{res.config.agent.id}' (mode={res.config.agent.mode.value})")
110
+ all_discovered = list(dict.fromkeys(res.discovered_files + agent_cfg_scan.scanned_files))
111
+ print(f" Discovered files: {', '.join(all_discovered) or 'none'}")
112
+ for label, p in paths.items():
113
+ print(f" Wrote {label}: {p}")
114
+
115
+ all_findings = list(res.poisoning_findings) + list(agent_cfg_scan.findings)
116
+ if all_findings:
117
+ print(f"\n[!] Day-1 Supply-Chain & MCP Poisoning Linter flagged {len(all_findings)} finding(s):")
118
+ for f in all_findings:
119
+ target = f"{f.server_name}: {f.tool_name}" if f.server_name in ("agent-config", "agent-rules", "mcp-config") else f"{f.server_name}.{f.tool_name}"
120
+ print(f" - [{f.severity.value.upper()}] {target} ({f.rule_id}): {f.message}")
121
+ if not args.allow_poisoned:
122
+ if any(f.severity.value in ("critical", "high") for f in res.poisoning_findings):
123
+ print(" Quarantined CRITICAL/HIGH MCP tools were excluded from piton.yaml and piton.lock.")
124
+ return 2
125
+ return 0
126
+
127
+
128
+ def _cmd_lock(args: argparse.Namespace) -> int:
129
+ lock_path = Path(args.lockfile)
130
+ config_path = Path(args.config)
131
+ config = AgentIaCConfig.load_file(config_path) if config_path.is_file() else None
132
+ probe_errs: Dict[str, str] = {}
133
+
134
+ if args.manifest:
135
+ manifest_path = Path(args.manifest)
136
+ if not manifest_path.is_file():
137
+ print(f"Error: manifest file not found at {manifest_path}.", file=sys.stderr)
138
+ return 1
139
+ manifest_data: Dict[str, List[Dict[str, Any]]] = json.loads(
140
+ manifest_path.read_text(encoding="utf-8")
141
+ )
142
+ elif args.probe and config is not None:
143
+ manifest_data, probe_errs = probe_configured_servers(config, timeout=getattr(args, "probe_timeout", 8.0))
144
+ for srv_name, err in probe_errs.items():
145
+ print(f"[warn] Live probe failed for MCP server '{srv_name}': {err}", file=sys.stderr)
146
+ else:
147
+ print("Error: provide --manifest <json> or --probe with piton.yaml.", file=sys.stderr)
148
+ return 1
149
+
150
+ servers_for_lock = {}
151
+ for srv_name, tools in manifest_data.items():
152
+ trust = (
153
+ config.mcp_servers[srv_name].trust_tier
154
+ if config and srv_name in config.mcp_servers
155
+ else TrustTier.THIRD_PARTY
156
+ )
157
+ url = config.mcp_servers[srv_name].url if config and srv_name in config.mcp_servers else None
158
+ servers_for_lock[srv_name] = (trust, url, tools)
159
+
160
+ shadowing = detect_cross_server_shadowing(manifest_data)
161
+ if args.update:
162
+ if probe_errs:
163
+ print("Error: refusing to update lockfile because one or more MCP servers failed to probe.", file=sys.stderr)
164
+ return 1
165
+ new_lock, findings = build_lockfile_from_servers(servers_for_lock, allow_poisoned=args.allow_poisoned)
166
+ new_lock.save_file(lock_path)
167
+ print(f"Updated {lock_path} (sha256={new_lock.canonical_sha256()[:16]}...)")
168
+ if findings:
169
+ print(f"Poisoning warnings/quarantined items: {len(findings)}")
170
+ return 0
171
+
172
+ if not lock_path.is_file():
173
+ print(f"Error: lockfile not found at {lock_path}. Run `piton init` first.", file=sys.stderr)
174
+ return 1
175
+
176
+ existing_lock = ManifestLockfile.load_file(lock_path)
177
+
178
+ if args.diff:
179
+ new_lock, poison_findings = build_lockfile_from_servers(servers_for_lock, allow_poisoned=True)
180
+ diff_res = diff_lockfiles(existing_lock, new_lock)
181
+ diff_res.drifts.extend(shadowing)
182
+ diff_res.blocked_count += len(shadowing)
183
+ # Fail closed when a pinned server fails live probing
184
+ for srv_name, err in probe_errs.items():
185
+ if srv_name in existing_lock.servers:
186
+ diff_res.drifts.append(
187
+ ManifestDriftItem(
188
+ server_name=srv_name,
189
+ tool_name="*",
190
+ kind=DriftKind.PROBE_ERROR,
191
+ action=DriftAction.BLOCK,
192
+ message=f"Live probe failed for pinned server '{srv_name}': {err}",
193
+ )
194
+ )
195
+ diff_res.blocked_count += 1
196
+ # Include static coding-agent hook/skill/rules RCE findings when scanning repo
197
+ if not getattr(args, "no_agent_scan", False):
198
+ repo_dir = Path(getattr(args, "repo", ".") or ".").resolve()
199
+ if repo_dir.is_dir():
200
+ agent_scan = scan_agent_supply_chain(repo_dir)
201
+ poison_findings.extend(agent_scan.findings)
202
+ # Always block CI on CRITICAL/HIGH Day-1 or rug-pull poisoning even on internal servers
203
+ for pf in poison_findings:
204
+ if pf.severity.value in ("critical", "high"):
205
+ diff_res.drifts.append(
206
+ ManifestDriftItem(
207
+ server_name=pf.server_name,
208
+ tool_name=pf.tool_name,
209
+ kind=DriftKind.DAY1_POISONING,
210
+ action=DriftAction.BLOCK,
211
+ message=f"Poisoning detected ({pf.rule_id}): {pf.message}",
212
+ )
213
+ )
214
+ diff_res.blocked_count += 1
215
+ diff_res.passed = diff_res.blocked_count == 0
216
+ print(render_diff_markdown(diff_res))
217
+ return 0 if diff_res.passed else 1
218
+
219
+ # Live/CI verification mode
220
+ all_passed = len(shadowing) == 0 and not any(s in existing_lock.servers for s in probe_errs)
221
+ for srv_name, err in probe_errs.items():
222
+ if srv_name in existing_lock.servers:
223
+ print(f"[BLOCK] Live probe failed for pinned server '{srv_name}': {err}")
224
+ for s in shadowing:
225
+ print(f"[BLOCK] {s.message}")
226
+ for srv_name, tools in manifest_data.items():
227
+ res = verify_tools_list(existing_lock, srv_name, tools)
228
+ if not res.passed:
229
+ all_passed = False
230
+ print(render_diff_markdown(res))
231
+ return 0 if all_passed else 1
232
+
233
+
234
+ def _cmd_replay(args: argparse.Namespace) -> int:
235
+ cfg_path = Path(args.config)
236
+ if not cfg_path.is_file():
237
+ print(f"Error: config file not found at {cfg_path}. Run `piton init` first.", file=sys.stderr)
238
+ return 1
239
+ config = AgentIaCConfig.load_file(cfg_path)
240
+ records = load_otel_or_ledger_records(Path(args.traces))
241
+ report = replay_traces(config, records, simulate_enforce=args.simulate_enforce)
242
+
243
+ if args.export in ("cel", "cedar"):
244
+ if args.strict and not report.ready_to_enforce:
245
+ print(
246
+ f"Error: replay reported {report.blocked_or_escalated_count}/{report.total_replayed} "
247
+ f"blocked/escalated calls ({report.false_block_rate_pct}%); refusing to export under --strict.",
248
+ file=sys.stderr,
249
+ )
250
+ return 1
251
+ if not report.ready_to_enforce and report.total_replayed > 0:
252
+ print(
253
+ f"[warn] Exporting current {cfg_path.name} with {report.blocked_or_escalated_count}/{report.total_replayed} "
254
+ f"uncalibrated call(s) ({report.false_block_rate_pct}%); pass --strict to block uncalibrated exports.",
255
+ file=sys.stderr,
256
+ )
257
+ print(export_cel_policies(config) if args.export == "cel" else export_cedar_policies(config))
258
+ return 0
259
+
260
+ if args.json:
261
+ print(report.model_dump_json(indent=2))
262
+ else:
263
+ print(f"Piton Policy Replay — agent='{config.agent.id}' (simulate_enforce={args.simulate_enforce})")
264
+ print(f" Replayed calls: {report.total_replayed}")
265
+ print(f" Allowed: {report.allowed_count}")
266
+ print(f" Blocked / Escalated: {report.blocked_or_escalated_count} ({report.false_block_rate_pct}%)")
267
+ readiness = "YES" if report.ready_to_enforce else "NO"
268
+ if report.ready_to_enforce and report.total_replayed < 20:
269
+ readiness += f" (low sample size: {report.total_replayed} calls; recommend >= 20)"
270
+ print(f" Ready to enforce: {readiness}")
271
+ if report.suggestions:
272
+ print("\nCalibration Suggestions:")
273
+ for s in report.suggestions:
274
+ print(f" - [{s.rule_id}] {s.server_name}.{s.tool_name}: {s.suggestion}")
275
+
276
+ return 0 if report.ready_to_enforce or not args.strict else 1
277
+
278
+
279
+ def _cmd_ledger_verify(args: argparse.Namespace) -> int:
280
+ signing_key = os.getenv("PITON_LEDGER_SIGNING_KEY", "piton-ledger-signing-key").encode("utf-8")
281
+ ledger = SignedDecisionLedger(Path(args.traces), signing_key=signing_key)
282
+ ok, err = ledger.verify_chain()
283
+ if ok:
284
+ print(f"Ledger integrity VERIFIED ({len(ledger.load_records())} chained records).")
285
+ return 0
286
+ print(f"Ledger integrity FAILED: {err}", file=sys.stderr)
287
+ return 1
288
+
289
+
290
+ def _cmd_top(args: argparse.Namespace) -> int:
291
+ traces_path = Path(args.traces)
292
+ if not traces_path.is_file():
293
+ print(f"No trace ledger found at {traces_path} yet.")
294
+ return 0
295
+
296
+ lines = traces_path.read_text(encoding="utf-8").splitlines()
297
+ recent = lines[-args.limit :]
298
+ print(f"{'VERDICT':<14} {'SERVER.TOOL':<32} {'LATENCY':>9} {'TRACEPARENT':<24} {'DETAILS'}")
299
+ print("-" * 105)
300
+ for raw in recent:
301
+ if not raw.strip():
302
+ continue
303
+ rec = json.loads(raw)
304
+ verdict = str(rec.get("verdict", "")).upper()
305
+ st = f"{rec.get('server_name', '')}.{rec.get('tool_name', '')}"[:31]
306
+ lat = f"{rec.get('latency_ms', 0.0):.1f}ms"
307
+ tp = str(rec.get("traceparent", ""))[:23]
308
+ viols = rec.get("violations") or []
309
+ detail = viols[0]["rule_id"] if viols else "ok"
310
+ print(f"{verdict:<14} {st:<32} {lat:>9} {tp:<24} {detail}")
311
+
312
+ if args.follow:
313
+ with traces_path.open("r", encoding="utf-8") as fh:
314
+ fh.seek(0, os.SEEK_END)
315
+ try:
316
+ while True:
317
+ line = fh.readline()
318
+ if not line:
319
+ time.sleep(0.25)
320
+ continue
321
+ rec = json.loads(line)
322
+ print(
323
+ f"{str(rec.get('verdict', '')).upper():<14} "
324
+ f"{rec.get('server_name', '')}.{rec.get('tool_name', ''):<20} "
325
+ f"{rec.get('latency_ms', 0.0):.1f}ms"
326
+ )
327
+ except KeyboardInterrupt:
328
+ pass
329
+ return 0
330
+
331
+
332
+ def _cmd_compile(args: argparse.Namespace) -> int:
333
+ cfg_path = Path(args.config)
334
+ if not cfg_path.is_file():
335
+ print(f"Error: config file not found at {cfg_path}. Run `piton init` first.", file=sys.stderr)
336
+ return 1
337
+ config = AgentIaCConfig.load_file(cfg_path)
338
+ out_path = Path(args.out)
339
+ out_path.parent.mkdir(parents=True, exist_ok=True)
340
+ out_path.write_text(
341
+ json.dumps(config.model_dump(mode="json"), indent=2, sort_keys=True) + "\n",
342
+ encoding="utf-8",
343
+ )
344
+ print(f"Compiled {args.config} -> {out_path} (policy_sha256={config.canonical_sha256()[:16]}...)")
345
+ return 0
346
+
347
+
348
+ def _detect_sidecar_asset_name() -> Optional[str]:
349
+ import platform
350
+
351
+ sys_os = platform.system().lower()
352
+ if sys_os not in ("linux", "darwin"):
353
+ return None
354
+ mach = platform.machine().lower()
355
+ arch_map = {
356
+ "x86_64": "amd64",
357
+ "amd64": "amd64",
358
+ "arm64": "arm64",
359
+ "aarch64": "arm64",
360
+ }
361
+ goarch = arch_map.get(mach)
362
+ if not goarch:
363
+ return None
364
+ return f"piton-sidecar-{sys_os}-{goarch}"
365
+
366
+
367
+ def _download_verified_sidecar_binary(
368
+ version: Optional[str] = None,
369
+ cache_dir: Optional[Path] = None,
370
+ base_url: Optional[str] = None,
371
+ ) -> Optional[Path]:
372
+ """
373
+ Downloads the matching static `piton-sidecar` binary from GitHub Releases (or
374
+ `PITON_SIDECAR_RELEASE_URL` enterprise mirror), verifies its SHA-256 digest
375
+ against `checksums.txt` (failing closed on mismatch), and caches it locally.
376
+ """
377
+ import hashlib
378
+ from piton import __version__
379
+
380
+ ver = version or __version__
381
+ asset = _detect_sidecar_asset_name()
382
+ if not asset:
383
+ return None
384
+
385
+ target_dir = cache_dir or (Path.home() / ".piton" / "bin")
386
+ cached = target_dir / f"{asset}-v{ver}"
387
+ if cached.is_file() and os.access(cached, os.X_OK):
388
+ return cached
389
+
390
+ release_base = (
391
+ base_url
392
+ or os.getenv("PITON_SIDECAR_RELEASE_URL")
393
+ or f"https://github.com/Tony-Stark2025/piton/releases/download/v{ver}"
394
+ ).rstrip("/")
395
+
396
+ checksums_url = f"{release_base}/checksums.txt"
397
+ binary_url = f"{release_base}/{asset}"
398
+
399
+ try:
400
+ with urllib.request.urlopen(checksums_url, timeout=15) as resp:
401
+ checksums_raw = resp.read(256 * 1024).decode("utf-8", errors="replace")
402
+ except Exception:
403
+ return None
404
+
405
+ expected_sha: Optional[str] = None
406
+ for line in checksums_raw.splitlines():
407
+ parts = line.strip().split()
408
+ if len(parts) >= 2 and Path(parts[1]).name == asset:
409
+ expected_sha = parts[0].lower()
410
+ break
411
+ if not expected_sha or len(expected_sha) != 64:
412
+ return None
413
+
414
+ try:
415
+ with urllib.request.urlopen(binary_url, timeout=60) as resp:
416
+ data = resp.read(64 * 1024 * 1024)
417
+ except Exception:
418
+ return None
419
+
420
+ actual_sha = hashlib.sha256(data).hexdigest().lower()
421
+ if actual_sha != expected_sha:
422
+ print(
423
+ f"Error: SHA-256 verification failed for {asset} (expected {expected_sha[:16]}..., got {actual_sha[:16]}...). Refusing to execute.",
424
+ file=sys.stderr,
425
+ )
426
+ return None
427
+
428
+ target_dir.mkdir(parents=True, exist_ok=True)
429
+ tmp_path = cached.with_suffix(".tmp")
430
+ tmp_path.write_bytes(data)
431
+ tmp_path.chmod(0o755)
432
+ tmp_path.replace(cached)
433
+ return cached
434
+
435
+
436
+ def _resolve_sidecar_binary(explicit_bin: Optional[str]) -> Optional[Path]:
437
+ if explicit_bin:
438
+ p = Path(explicit_bin)
439
+ return p if p.is_file() else None
440
+ env_bin = os.getenv("PITON_SIDECAR_BIN")
441
+ if env_bin:
442
+ p = Path(env_bin)
443
+ return p if p.is_file() else None
444
+ found = shutil.which("piton-sidecar")
445
+ if found:
446
+ return Path(found)
447
+ repo_sidecar = Path(__file__).resolve().parent.parent / "sidecar"
448
+ local_bin = repo_sidecar / "bin" / "piton-sidecar"
449
+ if local_bin.is_file():
450
+ return local_bin
451
+ if shutil.which("go") and (repo_sidecar / "cmd" / "piton-sidecar" / "main.go").is_file():
452
+ local_bin.parent.mkdir(parents=True, exist_ok=True)
453
+ res = subprocess.run(
454
+ ["go", "build", "-o", str(local_bin), "./cmd/piton-sidecar"],
455
+ cwd=str(repo_sidecar),
456
+ capture_output=True,
457
+ text=True,
458
+ )
459
+ if res.returncode == 0 and local_bin.is_file():
460
+ return local_bin
461
+ return _download_verified_sidecar_binary()
462
+
463
+
464
+ def _load_dotenv(path: Path) -> Dict[str, str]:
465
+ out: Dict[str, str] = {}
466
+ if not path.is_file():
467
+ return out
468
+ for line in path.read_text(encoding="utf-8").splitlines():
469
+ line = line.strip()
470
+ if not line or line.startswith("#") or "=" not in line:
471
+ continue
472
+ k, v = line.split("=", 1)
473
+ out[k.strip()] = v.strip()
474
+ return out
475
+
476
+
477
+ def _cmd_run(args: argparse.Namespace) -> int:
478
+ cmd = list(args.cmd or [])
479
+ if cmd and cmd[0] == "--":
480
+ cmd = cmd[1:]
481
+ if not cmd:
482
+ print("Error: provide an agent command after `--`, e.g. `piton run -- python agent.py`", file=sys.stderr)
483
+ return 2
484
+
485
+ config_path = Path(args.config)
486
+ if not config_path.is_file():
487
+ print(f"Error: config file not found at {config_path}. Run `piton init` first.", file=sys.stderr)
488
+ return 1
489
+ config = AgentIaCConfig.load_file(config_path)
490
+ compiled_path = Path(args.compiled_policy)
491
+ compiled_path.parent.mkdir(parents=True, exist_ok=True)
492
+ compiled_path.write_text(
493
+ json.dumps(config.model_dump(mode="json"), indent=2, sort_keys=True) + "\n",
494
+ encoding="utf-8",
495
+ )
496
+
497
+ sidecar_bin = _resolve_sidecar_binary(args.sidecar_bin)
498
+ if sidecar_bin is None:
499
+ print("Error: piton-sidecar binary not found and `go` toolchain unavailable.", file=sys.stderr)
500
+ return 1
501
+
502
+ # Host process (sidecar) inherits real secrets; child agent process receives ONLY ghost handles!
503
+ sidecar_cmd = [
504
+ str(sidecar_bin),
505
+ "--policy", str(compiled_path),
506
+ "--lock", str(args.lockfile),
507
+ "--traces", str(args.traces),
508
+ "--ghost-env", str(args.ghost_env),
509
+ "--addr", str(args.addr),
510
+ ]
511
+ if getattr(args, "collector_url", None):
512
+ sidecar_cmd.extend(["--collector-url", str(args.collector_url)])
513
+ sidecar_proc = subprocess.Popen(sidecar_cmd, env=os.environ.copy())
514
+
515
+ try:
516
+ # Wait up to 5s for /healthz
517
+ health_url = f"http://{args.addr}/healthz"
518
+ ready = False
519
+ for _ in range(50):
520
+ try:
521
+ with urllib.request.urlopen(health_url, timeout=0.2) as resp:
522
+ if resp.status == 200:
523
+ ready = True
524
+ break
525
+ except Exception:
526
+ time.sleep(0.1)
527
+ if not ready:
528
+ print(f"Error: piton-sidecar failed to become healthy at {health_url}", file=sys.stderr)
529
+ return 1
530
+
531
+ # Build scrubbed child environment: strip every real secret referenced in local_dev_credentials
532
+ child_env = os.environ.copy()
533
+ for slot in config.local_dev_credentials.values():
534
+ if slot.source.startswith("env://"):
535
+ real_var = slot.source[len("env://") :]
536
+ child_env.pop(real_var, None)
537
+
538
+ # Inject safe format-preserving ghost handles + gateway base URLs from .env.agent
539
+ ghost_vars = _load_dotenv(Path(args.ghost_env))
540
+ for k, v in ghost_vars.items():
541
+ if k.endswith("_BASE_URL") and "127.0.0.1" not in v and "localhost:8080" in v:
542
+ v = v.replace("localhost:8080", args.addr)
543
+ child_env[k] = v
544
+ child_env["PITON_GATEWAY_URL"] = f"http://{args.addr}"
545
+
546
+ res = subprocess.run(cmd, env=child_env)
547
+ return int(res.returncode)
548
+ finally:
549
+ sidecar_proc.terminate()
550
+ try:
551
+ sidecar_proc.wait(timeout=3)
552
+ except subprocess.TimeoutExpired:
553
+ sidecar_proc.kill()
554
+
555
+
556
+ def _cmd_wrap(args: argparse.Namespace) -> int:
557
+ cmd = list(args.cmd or [])
558
+ if cmd and cmd[0] == "--":
559
+ cmd = cmd[1:]
560
+ if not cmd:
561
+ print("Error: provide a STDIO MCP command after `--`, e.g. `piton wrap --enforce --server fs -- npx @modelcontextprotocol/server-filesystem`", file=sys.stderr)
562
+ return 2
563
+
564
+ cfg_path = Path(args.config)
565
+ if not cfg_path.is_file():
566
+ print(f"Error: config file not found at {cfg_path}. Run `piton init` first.", file=sys.stderr)
567
+ return 1
568
+ config = AgentIaCConfig.load_file(cfg_path)
569
+ lockfile = ManifestLockfile.load_file(Path(args.lockfile)) if Path(args.lockfile).is_file() else None
570
+ signing_key = os.getenv("PITON_LEDGER_SIGNING_KEY", "piton-ledger-signing-key").encode("utf-8")
571
+ ledger = SignedDecisionLedger(Path(args.traces), signing_key=signing_key) if args.traces else None
572
+ return wrap_stdio_mcp(
573
+ args.server,
574
+ cmd,
575
+ config,
576
+ lockfile,
577
+ ledger=ledger,
578
+ enforce_override=getattr(args, "enforce", False),
579
+ )
580
+
581
+
582
+ def _cmd_control_plane(args: argparse.Namespace) -> int:
583
+ from piton.control_plane.server import create_control_plane_server
584
+
585
+ signing_key = os.getenv("PITON_LEDGER_SIGNING_KEY", "piton-ledger-signing-key").encode("utf-8")
586
+ api_key = os.getenv("PITON_CONTROL_API_KEY", "")
587
+ slack_webhook = args.slack_webhook or os.getenv("PITON_SLACK_WEBHOOK_URL", "")
588
+ slack_secret = os.getenv("PITON_SLACK_SIGNING_SECRET", "")
589
+
590
+ httpd, store = create_control_plane_server(
591
+ host=args.host,
592
+ port=args.port,
593
+ db_path=args.db,
594
+ signing_key=signing_key,
595
+ api_key=api_key,
596
+ slack_webhook_url=slack_webhook,
597
+ slack_signing_secret=slack_secret,
598
+ )
599
+ print(
600
+ f"Piton Control Plane listening on http://{args.host}:{args.port} "
601
+ f"(db={args.db} slack_webhook={bool(slack_webhook)} api_key={bool(api_key)})"
602
+ )
603
+ try:
604
+ httpd.serve_forever()
605
+ except KeyboardInterrupt:
606
+ print("\nShutting down Piton Control Plane...")
607
+ finally:
608
+ httpd.server_close()
609
+ store.close()
610
+ return 0
611
+
612
+
613
+ def build_parser() -> argparse.ArgumentParser:
614
+ from piton import __version__
615
+
616
+ cfg_default = _default_config_name()
617
+ lock_default = _default_lock_name()
618
+
619
+ parser = argparse.ArgumentParser(
620
+ prog="piton",
621
+ description="Piton — Lockfile and static supply-chain scanner for MCP servers, Claude Code hooks, and Cursor rules.",
622
+ )
623
+ parser.add_argument("-V", "--version", action="version", version=f"piton {__version__}")
624
+ sub = parser.add_subparsers(dest="command", required=True)
625
+
626
+ p_scan = sub.add_parser("scan", help="Zero-config scan for Claude Code hook RCE, VS Code folderOpen autorun & poisoned Cursor/skill rules")
627
+ p_scan.add_argument("--repo", default=".", help="Repository path to scan")
628
+ p_scan.add_argument("--json", action="store_true", help="Output JSON findings")
629
+ p_scan.set_defaults(func=_cmd_scan)
630
+
631
+ p_init = sub.add_parser("init", help="Scan repo MCP configs, coding-agent hooks & env templates to generate piton.yaml & piton.lock")
632
+ p_init.add_argument("--repo", default=".", help="Repository path to scan")
633
+ p_init.add_argument("--agent-id", default=None, help="Explicit agent ID")
634
+ p_init.add_argument("--owner", default="platform-team@example.com", help="Owning team email")
635
+ p_init.add_argument("--manifest", default=None, help="Optional JSON file mapping server_name -> tools/list array")
636
+ p_init.add_argument("--probe", action="store_true", help="Live-probe discovered HTTP/STDIO MCP servers for tools/list")
637
+ p_init.add_argument("--probe-timeout", type=float, default=8.0, help="Per-server live probe timeout in seconds")
638
+ p_init.add_argument("--allow-poisoned", action="store_true", help="Include tools even if poisoning lint flags them")
639
+ p_init.set_defaults(func=_cmd_init)
640
+
641
+ p_compile = sub.add_parser("compile", help="Compile piton.yaml into .piton/runtime_policy.json for Go sidecar")
642
+ p_compile.add_argument("--config", default=cfg_default)
643
+ p_compile.add_argument("--out", default=".piton/runtime_policy.json")
644
+ p_compile.set_defaults(func=_cmd_compile)
645
+
646
+ p_run = sub.add_parser("run", help="Boot zero-secret Go sidecar, scrub real env secrets, inject .env.agent, and run agent")
647
+ p_run.add_argument("--config", default=cfg_default)
648
+ p_run.add_argument("--lockfile", default=lock_default)
649
+ p_run.add_argument("--ghost-env", default=".env.agent")
650
+ p_run.add_argument("--traces", default=".piton/traces.jsonl")
651
+ p_run.add_argument("--compiled-policy", default=".piton/runtime_policy.json")
652
+ p_run.add_argument("--addr", default="127.0.0.1:8080")
653
+ p_run.add_argument("--collector-url", default=os.getenv("PITON_COLLECTOR_URL", ""), help="Optional Control Plane URL for fleet ledger & MRTR approvals")
654
+ p_run.add_argument("--sidecar-bin", default=None)
655
+ p_run.add_argument("cmd", nargs=argparse.REMAINDER, help="Command to run (prefix with --)")
656
+ p_run.set_defaults(func=_cmd_run)
657
+
658
+ p_wrap = sub.add_parser("wrap", help="Transparent STDIO MCP wrapper enforcing piton.lock & bounds for Cursor/Claude Code")
659
+ p_wrap.add_argument("--server", required=True, help="MCP server name in piton.yaml / piton.lock")
660
+ p_wrap.add_argument("--config", default=cfg_default)
661
+ p_wrap.add_argument("--lockfile", default=lock_default)
662
+ p_wrap.add_argument("--traces", default=".piton/traces.jsonl")
663
+ p_wrap.add_argument("--enforce", action="store_true", help="Hard-block rug pulls & bound violations even if piton.yaml is in shadow mode")
664
+ p_wrap.add_argument("cmd", nargs=argparse.REMAINDER, help="STDIO MCP server command (prefix with --)")
665
+ p_wrap.set_defaults(func=_cmd_wrap)
666
+
667
+ p_cp = sub.add_parser("control-plane", help="Run central Fleet Ledger Collector, MRTR Slack/Webhook Approval Bridge & Governance UI")
668
+ p_cp.add_argument("--host", default="127.0.0.1")
669
+ p_cp.add_argument("--port", type=int, default=8090)
670
+ p_cp.add_argument("--db", default=".piton/control_plane.db")
671
+ p_cp.add_argument("--slack-webhook", default="", help="Optional Slack Incoming Webhook URL for MRTR Block Kit prompts")
672
+ p_cp.set_defaults(func=_cmd_control_plane)
673
+
674
+ p_lock = sub.add_parser("lock", help="Verify, diff, or update split-hash MCP pins & agent hook/skill supply-chain checks")
675
+ p_lock.add_argument("--repo", default=".", help="Repository path to also lint for coding-agent hook/skill poisoning")
676
+ p_lock.add_argument("--no-agent-scan", action="store_true", help="Skip static repo hook/rule scan (e.g. when piton scan already ran)")
677
+ p_lock.add_argument("--manifest", default=None, help="JSON file mapping server_name -> observed tools/list array")
678
+ p_lock.add_argument("--probe", action="store_true", help="Live-probe MCP servers from config instead of static JSON")
679
+ p_lock.add_argument("--probe-timeout", type=float, default=8.0, help="Per-server live probe timeout in seconds")
680
+ p_lock.add_argument("--lockfile", default=lock_default)
681
+ p_lock.add_argument("--config", default=cfg_default)
682
+ p_lock.add_argument("--diff", action="store_true", help="Render PR-ready markdown diff against existing lockfile")
683
+ p_lock.add_argument("--update", action="store_true", help="Update lockfile with observed manifests")
684
+ p_lock.add_argument("--allow-poisoned", action="store_true")
685
+ p_lock.set_defaults(func=_cmd_lock)
686
+
687
+ p_replay = sub.add_parser("replay", help="Replay recorded shadow traces (or OTel logs) against candidate policy")
688
+ p_replay.add_argument("--config", default=cfg_default)
689
+ p_replay.add_argument("--traces", default=".piton/traces.jsonl")
690
+ p_replay.add_argument("--simulate-enforce", action="store_true", default=True)
691
+ p_replay.add_argument("--strict", action="store_true", help="Exit non-zero if any calls would be blocked")
692
+ p_replay.add_argument("--export", choices=["cel", "cedar"], default=None, help="Export calibrated CEL (agentgateway) or Cedar (ToolHive/AgentCore) policies")
693
+ p_replay.add_argument("--json", action="store_true", help="Output JSON report")
694
+ p_replay.set_defaults(func=_cmd_replay)
695
+
696
+ p_verify = sub.add_parser("ledger-verify", help="Verify HMAC chain integrity of a signed decision ledger")
697
+ p_verify.add_argument("--traces", default=".piton/traces.jsonl")
698
+ p_verify.set_defaults(func=_cmd_ledger_verify)
699
+
700
+ p_top = sub.add_parser("top", help="Flight recorder view of recent/live agent tool decisions")
701
+ p_top.add_argument("--traces", default=".piton/traces.jsonl")
702
+ p_top.add_argument("--limit", type=int, default=25)
703
+ p_top.add_argument("--follow", "-f", action="store_true")
704
+ p_top.set_defaults(func=_cmd_top)
705
+
706
+ return parser
707
+
708
+
709
+ def main(argv: Optional[List[str]] = None) -> int:
710
+ parser = build_parser()
711
+ args = parser.parse_args(argv)
712
+ return int(args.func(args))
713
+
714
+
715
+ if __name__ == "__main__":
716
+ sys.exit(main())