# AKIOS CLI Module - Technical Reference

**Security-first command-line interface for the AKIOS security framework.**

## Overview

The CLI module provides a comprehensive, secure command-line interface for managing AKIOS projects and workflows. It implements 10 core commands with strict input validation, security enforcement, and intelligent error handling.

## Architecture

```
cli/
├── __init__.py          # CLI module exports
├── __main__.py          # Entry point delegation
├── main.py              # Main CLI application & command routing
├── commands/            # Individual command implementations
│   ├── __init__.py      # Command registration & lazy loading
│   ├── init.py          # Project initialization
│   ├── run.py           # Workflow execution
│   ├── status.py        # System status & security dashboard
│   ├── workflow.py      # Workflow instance management
│   ├── audit.py         # Audit log management & exports
│   ├── logs.py          # Log viewing utilities
│   ├── clean.py         # System maintenance
│   ├── testing.py       # Environment diagnostics
│   ├── setup.py         # Interactive configuration
│   └── templates.py     # Template management
├── data/                # Sample data and resources
│   └── samples/         # Test data for workflow templates
│       ├── analysis_targets/  # File analysis test samples (PDF, DOCX, TXT)
│       └── document_examples/ # Document ingestion test samples (PDF, DOCX, TXT)
├── helpers.py           # Shared CLI utilities & error handling
└── README.md            # This file
```

## Global Options

All commands support the following global options:

- **`--debug`**: Enable detailed debug logging for troubleshooting and development
- **`--help, -h`**: Display command help and usage information
- **`--version`**: Show AKIOS version information

Debug logging provides comprehensive internal operation details including:
- Configuration loading and validation sequences
- Workflow execution step-by-step tracing
- Agent operations and API call parameters
- Security validation and audit event generation
- Error conditions with full stack traces

## Commands

### Project Lifecycle

#### `init.py` - Project Initialization
- Creates secure project structure with safe defaults
- Generates configuration files with security hardening
- Copies validated production templates and sample data
- Sets up audit directories and security contexts
- Provides welcoming user experience (unless --quiet)

#### `setup.py` - Interactive Setup Wizard
- Guides users through first-time configuration
- Validates system compatibility and security features
- Configures API keys and environment settings
- Tests connectivity and permissions
- Provides clear success/failure feedback

### Workflow Management

#### `run.py` - Workflow Execution
- Parses and validates YAML workflows with schema enforcement
- Applies comprehensive security sandboxing and isolation
- Executes multi-agent orchestration with cost tracking
- Generates cryptographic audit logs with Merkle integrity
- Provides real-time progress and resource monitoring
- Includes detailed debug logging for workflow execution steps
- Supports environment variable expansion in workflow parameters

#### `workflow.py` - Workflow Instance Management
- Creates isolated workflow instances for repeatability
- Manages workflow lifecycle (create, run, list, delete, status)
- Supports template-based instantiation
- Tracks execution history and performance metrics
- Enables workflow versioning and comparison
- Includes safety confirmations and --dry-run for delete operations

### Monitoring & Diagnostics

#### `status.py` - System Status & Security Dashboard
- Validates all security components (seccomp, cgroups, PII, audit)
- Provides comprehensive security level assessment
- Checks API key configuration across all providers
- Reports resource usage and budget tracking
- Displays real-time security status and active protections
- Formats output for user experience (emojis, human-readable time, next steps guidance)
- Supports progressive disclosure with --verbose flag for technical details
- Includes debug logging for configuration validation and security checks
- Validates project context before showing status information

#### `testing.py` - Environment Diagnostics
- Auto-detects system capabilities and constraints
- Provides environment-specific recommendations
- Tracks testing issues and compatibility notes
- Supports multiple output formats (table, JSON, summary)
- Enables manual issue logging and categorization

### Audit & Compliance

#### `audit.py` - Audit Management & Export
- Exports cryptographic audit logs in multiple formats
- Validates Merkle tree integrity and tamper-evident trails
- Manages audit retention policies and cleanup
- Generates security posture reports for workflow validation
- Supports both programmatic and human-readable outputs

### System Administration

#### `clean.py` - System Maintenance
- Performs intelligent cleanup of project data
- Manages disk space with configurable retention policies
- Supports dry-run mode for safe preview
- Provides detailed cleanup reporting and metrics
- Respects security boundaries during maintenance

#### `logs.py` - Log Management & Analysis
- Views comprehensive workflow execution logs
- Supports intelligent filtering by workflow, time, and severity
- Provides searchable log content with highlighting
- Exports filtered logs for external analysis
- Integrates with audit system for complete traceability

### Content Management

#### `templates.py` - Template Management
- Lists available validated workflow templates
- Provides template descriptions and use cases
- Supports template discovery and selection
- Enables template customization workflows
- Maintains template integrity and security

## Design Decisions: Infrastructure vs User Data

AKIOS follows a deliberate architectural pattern for handling different types of content during project initialization:

### Infrastructure Templates (Hardcoded)
**Project structure files** (config.yaml, README.md, .gitignore, .env templates) are **hardcoded in the CLI code** rather than stored as external files.

**Rationale:**
- **Guaranteed Reliability**: Project initialization must never fail due to missing files
- **Self-Contained Distribution**: No external file dependencies for critical infrastructure
- **Version Consistency**: Templates evolve with code changes, maintaining compatibility
- **Performance**: No file I/O overhead during project creation
- **Availability Requirements**: Critical system components need 100% availability

### User Sample Data (File-based)
**Workflow test samples** (.pdf, .docx, .txt files) are stored as **external package data files** and loaded via `importlib.resources`.

**Rationale:**
- **Real Test Data**: Binary files impractical to maintain in source code
- **User Customization**: Projects can replace samples with real data
- **Multiple Formats**: Support for various file types (.pdf, .docx, .txt)
- **Package Optimization**: Can be excluded from lean distributions if needed
- **Maintenance**: Easy to update samples without code modifications

### Implementation Pattern
```python
# Infrastructure (hardcoded) - always works
def create_readme() -> str:
    return """# AKIOS Project\n..."""

# Samples (file-based) - flexible with fallbacks
sample_content = resources.files('akios.cli.data.samples.document_examples')
    .joinpath('sample.txt').read_bytes()
```

This hybrid approach balances **production reliability** with **user flexibility**.

## Security Enforcement

Every command implements security-first execution:

```python
def run_command_name(args: argparse.Namespace) -> int:
    """Execute command with comprehensive security and error handling."""
    try:
        # 1. Project context validation
        check_project_context()

        # 2. Input sanitization and validation
        validated_params = validate_and_sanitize_inputs(args)

        # 3. Security pre-checks
        validate_command_security(args.command)

        # 4. Audit context establishment
        with audit_context(operation=args.command):
            # 5. Execute with resource limits and monitoring
            result = execute_with_limits(validated_params)

        # 6. Success logging and user feedback
        log_command_success(args.command, result)
        return 0

    except CLIError as e:
        return handle_cli_error(e, json_mode=getattr(args, 'json', False))
    except Exception as e:
        return handle_cli_error(e, json_mode=getattr(args, 'json', False))
```

## Command Registration

Commands are registered using lazy loading for performance in `__init__.py`:

```python
def register_all_commands(subparsers: argparse._SubParsersAction) -> None:
    """Register all CLI commands with lazy loading."""
    # Core commands
    _lazy_import_command('init').register_init_command(subparsers)
    _lazy_import_command('run').register_run_command(subparsers)
    _lazy_import_command('status').register_status_command(subparsers)

    # Advanced commands
    _lazy_import_command('workflow').register_workflow_command(subparsers)
    _lazy_import_command('audit').register_audit_command(subparsers)
    _lazy_import_command('logs').register_logs_command(subparsers)
    _lazy_import_command('clean').register_clean_command(subparsers)
    _lazy_import_command('testing').register_testing_command(subparsers)
    _lazy_import_command('setup').register_setup_command(subparsers)
    _lazy_import_command('templates').register_templates_command(subparsers)
```

## Error Handling

Commands provide intelligent error classification and user guidance:

- **`CLIError`** - Command-specific errors with exit codes
- **`ConfigurationError`** - Invalid config, missing files, environment issues
- **`SecurityViolation`** - Blocked by sandbox policies or permission issues
- **`ValidationError`** - Invalid parameters, malformed inputs, constraint violations
- **`ExecutionError`** - Runtime failures, timeouts, resource exhaustion
- **`NetworkError`** - Connectivity issues, API failures, rate limits

All errors are processed through `handle_cli_error()` for consistent user experience.

## Integration Points

Commands integrate comprehensively with all AKIOS framework components:

- **`config`** - Settings loading, validation, and environment management
- **`core.runtime`** - Workflow execution engine and agent orchestration
- **`core.audit`** - Cryptographic audit trails and security posture scoring
- **`security`** - Sandboxing, syscall filtering, PII redaction, and isolation
- **`templates`** - Validated workflow templates and example repositories

## Testing Standards

Each command includes comprehensive test coverage:

- **Unit tests** - Core logic validation with mocked dependencies
- **Integration tests** - End-to-end workflows with security validation
- **Security tests** - Sandbox enforcement and permission validation
- **Error handling tests** - All error paths and edge conditions
- **Performance tests** - Resource usage and execution time validation

## Development Standards

- **Type safety** - Full type hints on all function signatures
- **Security first** - Project context and security validation before execution
- **Error resilience** - Comprehensive exception handling with user guidance
- **Audit compliance** - Complete audit logging for all operations
- **User experience** - Clear help text, progress indicators, and actionable feedback
- **Performance conscious** - Lazy loading, efficient algorithms, resource awareness
- **Maintainable** - Clear separation of concerns, comprehensive documentation

## Security Integration

The CLI enforces security-first controls at every interaction:

- **Input validation** - All file paths, parameters, and user inputs validated
- **Security validation** - Pre-command security checks prevent unsafe operations
- **Audit logging** - Comprehensive logging of all CLI operations with Merkle integrity
- **Project context** - Commands validate execution within valid AKIOS project directories
- **Resource limits** - Automatic cost controls and execution timeouts
- **PII protection** - Automatic redaction of sensitive data in inputs and outputs

## Entry Points

- **`python -m akios.cli`** - Direct module execution
- **`akios`** - Docker wrapper script (recommended for production)
- **`python -m akios`** - Alternative direct execution

---

**Internal Technical Reference - Not for Public Distribution** 🔒
