authority-runtime 0.3.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.
@@ -0,0 +1,1405 @@
1
+ """
2
+ Carryall CLI - Authority Runtime command-line interface.
3
+
4
+ Commands:
5
+ carryall init Initialize carryall in a directory
6
+ carryall keys generate Generate new Ed25519 keypair
7
+ carryall keys list List stored agent keys
8
+ carryall keys show Show agent's public key
9
+ carryall keys delete Delete agent's key
10
+ carryall credentials issue Issue a new envelope/credential
11
+ carryall credentials list List stored credentials
12
+ carryall credentials show Show credential details
13
+ carryall credentials revoke Revoke a credential
14
+ carryall shell Interactive policy-enforced shell
15
+ carryall test Dry-run policy evaluation
16
+ carryall backends list List registered backends
17
+ carryall backends inspect Inspect a backend
18
+ carryall audit Query audit log
19
+ carryall audit --verify Verify audit log integrity
20
+ carryall mcp serve Start MCP server for Clawdbot integration
21
+ """
22
+
23
+ import json
24
+ import os
25
+ import sys
26
+ from datetime import datetime, timezone
27
+ from pathlib import Path
28
+ from typing import Optional
29
+
30
+ import typer
31
+ from rich.console import Console
32
+ from rich.table import Table
33
+
34
+ from .keys import AgentKeyStore
35
+ from .envelope import create_simple_envelope, generate_key_pair, verify_signature
36
+ from .storage import EnvelopeStore
37
+ from .compliance import ComplianceReport
38
+ from .policy import PolicyEngine, PolicyValidationError
39
+ from .types import AuthorityEnvelope
40
+ from .backends.slos import SlosBackend, Decision, parse_slos_uri
41
+
42
+ # Initialize Typer app
43
+ app = typer.Typer(
44
+ name="carryall",
45
+ help="Authority Runtime CLI - Cryptographic permissions for AI agents",
46
+ add_completion=False,
47
+ )
48
+
49
+ console = Console()
50
+
51
+ # Sub-apps
52
+ keys_app = typer.Typer(help="Manage agent Ed25519 keys")
53
+ credentials_app = typer.Typer(help="Manage authority envelopes/credentials")
54
+ backends_app = typer.Typer(help="Manage backend adapters")
55
+ audit_app = typer.Typer(help="Query and verify audit logs")
56
+ compliance_app = typer.Typer(help="FERPA/compliance reporting and attestation")
57
+ policy_app = typer.Typer(help="YAML policy management")
58
+ mcp_app = typer.Typer(help="MCP server for Clawdbot integration")
59
+ db_app = typer.Typer(help="Database management")
60
+
61
+ app.add_typer(keys_app, name="keys")
62
+ app.add_typer(credentials_app, name="credentials")
63
+ app.add_typer(backends_app, name="backends")
64
+ app.add_typer(audit_app, name="audit")
65
+ app.add_typer(compliance_app, name="compliance")
66
+ app.add_typer(policy_app, name="policy")
67
+ app.add_typer(mcp_app, name="mcp")
68
+ app.add_typer(db_app, name="db")
69
+
70
+
71
+ def get_keys_dir() -> str:
72
+ """Get keys directory from environment or default."""
73
+ return os.environ.get("CARRYALL_KEYS_DIR", "~/.carryall/keys")
74
+
75
+
76
+ def get_db_path() -> str:
77
+ """Get database path from environment or default."""
78
+ return os.environ.get("CARRYALL_DB", "~/.carryall/authority.db")
79
+
80
+
81
+ def get_credentials_dir() -> str:
82
+ """Get credentials directory from environment or default."""
83
+ return os.environ.get("CARRYALL_CREDENTIALS_DIR", "~/.carryall/credentials")
84
+
85
+
86
+ # =============================================================================
87
+ # Root commands
88
+ # =============================================================================
89
+
90
+
91
+ @app.command()
92
+ def init(
93
+ path: str = typer.Argument(".", help="Directory to initialize"),
94
+ ):
95
+ """Initialize carryall configuration in a directory."""
96
+ init_path = Path(path).expanduser().resolve()
97
+
98
+ # Create .carryall directory
99
+ carryall_dir = init_path / ".carryall"
100
+ carryall_dir.mkdir(parents=True, exist_ok=True)
101
+
102
+ # Create subdirectories
103
+ (carryall_dir / "keys").mkdir(exist_ok=True)
104
+ (carryall_dir / "credentials").mkdir(exist_ok=True)
105
+
106
+ # Create config file
107
+ config_path = carryall_dir / "config.json"
108
+ if not config_path.exists():
109
+ config = {
110
+ "version": "1.0.0",
111
+ "keys_dir": str(carryall_dir / "keys"),
112
+ "credentials_dir": str(carryall_dir / "credentials"),
113
+ "db_path": str(carryall_dir / "authority.db"),
114
+ "backends": {
115
+ "slos": {
116
+ "enabled": False,
117
+ "config_path": None,
118
+ }
119
+ },
120
+ }
121
+ with open(config_path, "w") as f:
122
+ json.dump(config, f, indent=2)
123
+
124
+ console.print(f"[green]✓[/green] Initialized carryall in {carryall_dir}")
125
+ console.print(f" Keys: {carryall_dir / 'keys'}")
126
+ console.print(f" Credentials: {carryall_dir / 'credentials'}")
127
+ console.print(f" Database: {carryall_dir / 'authority.db'}")
128
+ console.print(f" Config: {config_path}")
129
+
130
+
131
+ @app.command()
132
+ def shell(
133
+ agent: str = typer.Option(..., "--agent", "-a", help="Agent ID to use"),
134
+ mock: bool = typer.Option(True, "--mock/--no-mock", help="Use mock SLOS backend"),
135
+ ):
136
+ """Start interactive shell with policy-enforced access.
137
+
138
+ Example:
139
+ carryall shell --agent finance-agent
140
+
141
+ Commands inside the shell:
142
+ vaults List available vaults
143
+ read <uri> Read a document (policy-enforced)
144
+ check <action> <uri> Check access without acting
145
+ switch <agent-id> Switch agents
146
+ audit --since 1h Show recent audit trail
147
+ help Show all commands
148
+ """
149
+ from .shell import CarryallShell
150
+
151
+ shell_instance = CarryallShell(
152
+ agent_id=agent,
153
+ keys_dir=get_keys_dir(),
154
+ db_path=get_db_path(),
155
+ credentials_dir=get_credentials_dir(),
156
+ mock=mock,
157
+ )
158
+ shell_instance.run()
159
+
160
+
161
+ @app.command()
162
+ def test(
163
+ credential: str = typer.Option(..., "--credential", "-c", help="Path to credential/envelope JSON"),
164
+ action: str = typer.Option(..., "--action", "-a", help="Action to test (read, write, delete)"),
165
+ resource: str = typer.Option(..., "--resource", "-r", help="Resource URI (e.g., slos://vaults/finance/doc-id)"),
166
+ mock: bool = typer.Option(False, "--mock", help="Use mock backend (no real SLOS)"),
167
+ ):
168
+ """Dry-run policy evaluation for a credential and resource."""
169
+ # Load credential
170
+ cred_path = Path(credential).expanduser()
171
+ if not cred_path.exists():
172
+ console.print(f"[red]Error:[/red] Credential file not found: {credential}")
173
+ raise typer.Exit(1)
174
+
175
+ with open(cred_path) as f:
176
+ envelope_data = json.load(f)
177
+
178
+ envelope = AuthorityEnvelope(**envelope_data)
179
+
180
+ # Determine backend from URI
181
+ if resource.startswith("slos://"):
182
+ key_store = AgentKeyStore(get_keys_dir())
183
+ backend = SlosBackend(key_store=key_store)
184
+
185
+ result = backend.check_access(envelope, action, resource, mock=mock)
186
+
187
+ # Display result
188
+ if result.decision == Decision.ALLOW:
189
+ console.print(f"[green]✓ ALLOW[/green]: {result.reason}")
190
+ elif result.decision == Decision.REQUIRE_APPROVAL:
191
+ console.print(f"[yellow]⚠ REQUIRE_APPROVAL[/yellow]: {result.reason}")
192
+ else:
193
+ console.print(f"[red]✗ DENY[/red]: {result.reason}")
194
+
195
+ # Show metadata
196
+ console.print("\nMetadata:")
197
+ for key, value in result.metadata.items():
198
+ console.print(f" {key}: {value}")
199
+
200
+ else:
201
+ console.print(f"[red]Error:[/red] Unknown resource URI scheme: {resource}")
202
+ console.print("Supported: slos://")
203
+ raise typer.Exit(1)
204
+
205
+
206
+ # =============================================================================
207
+ # Keys commands
208
+ # =============================================================================
209
+
210
+
211
+ @keys_app.command("generate")
212
+ def keys_generate(
213
+ agent_id: str = typer.Argument(..., help="Agent identifier (e.g., finance-agent)"),
214
+ overwrite: bool = typer.Option(False, "--overwrite", "-f", help="Overwrite existing key"),
215
+ ):
216
+ """Generate new Ed25519 keypair for an agent."""
217
+ store = AgentKeyStore(get_keys_dir())
218
+
219
+ if store.has_key(agent_id) and not overwrite:
220
+ console.print(f"[red]Error:[/red] Key already exists for {agent_id}")
221
+ console.print("Use --overwrite to replace existing key")
222
+ raise typer.Exit(1)
223
+
224
+ public_key, secret_path = store.generate_keypair(agent_id, overwrite=overwrite)
225
+
226
+ console.print(f"[green]✓[/green] Generated keypair for {agent_id}")
227
+ console.print()
228
+ console.print("Public key (add to SLOS config/agents.yaml):")
229
+ console.print(f" {agent_id}: {public_key}")
230
+ console.print()
231
+ console.print(f"Secret key saved to: {secret_path}")
232
+
233
+
234
+ @keys_app.command("list")
235
+ def keys_list():
236
+ """List all agents with stored keys."""
237
+ store = AgentKeyStore(get_keys_dir())
238
+ agents = store.list_agents()
239
+
240
+ if not agents:
241
+ console.print("No agent keys found.")
242
+ console.print(f"Generate one with: carryall keys generate <agent-id>")
243
+ return
244
+
245
+ table = Table(title="Agent Keys")
246
+ table.add_column("Agent ID", style="cyan")
247
+ table.add_column("Public Key (first 32 chars)")
248
+
249
+ for agent_id in agents:
250
+ try:
251
+ public_key = store.get_public_key_base64(agent_id)
252
+ table.add_row(agent_id, public_key[:32] + "...")
253
+ except Exception as e:
254
+ table.add_row(agent_id, f"[red]Error: {e}[/red]")
255
+
256
+ console.print(table)
257
+
258
+
259
+ @keys_app.command("show")
260
+ def keys_show(
261
+ agent_id: str = typer.Argument(..., help="Agent identifier"),
262
+ ):
263
+ """Show agent's public key."""
264
+ store = AgentKeyStore(get_keys_dir())
265
+
266
+ if not store.has_key(agent_id):
267
+ console.print(f"[red]Error:[/red] No key found for {agent_id}")
268
+ raise typer.Exit(1)
269
+
270
+ public_key = store.get_public_key_base64(agent_id)
271
+ console.print(f"Agent: {agent_id}")
272
+ console.print(f"Public key (base64 for SLOS config): {public_key}")
273
+
274
+
275
+ @keys_app.command("delete")
276
+ def keys_delete(
277
+ agent_id: str = typer.Argument(..., help="Agent identifier"),
278
+ force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation"),
279
+ ):
280
+ """Delete agent's key."""
281
+ store = AgentKeyStore(get_keys_dir())
282
+
283
+ if not store.has_key(agent_id):
284
+ console.print(f"[red]Error:[/red] No key found for {agent_id}")
285
+ raise typer.Exit(1)
286
+
287
+ if not force:
288
+ confirm = typer.confirm(f"Delete key for {agent_id}? This cannot be undone.")
289
+ if not confirm:
290
+ raise typer.Exit(0)
291
+
292
+ store.delete_key(agent_id)
293
+ console.print(f"[green]✓[/green] Deleted key for {agent_id}")
294
+
295
+
296
+ @keys_app.command("sync")
297
+ def keys_sync(
298
+ slos_config: str = typer.Option(None, "--slos-config", help="Path to SLOS agents.yaml"),
299
+ ):
300
+ """Check which SLOS agents have keys in carryall."""
301
+ store = AgentKeyStore(get_keys_dir())
302
+
303
+ # Known SLOS agents (hardcoded for now, could read from config)
304
+ slos_agents = [
305
+ "executive-agent",
306
+ "finance-agent",
307
+ "startup-agent",
308
+ "health-agent",
309
+ "personal-agent",
310
+ ]
311
+
312
+ console.print("Agent key status:")
313
+ for agent in slos_agents:
314
+ if store.has_key(agent):
315
+ console.print(f" [green]✓[/green] {agent}")
316
+ else:
317
+ console.print(f" [red]✗[/red] {agent} (missing)")
318
+
319
+ missing = [a for a in slos_agents if not store.has_key(a)]
320
+ if missing:
321
+ console.print()
322
+ console.print("To generate missing keys:")
323
+ for agent in missing:
324
+ console.print(f" carryall keys generate {agent}")
325
+
326
+
327
+ # =============================================================================
328
+ # Credentials commands
329
+ # =============================================================================
330
+
331
+
332
+ @credentials_app.command("issue")
333
+ def credentials_issue(
334
+ agent_id: str = typer.Argument(..., help="Agent identifier"),
335
+ scopes: str = typer.Option(..., "--scopes", "-s", help="Comma-separated scopes"),
336
+ ttl: str = typer.Option("24h", "--ttl", "-t", help="Time to live (e.g., 1h, 24h, 7d)"),
337
+ output: str = typer.Option(None, "--output", "-o", help="Output file path"),
338
+ ):
339
+ """Issue a new envelope/credential for an agent."""
340
+ # Parse TTL
341
+ ttl_seconds = parse_ttl(ttl)
342
+
343
+ # Parse scopes
344
+ scope_list = [s.strip() for s in scopes.split(",")]
345
+
346
+ # Load or generate signing key
347
+ key_store = AgentKeyStore(get_keys_dir())
348
+
349
+ if not key_store.has_key(agent_id):
350
+ console.print(f"[yellow]Warning:[/yellow] No key found for {agent_id}, generating new one...")
351
+ public_key_b64, _ = key_store.generate_keypair(agent_id)
352
+ console.print(f"Generated keypair. Public key: {public_key_b64}")
353
+
354
+ # Get private key for signing
355
+ signing_key = key_store.load_signing_key(agent_id)
356
+ private_key_hex = signing_key.encode().hex()
357
+
358
+ # Create envelope
359
+ envelope = create_simple_envelope(
360
+ agent_id=agent_id,
361
+ scopes=scope_list,
362
+ private_key=private_key_hex,
363
+ ttl_seconds=ttl_seconds,
364
+ )
365
+
366
+ # Output
367
+ envelope_json = envelope.model_dump_json(indent=2)
368
+
369
+ if output:
370
+ output_path = Path(output).expanduser()
371
+ output_path.parent.mkdir(parents=True, exist_ok=True)
372
+ with open(output_path, "w") as f:
373
+ f.write(envelope_json)
374
+ console.print(f"[green]✓[/green] Credential saved to: {output_path}")
375
+ else:
376
+ console.print(envelope_json)
377
+
378
+ # Also save to credentials directory
379
+ creds_dir = Path(get_credentials_dir()).expanduser()
380
+ creds_dir.mkdir(parents=True, exist_ok=True)
381
+ cred_file = creds_dir / f"{envelope.envelope_id}.json"
382
+ with open(cred_file, "w") as f:
383
+ f.write(envelope_json)
384
+
385
+ console.print()
386
+ console.print(f"Envelope ID: {envelope.envelope_id}")
387
+ console.print(f"Agent: {agent_id}")
388
+ console.print(f"Scopes: {scope_list}")
389
+ console.print(f"Expires: {envelope.expires_at}")
390
+
391
+
392
+ @credentials_app.command("list")
393
+ def credentials_list():
394
+ """List stored credentials."""
395
+ creds_dir = Path(get_credentials_dir()).expanduser()
396
+
397
+ if not creds_dir.exists():
398
+ console.print("No credentials directory found.")
399
+ return
400
+
401
+ cred_files = list(creds_dir.glob("*.json"))
402
+
403
+ if not cred_files:
404
+ console.print("No credentials found.")
405
+ return
406
+
407
+ table = Table(title="Stored Credentials")
408
+ table.add_column("Envelope ID", style="cyan")
409
+ table.add_column("Agent")
410
+ table.add_column("Scopes")
411
+ table.add_column("Expires")
412
+ table.add_column("Status")
413
+
414
+ now = datetime.now(timezone.utc)
415
+
416
+ for cred_file in sorted(cred_files):
417
+ try:
418
+ with open(cred_file) as f:
419
+ data = json.load(f)
420
+
421
+ envelope = AuthorityEnvelope(**data)
422
+ expires_str = envelope.expires_at.replace("Z", "+00:00")
423
+ expires = datetime.fromisoformat(expires_str)
424
+
425
+ status = "[green]active[/green]" if expires > now else "[red]expired[/red]"
426
+ scopes_str = ", ".join(envelope.authority.scopes[:3])
427
+ if len(envelope.authority.scopes) > 3:
428
+ scopes_str += f" (+{len(envelope.authority.scopes) - 3})"
429
+
430
+ table.add_row(
431
+ envelope.envelope_id,
432
+ envelope.agent_id,
433
+ scopes_str,
434
+ envelope.expires_at[:19],
435
+ status,
436
+ )
437
+ except Exception as e:
438
+ table.add_row(cred_file.stem, "[red]Error[/red]", str(e), "", "")
439
+
440
+ console.print(table)
441
+
442
+
443
+ @credentials_app.command("show")
444
+ def credentials_show(
445
+ envelope_id: str = typer.Argument(..., help="Envelope ID or path to credential file"),
446
+ ):
447
+ """Show credential details."""
448
+ # Try as file path first
449
+ cred_path = Path(envelope_id).expanduser()
450
+ if cred_path.exists():
451
+ with open(cred_path) as f:
452
+ data = json.load(f)
453
+ else:
454
+ # Try in credentials directory
455
+ creds_dir = Path(get_credentials_dir()).expanduser()
456
+ cred_file = creds_dir / f"{envelope_id}.json"
457
+ if cred_file.exists():
458
+ with open(cred_file) as f:
459
+ data = json.load(f)
460
+ else:
461
+ console.print(f"[red]Error:[/red] Credential not found: {envelope_id}")
462
+ raise typer.Exit(1)
463
+
464
+ envelope = AuthorityEnvelope(**data)
465
+
466
+ console.print(f"[bold]Envelope ID:[/bold] {envelope.envelope_id}")
467
+ console.print(f"[bold]Agent:[/bold] {envelope.agent_id}")
468
+ console.print(f"[bold]Provider:[/bold] {envelope.provider}")
469
+ console.print(f"[bold]Created:[/bold] {envelope.created_at}")
470
+ console.print(f"[bold]Expires:[/bold] {envelope.expires_at}")
471
+ console.print(f"[bold]TTL:[/bold] {envelope.ttl_seconds} seconds")
472
+ console.print()
473
+ console.print("[bold]Scopes:[/bold]")
474
+ for scope in envelope.authority.scopes:
475
+ console.print(f" - {scope}")
476
+ console.print()
477
+ console.print("[bold]Resources:[/bold]")
478
+ for resource in envelope.authority.resources:
479
+ console.print(f" - {resource}")
480
+ console.print()
481
+ console.print(f"[bold]Signature:[/bold] {envelope.signature[:32]}...")
482
+
483
+ # Check expiration
484
+ now = datetime.now(timezone.utc)
485
+ expires_str = envelope.expires_at.replace("Z", "+00:00")
486
+ expires = datetime.fromisoformat(expires_str)
487
+
488
+ if expires <= now:
489
+ console.print()
490
+ console.print("[red]⚠ This credential has expired[/red]")
491
+
492
+
493
+ @credentials_app.command("revoke")
494
+ def credentials_revoke(
495
+ envelope_id: str = typer.Argument(..., help="Envelope ID to revoke"),
496
+ force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation"),
497
+ ):
498
+ """Revoke a credential (delete from local storage)."""
499
+ creds_dir = Path(get_credentials_dir()).expanduser()
500
+ cred_file = creds_dir / f"{envelope_id}.json"
501
+
502
+ if not cred_file.exists():
503
+ console.print(f"[red]Error:[/red] Credential not found: {envelope_id}")
504
+ raise typer.Exit(1)
505
+
506
+ if not force:
507
+ confirm = typer.confirm(f"Revoke credential {envelope_id}? This cannot be undone.")
508
+ if not confirm:
509
+ raise typer.Exit(0)
510
+
511
+ cred_file.unlink()
512
+ console.print(f"[green]✓[/green] Revoked credential: {envelope_id}")
513
+
514
+
515
+ # =============================================================================
516
+ # Backends commands
517
+ # =============================================================================
518
+
519
+
520
+ @backends_app.command("list")
521
+ def backends_list():
522
+ """List registered backends."""
523
+ table = Table(title="Backends")
524
+ table.add_column("Backend", style="cyan")
525
+ table.add_column("Status")
526
+ table.add_column("Description")
527
+
528
+ # SLOS backend
529
+ slos_status = "[yellow]available[/yellow]"
530
+ table.add_row("sovereign-life-os", slos_status, "Sovereign Life OS vault backend")
531
+
532
+ console.print(table)
533
+
534
+
535
+ @backends_app.command("inspect")
536
+ def backends_inspect(
537
+ backend: str = typer.Argument(..., help="Backend name"),
538
+ mock: bool = typer.Option(False, "--mock", help="Use mock data"),
539
+ ):
540
+ """Inspect a backend's available resources."""
541
+ if backend in ["sovereign-life-os", "slos"]:
542
+ key_store = AgentKeyStore(get_keys_dir())
543
+ slos = SlosBackend(key_store=key_store)
544
+
545
+ try:
546
+ vaults = slos.list_vaults("executive-agent", mock=mock)
547
+ console.print(f"[bold]Backend:[/bold] Sovereign Life OS")
548
+ console.print(f"[bold]Vaults:[/bold]")
549
+ for vault in vaults:
550
+ console.print(f" - {vault}")
551
+ except FileNotFoundError as e:
552
+ console.print(f"[red]Error:[/red] {e}")
553
+ console.print("Generate keys first: carryall keys generate executive-agent")
554
+ except Exception as e:
555
+ console.print(f"[red]Error:[/red] {e}")
556
+ else:
557
+ console.print(f"[red]Error:[/red] Unknown backend: {backend}")
558
+ console.print("Available: sovereign-life-os")
559
+ raise typer.Exit(1)
560
+
561
+
562
+ # =============================================================================
563
+ # Audit commands
564
+ # =============================================================================
565
+
566
+
567
+ @audit_app.callback(invoke_without_command=True)
568
+ def audit_query(
569
+ ctx: typer.Context,
570
+ agent_id: Optional[str] = typer.Option(None, "--agent", "-a", help="Filter by agent ID"),
571
+ limit: int = typer.Option(100, "--limit", "-n", help="Maximum entries to show"),
572
+ verify: bool = typer.Option(False, "--verify", help="Verify audit log integrity"),
573
+ ):
574
+ """Query audit log."""
575
+ if ctx.invoked_subcommand is not None:
576
+ return
577
+
578
+ db_path = Path(get_db_path()).expanduser()
579
+
580
+ if not db_path.exists():
581
+ console.print("No audit log found.")
582
+ return
583
+
584
+ store = EnvelopeStore(str(db_path))
585
+
586
+ if verify:
587
+ # Verify audit trail hash chain integrity
588
+ console.print("Verifying audit trail hash chain...")
589
+
590
+ result = store.verify_audit_chain()
591
+
592
+ console.print(f"Entries verified: {result['entries_checked']}")
593
+
594
+ if result["gaps"]:
595
+ console.print(f"[yellow]WARNING: {len(result['gaps'])} gap(s) detected (possible deletions)[/yellow]")
596
+ for expected, actual in result["gaps"]:
597
+ console.print(f" Gap: expected id {expected}, found id {actual}")
598
+
599
+ if result["valid"]:
600
+ console.print(f"[green]Audit chain VALID. {result['entries_checked']} entries verified.[/green]")
601
+ else:
602
+ console.print(f"[red]Audit chain INVALID at entry #{result['first_invalid_id']}[/red]")
603
+ console.print(f" Error: {result['error']}")
604
+
605
+ # Also check signature stats
606
+ stats = store.get_stats()
607
+ if stats['audit_trail']['signature_failures'] > 0:
608
+ console.print(f"[red]⚠ {stats['audit_trail']['signature_failures']} signature failure(s) detected[/red]")
609
+
610
+ return
611
+
612
+ # Query audit trail
613
+ entries = store.get_audit_trail(agent_id=agent_id, limit=limit)
614
+
615
+ if not entries:
616
+ console.print("No audit entries found.")
617
+ return
618
+
619
+ table = Table(title="Audit Trail")
620
+ table.add_column("Timestamp", style="dim")
621
+ table.add_column("Agent")
622
+ table.add_column("Action")
623
+ table.add_column("Result")
624
+ table.add_column("Envelope ID")
625
+
626
+ for entry in entries:
627
+ result_style = "green" if entry["result"] == "success" else "red"
628
+ table.add_row(
629
+ entry["timestamp"][:19],
630
+ entry["agent_id"],
631
+ entry["action"],
632
+ f"[{result_style}]{entry['result']}[/{result_style}]",
633
+ entry["envelope_id"][:16] + "...",
634
+ )
635
+
636
+ console.print(table)
637
+
638
+
639
+ @audit_app.command("stats")
640
+ def audit_stats(
641
+ output_format: str = typer.Option("table", "--format", "-f", help="Output format: table, json"),
642
+ ):
643
+ """Show audit statistics for compliance reporting.
644
+
645
+ Displays summary metrics about agent activity, policy enforcement,
646
+ and signature verification - useful for compliance dashboards.
647
+ """
648
+ db_path = Path(get_db_path()).expanduser()
649
+
650
+ if not db_path.exists():
651
+ console.print("No audit database found.")
652
+ return
653
+
654
+ store = EnvelopeStore(str(db_path))
655
+ stats = store.get_stats()
656
+
657
+ if output_format == "json":
658
+ import json
659
+ console.print(json.dumps(stats, indent=2))
660
+ return
661
+
662
+ # Table output
663
+ console.print("\n[bold]Audit Statistics[/bold]")
664
+ console.print(f"Database: {db_path}\n")
665
+
666
+ # Envelope stats
667
+ env_table = Table(title="Envelope Statistics")
668
+ env_table.add_column("Metric", style="cyan")
669
+ env_table.add_column("Value", style="green")
670
+ env_table.add_row("Total Envelopes", str(stats["envelopes"]["total"]))
671
+ env_table.add_row("Unique Agents", str(stats["envelopes"]["unique_agents"]))
672
+ env_table.add_row("Unique Policies", str(stats["envelopes"]["unique_policies"]))
673
+ console.print(env_table)
674
+
675
+ # Audit trail stats
676
+ audit_table = Table(title="Audit Trail Statistics")
677
+ audit_table.add_column("Metric", style="cyan")
678
+ audit_table.add_column("Value", style="green")
679
+ audit_table.add_row("Total Actions", str(stats["audit_trail"]["total_actions"]))
680
+ audit_table.add_row("Successful", str(stats["audit_trail"]["successful"]))
681
+ audit_table.add_row("Blocked", str(stats["audit_trail"]["blocked"]))
682
+ audit_table.add_row("Signature Failures", str(stats["audit_trail"]["signature_failures"]))
683
+
684
+ # Calculate success rate
685
+ total = stats["audit_trail"]["total_actions"]
686
+ if total > 0:
687
+ success_rate = (stats["audit_trail"]["successful"] / total) * 100
688
+ audit_table.add_row("Success Rate", f"{success_rate:.1f}%")
689
+
690
+ console.print(audit_table)
691
+
692
+ # Security summary
693
+ if stats["audit_trail"]["signature_failures"] > 0:
694
+ console.print("\n[red]⚠ WARNING: Signature failures detected - possible tampering[/red]")
695
+ else:
696
+ console.print("\n[green]✓ All signatures valid - audit trail integrity maintained[/green]")
697
+
698
+
699
+ @audit_app.command("export")
700
+ def audit_export(
701
+ output: str = typer.Option("audit_export.json", "--output", "-o", help="Output file path"),
702
+ agent_id: Optional[str] = typer.Option(None, "--agent", "-a", help="Filter by agent ID"),
703
+ since: Optional[str] = typer.Option(None, "--since", "-s", help="Time window (e.g., 30d, 90d, 365d)"),
704
+ limit: int = typer.Option(10000, "--limit", "-n", help="Maximum entries to export"),
705
+ fmt: str = typer.Option("json", "--format", "-f", help="Output format: json or csv"),
706
+ ):
707
+ """Export audit trail to JSON or CSV file for compliance archival.
708
+
709
+ Creates a portable export of the audit trail that can be
710
+ submitted to compliance systems or archived.
711
+
712
+ Examples:
713
+ carryall audit export --since 90d --output report.json
714
+ carryall audit export --since 365d --format csv --output annual.csv
715
+ """
716
+ import json as json_mod
717
+ import csv
718
+
719
+ db_path = Path(get_db_path()).expanduser()
720
+
721
+ if not db_path.exists():
722
+ console.print("No audit database found.")
723
+ return
724
+
725
+ store = EnvelopeStore(str(db_path))
726
+
727
+ # Parse --since into start_time
728
+ start_time = None
729
+ if since:
730
+ start_time = _parse_since(since)
731
+
732
+ entries = store.get_audit_trail(agent_id=agent_id, start_time=start_time, limit=limit)
733
+ stats = store.get_stats()
734
+
735
+ output_path = Path(output)
736
+
737
+ if fmt == "csv":
738
+ if entries:
739
+ with open(output_path, "w", newline="") as f:
740
+ writer = csv.DictWriter(f, fieldnames=entries[0].keys())
741
+ writer.writeheader()
742
+ writer.writerows(entries)
743
+ else:
744
+ output_path.write_text("")
745
+ else:
746
+ export_data = {
747
+ "export_timestamp": datetime.now(timezone.utc).isoformat(),
748
+ "database_path": str(db_path),
749
+ "statistics": stats,
750
+ "filter_agent_id": agent_id,
751
+ "filter_since": since,
752
+ "entry_count": len(entries),
753
+ "entries": entries,
754
+ }
755
+ output_path.write_text(json_mod.dumps(export_data, indent=2, default=str))
756
+
757
+ console.print(f"[green]Exported {len(entries)} audit entries to {output_path}[/green]")
758
+ console.print(f" Total size: {output_path.stat().st_size / 1024:.1f} KB")
759
+
760
+
761
+ @audit_app.command("archive")
762
+ def audit_archive(
763
+ older_than: str = typer.Option(..., "--older-than", help="Archive entries older than (e.g., 365d)"),
764
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
765
+ ):
766
+ """Archive old audit entries to a separate table.
767
+
768
+ Moves entries older than the specified threshold to audit_trail_archive.
769
+ Hash chain data is preserved. Gaps in the main table's ID sequence
770
+ will be detected by 'carryall audit --verify' as warnings.
771
+
772
+ Examples:
773
+ carryall audit archive --older-than 365d --yes
774
+ """
775
+ db_path = Path(get_db_path()).expanduser()
776
+
777
+ if not db_path.exists():
778
+ console.print("No audit database found.")
779
+ return
780
+
781
+ # Parse days from the threshold
782
+ if not older_than.endswith("d"):
783
+ console.print("[red]Error: --older-than must be in days (e.g., 365d)[/red]")
784
+ raise typer.Exit(code=1)
785
+
786
+ days = int(older_than[:-1])
787
+
788
+ if not yes:
789
+ console.print(f"This will archive audit entries older than {days} days.")
790
+ confirm = typer.confirm("Proceed?")
791
+ if not confirm:
792
+ console.print("Aborted.")
793
+ return
794
+
795
+ store = EnvelopeStore(str(db_path))
796
+ result = store.archive_audit_entries(older_than_days=days)
797
+ console.print(f"[green]Archived {result['archived_count']} entries (cutoff: {result['cutoff_date'][:10]})[/green]")
798
+
799
+
800
+ def _parse_since(since: str) -> str:
801
+ """Parse a --since value like '30d', '90d', '1y' into an ISO timestamp."""
802
+ from datetime import timedelta
803
+ if since.endswith("d"):
804
+ days = int(since[:-1])
805
+ elif since.endswith("y"):
806
+ days = int(since[:-1]) * 365
807
+ else:
808
+ days = int(since)
809
+ cutoff = datetime.now(timezone.utc) - timedelta(days=days)
810
+ return cutoff.isoformat()
811
+
812
+
813
+ # =============================================================================
814
+ # Compliance commands
815
+ # =============================================================================
816
+
817
+
818
+ @compliance_app.command("attest")
819
+ def compliance_attest(
820
+ agent_id: str = typer.Option(..., "--agent", "-a", help="Agent ID to attest"),
821
+ resource: str = typer.Option(..., "--resource", "-r", help="Resource pattern (SQL LIKE, use % wildcard)"),
822
+ since: str = typer.Option("90d", "--since", "-s", help="Time window (e.g., 30d, 90d, 1y)"),
823
+ output_format: str = typer.Option("table", "--format", "-f", help="Output format: table, json"),
824
+ ):
825
+ """Prove an agent NEVER accessed a resource (negative attestation).
826
+
827
+ The FERPA killer feature: cryptographic proof that an agent did not
828
+ access specific records during a time period.
829
+
830
+ Examples:
831
+
832
+ carryall compliance attest --agent financial-aid-agent --resource "slos://vaults/student-health/%"
833
+
834
+ carryall compliance attest --agent academic-advisor --resource "slos://vaults/student-health/%" --since 90d
835
+ """
836
+ db_path = Path(get_db_path()).expanduser()
837
+ if not db_path.exists():
838
+ console.print("No audit database found.")
839
+ raise typer.Exit(1)
840
+
841
+ store = EnvelopeStore(str(db_path))
842
+ report = ComplianceReport(store)
843
+
844
+ ttl_seconds = parse_ttl(since)
845
+ start_time = datetime.now(timezone.utc).timestamp() - ttl_seconds
846
+
847
+ result = report.negative_attestation(
848
+ agent_id=agent_id,
849
+ resource_pattern=resource,
850
+ start_time=start_time,
851
+ )
852
+
853
+ if output_format == "json":
854
+ console.print(json.dumps(result, indent=2))
855
+ return
856
+
857
+ if result["confirmed"]:
858
+ console.print(f"\n[green bold]CONFIRMED: {agent_id} did NOT access {resource}[/green bold]")
859
+ else:
860
+ console.print(f"\n[red bold]FAILED: {agent_id} accessed {resource} ({result['count']} events)[/red bold]")
861
+
862
+ console.print(f"\n Agent: {result['agent_id']}")
863
+ console.print(f" Resource: {result['resource_pattern']}")
864
+ console.print(f" Window: last {since}")
865
+ console.print(f" Events: {result['count']}")
866
+ console.print(f" Hash: {result['attestation_hash']}")
867
+
868
+
869
+ @compliance_app.command("agent-report")
870
+ def compliance_agent_report(
871
+ agent_id: str = typer.Option(..., "--agent", "-a", help="Agent ID"),
872
+ resource: Optional[str] = typer.Option(None, "--resource", "-r", help="Resource pattern filter"),
873
+ since: str = typer.Option("30d", "--since", "-s", help="Time window"),
874
+ output_format: str = typer.Option("table", "--format", "-f", help="Output format: table, json, csv"),
875
+ output: Optional[str] = typer.Option(None, "--output", "-o", help="Output file path"),
876
+ ):
877
+ """Show all access events for an agent.
878
+
879
+ Examples:
880
+
881
+ carryall compliance agent-report --agent academic-advisor --since 30d
882
+
883
+ carryall compliance agent-report --agent financial-aid-agent --resource "slos://vaults/student-health/%" --format csv -o report.csv
884
+ """
885
+ db_path = Path(get_db_path()).expanduser()
886
+ if not db_path.exists():
887
+ console.print("No audit database found.")
888
+ raise typer.Exit(1)
889
+
890
+ store = EnvelopeStore(str(db_path))
891
+ report = ComplianceReport(store)
892
+
893
+ ttl_seconds = parse_ttl(since)
894
+ start_time = datetime.now(timezone.utc).timestamp() - ttl_seconds
895
+
896
+ result = report.agent_access_report(
897
+ agent_id=agent_id,
898
+ resource_pattern=resource,
899
+ start_time=start_time,
900
+ )
901
+
902
+ if output_format == "json":
903
+ if output:
904
+ report.export_json(result, output)
905
+ console.print(f"[green]Exported to {output}[/green]")
906
+ else:
907
+ console.print(json.dumps(result, indent=2, default=str))
908
+ return
909
+
910
+ if output_format == "csv":
911
+ entries = store.get_audit_trail(
912
+ agent_id=agent_id,
913
+ resource_pattern=resource,
914
+ )
915
+ if output:
916
+ report.export_csv(entries, output)
917
+ console.print(f"[green]Exported {len(entries)} entries to {output}[/green]")
918
+ else:
919
+ console.print(report.export_csv_string(entries))
920
+ return
921
+
922
+ # Table output
923
+ summary = result["summary"]
924
+ console.print(f"\n[bold]Agent Access Report: {agent_id}[/bold]")
925
+ console.print(f" Window: last {since}")
926
+
927
+ table = Table()
928
+ table.add_column("Metric", style="cyan")
929
+ table.add_column("Value", style="green")
930
+ table.add_row("Total Events", str(summary["total_events"]))
931
+ table.add_row("Successful", str(summary["successful"]))
932
+ table.add_row("Blocked", str(summary["blocked"]))
933
+ table.add_row("Distinct Resources", str(summary["distinct_resources"]))
934
+ console.print(table)
935
+
936
+
937
+ @compliance_app.command("resource-report")
938
+ def compliance_resource_report(
939
+ resource: str = typer.Option(..., "--resource", "-r", help="Resource pattern (SQL LIKE)"),
940
+ since: str = typer.Option("30d", "--since", "-s", help="Time window"),
941
+ output_format: str = typer.Option("table", "--format", "-f", help="Output format: table, json"),
942
+ ):
943
+ """Show all agents that accessed a resource.
944
+
945
+ Examples:
946
+
947
+ carryall compliance resource-report --resource "slos://vaults/student-records/%"
948
+
949
+ carryall compliance resource-report --resource "slos://vaults/student-health/%" --format json
950
+ """
951
+ db_path = Path(get_db_path()).expanduser()
952
+ if not db_path.exists():
953
+ console.print("No audit database found.")
954
+ raise typer.Exit(1)
955
+
956
+ store = EnvelopeStore(str(db_path))
957
+ report = ComplianceReport(store)
958
+
959
+ ttl_seconds = parse_ttl(since)
960
+ start_time = datetime.now(timezone.utc).timestamp() - ttl_seconds
961
+
962
+ result = report.resource_access_report(
963
+ resource_pattern=resource,
964
+ start_time=start_time,
965
+ )
966
+
967
+ if output_format == "json":
968
+ console.print(json.dumps(result, indent=2, default=str))
969
+ return
970
+
971
+ summary = result["summary"]
972
+ console.print(f"\n[bold]Resource Access Report: {resource}[/bold]")
973
+ console.print(f" Window: last {since}")
974
+
975
+ table = Table()
976
+ table.add_column("Metric", style="cyan")
977
+ table.add_column("Value", style="green")
978
+ table.add_row("Total Events", str(summary["total_events"]))
979
+ table.add_row("Distinct Agents", str(summary["distinct_agents"]))
980
+ console.print(table)
981
+
982
+ if result.get("agents"):
983
+ agent_table = Table(title="Agents")
984
+ agent_table.add_column("Agent ID", style="cyan")
985
+ agent_table.add_column("Access Count")
986
+ agent_table.add_column("First Access")
987
+ agent_table.add_column("Last Access")
988
+ for agent in result["agents"]:
989
+ agent_table.add_row(
990
+ agent["agent_id"],
991
+ str(agent["access_count"]),
992
+ agent.get("first_access", "")[:19],
993
+ agent.get("last_access", "")[:19],
994
+ )
995
+ console.print(agent_table)
996
+
997
+
998
+ @compliance_app.command("report")
999
+ def compliance_report(
1000
+ since: str = typer.Option("90d", "--since", "-s", help="Time window (e.g., 30d, 90d, 1y)"),
1001
+ output: str = typer.Option("report.html", "--output", "-o", help="Output file path"),
1002
+ output_format: str = typer.Option("html", "--format", "-f", help="Output format: html, json"),
1003
+ policy: Optional[str] = typer.Option(None, "--policy", "-p", help="Path to YAML policy file (adds data classifications)"),
1004
+ title: str = typer.Option("FERPA Compliance Report", "--title", "-t", help="Report title"),
1005
+ ):
1006
+ """Generate a comprehensive compliance report.
1007
+
1008
+ Produces a self-contained HTML document that can be emailed to legal.
1009
+ Includes executive summary, per-agent breakdown, negative attestation
1010
+ matrix, and data classification details.
1011
+
1012
+ Examples:
1013
+
1014
+ carryall compliance report --since 90d --output ferpa-q1.html
1015
+
1016
+ carryall compliance report --since 30d --policy policy.yaml --output report.html
1017
+
1018
+ carryall compliance report --format json --output report.json
1019
+ """
1020
+ db_path = Path(get_db_path()).expanduser()
1021
+ if not db_path.exists():
1022
+ console.print("No audit database found.")
1023
+ raise typer.Exit(1)
1024
+
1025
+ store = EnvelopeStore(str(db_path))
1026
+ report_gen = ComplianceReport(store)
1027
+
1028
+ ttl_seconds = parse_ttl(since)
1029
+ start_time = datetime.now(timezone.utc).timestamp() - ttl_seconds
1030
+
1031
+ # Load policy if provided
1032
+ policy_summary = None
1033
+ if policy:
1034
+ try:
1035
+ engine = PolicyEngine.load(policy)
1036
+ policy_summary = engine.summary()
1037
+ except Exception as e:
1038
+ console.print(f"[yellow]Warning:[/yellow] Could not load policy: {e}")
1039
+
1040
+ full_report = report_gen.generate_full_report(
1041
+ start_time=start_time,
1042
+ policy_summary=policy_summary,
1043
+ title=title,
1044
+ )
1045
+
1046
+ if output_format == "json":
1047
+ report_gen.export_json(full_report, output)
1048
+ console.print(f"[green]JSON report saved to {output}[/green]")
1049
+ return
1050
+
1051
+ # HTML output
1052
+ html = report_gen.render_html(full_report)
1053
+ with open(output, "w") as f:
1054
+ f.write(html)
1055
+
1056
+ console.print(f"[green]HTML compliance report saved to {output}[/green]")
1057
+ exec_summary = full_report["executive_summary"]
1058
+ console.print(f" Agents: {exec_summary['total_agents']}, Events: {exec_summary['total_events']}, "
1059
+ f"Blocked: {exec_summary['blocked']}, Attestations: {len(full_report['attestations'])}")
1060
+
1061
+
1062
+ @compliance_app.command("summary")
1063
+ def compliance_summary(
1064
+ since: str = typer.Option("30d", "--since", "-s", help="Time window"),
1065
+ output_format: str = typer.Option("table", "--format", "-f", help="Output format: table, json"),
1066
+ ):
1067
+ """Show compliance summary across all agents.
1068
+
1069
+ Examples:
1070
+
1071
+ carryall compliance summary --since 30d
1072
+
1073
+ carryall compliance summary --format json
1074
+ """
1075
+ db_path = Path(get_db_path()).expanduser()
1076
+ if not db_path.exists():
1077
+ console.print("No audit database found.")
1078
+ raise typer.Exit(1)
1079
+
1080
+ store = EnvelopeStore(str(db_path))
1081
+ report = ComplianceReport(store)
1082
+
1083
+ result = report.scope_usage_report()
1084
+
1085
+ if output_format == "json":
1086
+ console.print(json.dumps(result, indent=2, default=str))
1087
+ return
1088
+
1089
+ summary = result["summary"]
1090
+ console.print(f"\n[bold]Compliance Summary[/bold]")
1091
+
1092
+ table = Table()
1093
+ table.add_column("Metric", style="cyan")
1094
+ table.add_column("Value", style="green")
1095
+ table.add_row("Total Events", str(summary["total_events"]))
1096
+ table.add_row("Distinct Agents", str(summary["distinct_agents"]))
1097
+ table.add_row("Successful", str(summary.get("successful", "N/A")))
1098
+ table.add_row("Blocked", str(summary.get("blocked", "N/A")))
1099
+ console.print(table)
1100
+
1101
+ if result.get("agents"):
1102
+ agent_table = Table(title="Agent Activity")
1103
+ agent_table.add_column("Agent ID", style="cyan")
1104
+ agent_table.add_column("Events")
1105
+ agent_table.add_column("Successful")
1106
+ agent_table.add_column("Blocked")
1107
+ for agent in result["agents"]:
1108
+ agent_table.add_row(
1109
+ agent["agent_id"],
1110
+ str(agent["total_events"]),
1111
+ str(agent.get("successful", 0)),
1112
+ str(agent.get("blocked", 0)),
1113
+ )
1114
+ console.print(agent_table)
1115
+
1116
+
1117
+ # =============================================================================
1118
+ # Policy commands
1119
+ # =============================================================================
1120
+
1121
+
1122
+ @policy_app.command("validate")
1123
+ def policy_validate(
1124
+ path: str = typer.Argument(..., help="Path to YAML policy file"),
1125
+ ):
1126
+ """Validate a YAML policy file and show a summary.
1127
+
1128
+ Examples:
1129
+
1130
+ carryall policy validate examples/edtech-policy.yaml
1131
+ """
1132
+ try:
1133
+ engine = PolicyEngine.load(path)
1134
+ except PolicyValidationError as e:
1135
+ console.print(f"[red]INVALID:[/red] {e}")
1136
+ raise typer.Exit(1)
1137
+ except Exception as e:
1138
+ console.print(f"[red]Error loading policy:[/red] {e}")
1139
+ raise typer.Exit(1)
1140
+
1141
+ s = engine.summary()
1142
+ console.print(f"[green]Valid.[/green] {s['agent_count']} agents, "
1143
+ f"{s['classification_count']} data classifications, "
1144
+ f"{', '.join(s['compliance_frameworks']) or 'no'} compliance framework(s)")
1145
+ console.print(f" Organization: {s['organization']}")
1146
+ console.print(f" Version: {s['version']}")
1147
+
1148
+
1149
+ @policy_app.command("show")
1150
+ def policy_show(
1151
+ path: str = typer.Argument(..., help="Path to YAML policy file"),
1152
+ output_format: str = typer.Option("table", "--format", "-f", help="Output format: table, json"),
1153
+ ):
1154
+ """Show policy details in a rich table.
1155
+
1156
+ Examples:
1157
+
1158
+ carryall policy show examples/edtech-policy.yaml
1159
+
1160
+ carryall policy show examples/edtech-policy.yaml --format json
1161
+ """
1162
+ try:
1163
+ engine = PolicyEngine.load(path)
1164
+ except PolicyValidationError as e:
1165
+ console.print(f"[red]INVALID:[/red] {e}")
1166
+ raise typer.Exit(1)
1167
+
1168
+ if output_format == "json":
1169
+ console.print(json.dumps(engine.summary(), indent=2))
1170
+ return
1171
+
1172
+ s = engine.summary()
1173
+
1174
+ # Header
1175
+ console.print(f"\n[bold]{s['organization']}[/bold] — Policy v{s['version']}")
1176
+ if s['compliance_frameworks']:
1177
+ console.print(f" Frameworks: {', '.join(s['compliance_frameworks'])}")
1178
+
1179
+ # Agents table
1180
+ agent_table = Table(title="Agent Policies")
1181
+ agent_table.add_column("Agent ID", style="cyan")
1182
+ agent_table.add_column("Scopes")
1183
+ agent_table.add_column("Constraints")
1184
+ agent_table.add_column("Denied Resources", style="red")
1185
+
1186
+ for agent in s["agents"]:
1187
+ constraints_str = ", ".join(
1188
+ f"{k}={v}" for k, v in agent["constraints"].items()
1189
+ ) or "none"
1190
+ denied_str = "\n".join(agent["denied_resources"]) or "none"
1191
+ scopes_str = "\n".join(agent["scopes"])
1192
+ agent_table.add_row(agent["id"], scopes_str, constraints_str, denied_str)
1193
+
1194
+ console.print(agent_table)
1195
+
1196
+ # Data classifications table
1197
+ if s["data_classifications"]:
1198
+ dc_table = Table(title="Data Classifications")
1199
+ dc_table.add_column("Domain", style="cyan")
1200
+ dc_table.add_column("Sensitivity")
1201
+ dc_table.add_column("PII Fields", style="yellow")
1202
+ dc_table.add_column("Retention")
1203
+
1204
+ for dc in s["data_classifications"]:
1205
+ sensitivity_style = {
1206
+ "internal": "green",
1207
+ "confidential": "yellow",
1208
+ "restricted": "red",
1209
+ }.get(dc["sensitivity"], "white")
1210
+
1211
+ retention = f"{dc['retention_days']} days" if dc["retention_days"] else "not set"
1212
+
1213
+ dc_table.add_row(
1214
+ dc["domain"],
1215
+ f"[{sensitivity_style}]{dc['sensitivity']}[/{sensitivity_style}]",
1216
+ ", ".join(dc["pii_fields"]) or "none",
1217
+ retention,
1218
+ )
1219
+
1220
+ console.print(dc_table)
1221
+
1222
+
1223
+ # =============================================================================
1224
+ # Database commands
1225
+ # =============================================================================
1226
+
1227
+
1228
+ @db_app.command("migrate")
1229
+ def db_migrate():
1230
+ """Run pending schema migrations.
1231
+
1232
+ Automatically backs up the database before applying migrations.
1233
+ Safe to run repeatedly — only pending migrations are applied.
1234
+ """
1235
+ from .storage import MIGRATIONS
1236
+
1237
+ db_path = Path(get_db_path()).expanduser()
1238
+ store = EnvelopeStore(str(db_path))
1239
+
1240
+ version = store.get_schema_version()
1241
+ latest = MIGRATIONS[-1][0] if MIGRATIONS else 0
1242
+
1243
+ if version >= latest:
1244
+ console.print(f"[green]Database is up to date (version {version}).[/green]")
1245
+ else:
1246
+ console.print(f"[green]Migrations complete. Schema version: {store.get_schema_version()}[/green]")
1247
+
1248
+
1249
+ @db_app.command("status")
1250
+ def db_status():
1251
+ """Show current schema version and migration history."""
1252
+ from .storage import MIGRATIONS
1253
+
1254
+ db_path = Path(get_db_path()).expanduser()
1255
+
1256
+ if not db_path.exists():
1257
+ console.print(f"No database found at {db_path}")
1258
+ return
1259
+
1260
+ store = EnvelopeStore(str(db_path))
1261
+ version = store.get_schema_version()
1262
+ latest = MIGRATIONS[-1][0] if MIGRATIONS else 0
1263
+
1264
+ console.print(f"\n[bold]Database Status[/bold]")
1265
+ console.print(f"Path: {db_path}")
1266
+ console.print(f"Schema version: {version}")
1267
+ console.print(f"Latest available: {latest}")
1268
+
1269
+ if version < latest:
1270
+ console.print(f"[yellow]Pending migrations: {latest - version}[/yellow]")
1271
+ else:
1272
+ console.print(f"[green]All migrations applied.[/green]")
1273
+
1274
+ history = store.get_migration_history()
1275
+ if history:
1276
+ table = Table(title="Migration History")
1277
+ table.add_column("Version", style="cyan")
1278
+ table.add_column("Applied At", style="dim")
1279
+ table.add_column("Description")
1280
+ for m in history:
1281
+ table.add_row(str(m["version"]), m["applied_at"][:19], m["description"])
1282
+ console.print(table)
1283
+
1284
+
1285
+ # =============================================================================
1286
+ # MCP commands
1287
+ # =============================================================================
1288
+
1289
+
1290
+ @mcp_app.command("serve")
1291
+ def mcp_serve(
1292
+ transport: str = typer.Option("stdio", "--transport", "-t", help="Transport: stdio or http"),
1293
+ host: str = typer.Option("0.0.0.0", "--host", "-H", help="HTTP host to bind (http transport only)"),
1294
+ port: int = typer.Option(8765, "--port", "-p", help="HTTP port to listen on (http transport only)"),
1295
+ mock: bool = typer.Option(False, "--mock", help="Use mock backends (no real SLOS)"),
1296
+ ):
1297
+ """Start MCP server for Clawdbot integration.
1298
+
1299
+ Supports two transport modes:
1300
+
1301
+ STDIO (default): Listens on stdin/stdout for JSON-RPC 2.0 requests.
1302
+ Use this for local MCP clients like Clawdbot desktop.
1303
+
1304
+ HTTP: Listens on HTTP for JSON-RPC and REST requests.
1305
+ Use this for Kubernetes sidecar deployments.
1306
+
1307
+ Tools exposed:
1308
+ - carryall_check_access: Check if an envelope allows an action
1309
+ - carryall_list_vaults: List SLOS vaults
1310
+ - carryall_get_metadata: Get document metadata
1311
+ - carryall_audit_log: Query the audit log
1312
+
1313
+ Examples:
1314
+
1315
+ # Stdio mode (for local Clawdbot)
1316
+ carryall mcp serve
1317
+
1318
+ # HTTP mode (for Kubernetes sidecar)
1319
+ carryall mcp serve --transport http --port 8765
1320
+
1321
+ Clawdbot config (~/.clawdbot/clawdbot.json):
1322
+
1323
+ {
1324
+ "mcpServers": {
1325
+ "carryall": {
1326
+ "command": "carryall",
1327
+ "args": ["mcp", "serve"]
1328
+ }
1329
+ }
1330
+ }
1331
+ """
1332
+ import asyncio
1333
+ from .mcp_server import CarryallMCPServer
1334
+
1335
+ if transport not in ["stdio", "http"]:
1336
+ console.print(f"[red]Error:[/red] Unknown transport: {transport}")
1337
+ console.print("Supported: stdio, http")
1338
+ raise typer.Exit(1)
1339
+
1340
+ server = CarryallMCPServer()
1341
+
1342
+ try:
1343
+ if transport == "http":
1344
+ asyncio.run(server.run_http(host, port))
1345
+ else:
1346
+ asyncio.run(server.run_stdio())
1347
+ except KeyboardInterrupt:
1348
+ console.print("\nServer stopped.")
1349
+
1350
+
1351
+ @mcp_app.command("config")
1352
+ def mcp_config():
1353
+ """Show Clawdbot configuration for carryall MCP server."""
1354
+ config = {
1355
+ "mcpServers": {
1356
+ "carryall": {
1357
+ "command": "carryall",
1358
+ "args": ["mcp", "serve"],
1359
+ }
1360
+ }
1361
+ }
1362
+
1363
+ console.print("[bold]Add this to ~/.clawdbot/clawdbot.json:[/bold]")
1364
+ console.print()
1365
+ console.print(json.dumps(config, indent=2))
1366
+ console.print()
1367
+ console.print("Or for Claude Desktop (~/.claude/claude_desktop_config.json):")
1368
+ console.print()
1369
+ console.print(json.dumps(config, indent=2))
1370
+
1371
+
1372
+ # =============================================================================
1373
+ # Utility functions
1374
+ # =============================================================================
1375
+
1376
+
1377
+ def parse_ttl(ttl: str) -> int:
1378
+ """Parse TTL string (e.g., '1h', '24h', '7d') to seconds."""
1379
+ ttl = ttl.strip().lower()
1380
+
1381
+ if ttl.endswith("s"):
1382
+ return int(ttl[:-1])
1383
+ elif ttl.endswith("m"):
1384
+ return int(ttl[:-1]) * 60
1385
+ elif ttl.endswith("h"):
1386
+ return int(ttl[:-1]) * 3600
1387
+ elif ttl.endswith("d"):
1388
+ return int(ttl[:-1]) * 86400
1389
+ else:
1390
+ # Assume seconds
1391
+ return int(ttl)
1392
+
1393
+
1394
+ # =============================================================================
1395
+ # Main entry point
1396
+ # =============================================================================
1397
+
1398
+
1399
+ def main():
1400
+ """Entry point for the CLI."""
1401
+ app()
1402
+
1403
+
1404
+ if __name__ == "__main__":
1405
+ main()