Purple8-platform

Code Governance System

Overview

The Code Governance System ensures that all code generated by 8 is protected, properly promoted through environments, requires human approval for production, and respects licensing constraints.

Core Principles

  1. Code Immutability: Generated code is cryptographically signed and tampering is detected
  2. Environment Progression: Code must follow dev → staging → prod workflow
  3. Human-in-the-Loop: Production deployments require explicit human approval
  4. Licensing Control: Features and deployments are gated by license tier

Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                    CODE GOVERNANCE LAYERS                            │
│                                                                      │
│  Layer 1: CODE PROTECTION                                           │
│  ├─ Cryptographic signing (SHA-256)                                 │
│  ├─ Tampering detection                                             │
│  ├─ Environment tagging (dev/staging/prod)                          │
│  └─ Immutability enforcement                                        │
│                                                                      │
│  Layer 2: ENVIRONMENT PROMOTION                                     │
│  ├─ dev → staging → prod workflow                                   │
│  ├─ Block direct production deployment                              │
│  ├─ Promotion history tracking                                      │
│  └─ Rollback support                                                │
│                                                                      │
│  Layer 3: HUMAN-IN-THE-LOOP APPROVAL                                │
│  ├─ Production deployment gates                                     │
│  ├─ Reviewer assignment                                             │
│  ├─ Audit trail generation                                          │
│  └─ Rejection handling                                              │
│                                                                      │
│  Layer 4: LICENSING & USAGE CONTROL                                 │
│  ├─ License validation                                              │
│  ├─ Feature gating by tier                                          │
│  ├─ Usage limits enforcement                                        │
│  └─ Compliance reporting                                            │
└─────────────────────────────────────────────────────────────────────┘

Layer 1: Code Protection

Purpose

Prevents unauthorized modification of 8-generated code and enforces immutability.

Features

1. Cryptographic Signing

Every artifact generated by 8 is signed with SHA-256 hash:

from shared.agents.code_protection_agent import CodeProtectionAgent

agent = CodeProtectionAgent()

# Sign code for development
signed = agent.sign_artifact(
    content=code_content,
    artifact_type='python',
    environment='dev',
    metadata={'project': 'my-app', 'component': 'backend'}
)

# Result includes:
# - content: Protected code with header
# - signature: Hash, timestamp, environment tag
# - hash: SHA-256 hash for validation
# - environment: Tagged environment (dev/staging/prod)

2. Tampering Detection

Automatically detects if code has been modified:

# Validate artifact integrity
validation = agent.validate_artifact(signed_artifact)

if validation['tampering_detected']:
    print(f"⚠️ Code has been modified!")
    print(f"Reason: {validation['reason']}")
    # Reject deployment

3. Environment Tagging

Each artifact is tagged for specific environment:

# Check if artifact can deploy to target environment
compatibility = agent.check_environment_compatibility(
    artifact_environment='dev',
    target_environment='prod'
)

if not compatibility['is_compatible']:
    print(f"❌ {compatibility['reason']}")
    # Output: "Cannot deploy dev code directly to prod. Use promotion workflow."

4. Protection Headers

All code includes tamper-evident header:

# Example protected Python file:
#
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 🔒 CODE PROTECTION - DO NOT MODIFY
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# Artifact Hash: abc123def456...
# Environment: dev
# Signed At: 2025-12-05T10:30:00Z
# Signed By: 8
#
# ⚠️ WARNING: Modifications will be detected and rejected.
# ⚠️ For production deployment, code must be promoted through proper channels.
# ⚠️ Human-in-the-Loop approval required for production environments.
#
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#

def my_function():
    # Your code here
    pass

API Reference

CodeProtectionAgent


Layer 2: Environment Promotion

Purpose

Enforces proper environment progression and prevents unauthorized production deployments.

Workflow

Development → Staging → Production
    ↓           ↓          ↓
   dev        staging     prod
  (auto)      (auto)    (approval)

Features

1. Promotion Workflow

Code must progress through environments sequentially:

from services.environment_promotion import EnvironmentPromotion

promotion = EnvironmentPromotion()

# Try to promote dev → prod (BLOCKED)
result = promotion.create_promotion_request(
    project_id='my-app',
    from_environment='dev',
    to_environment='prod',
    artifacts=dev_artifacts,
    requested_by='developer@example.com'
)

# Output: {
#   'success': False,
#   'reason': 'Cannot skip environments. Must promote: dev → staging → prod'
# }

# Correct flow: dev → staging (ALLOWED)
result = promotion.create_promotion_request(
    project_id='my-app',
    from_environment='dev',
    to_environment='staging',
    artifacts=dev_artifacts,
    requested_by='developer@example.com'
)

# Output: {
#   'success': True,
#   'request_id': 'promo-uuid-123',
#   'status': 'approved',
#   'requires_approval': False  # Staging is auto-approved
# }

2. Block Direct Production Deployment

System automatically blocks attempts to deploy non-prod code to production:

# Check if artifacts attempt direct prod deployment
block_result = promotion.block_direct_production_deployment(dev_artifacts)

if block_result['blocked']:
    print(f"⛔ {block_result['message']}")
    # Output: "Cannot deploy 5 non-production artifacts directly to production"
    print(f"Required action: {block_result['required_action']}")
    # Output: "Create promotion request through proper channels"

3. Promotion History

Track all environment promotions with audit trail:

# Get promotion history for project
history = promotion.get_promotion_history(project_id='my-app', limit=20)

for request in history:
    print(f"{request['from_environment']}{request['to_environment']}")
    print(f"Status: {request['status']}")
    print(f"Requested: {request['requested_at']}")
    if request['approval']:
        print(f"Approved by: {request['approval']['approved_by']}")

4. Pending Approvals

View all promotion requests awaiting approval:

# Get pending prod promotions
pending = promotion.get_pending_approvals(to_environment='prod')

print(f"Pending production promotions: {len(pending)}")
for request in pending:
    print(f"  - {request['project_id']}: {request['artifact_count']} artifacts")
    print(f"    Requested by: {request['requested_by']}")

API Reference

EnvironmentPromotion


Layer 3: Human-in-the-Loop (HITL) Approval

Purpose

Requires explicit human approval before any code reaches production environment.

Features

1. Approval Workflow

Production deployments create approval requests:

from services.hitl_approval_system import HITLApprovalSystem

hitl = HITLApprovalSystem()

# Create approval request for production deployment
result = hitl.create_approval_request(
    promotion_request_id='promo-123',
    project_id='my-app',
    environment='prod',
    artifacts=staging_artifacts,
    requested_by='developer@example.com',
    security_assessment={'risk_level': 'HIGH', 'controls': 12},
    metadata={'ticket': 'JIRA-456', 'sprint': 'Sprint 10'}
)

if result['requires_manual_approval']:
    approval_id = result['approval_id']
    print(f"⏳ Approval required: {approval_id}")
    print(f"   {result['message']}")
    # Output: "Approval request created. Requires 1 approver(s)."

2. Approve Deployment

Authorized reviewers can approve:

# Tech lead approves deployment
approval = hitl.approve(
    approval_id='approval-uuid-456',
    approved_by='tech_lead@example.com',
    approval_notes='Code reviewed, security validated, tests passing',
    reviewed_artifacts=['hash1', 'hash2', 'hash3']
)

if approval['status'] == 'approved':
    print(f"✅ {approval['message']}")
    # Output: "Deployment approved - all required approvals received"

3. Reject Deployment

Reviewers can block problematic deployments:

# Security team rejects deployment
rejection = hitl.reject(
    approval_id='approval-uuid-456',
    rejected_by='security@example.com',
    rejection_reason='Critical security vulnerabilities found',
    blocking_issues=[
        'SQL injection in user input handler',
        'Missing encryption for PII data',
        'No rate limiting on API endpoints'
    ]
)

print(f"❌ {rejection['message']}")
# Output: "Deployment rejected: Critical security vulnerabilities found"

4. Audit Trail

Complete audit history for compliance:

# Get audit trail for approval
audit = hitl.get_audit_trail(approval_id='approval-uuid-456')

for entry in audit:
    print(f"{entry['timestamp']}: {entry['action']} by {entry['actor']}")
    print(f"  Details: {entry['details']}")

# Example output:
# 2025-12-05T10:00:00Z: approval by tech_lead@example.com
#   Details: {'notes': 'Code reviewed', 'artifacts_reviewed': 3}
# 2025-12-05T09:55:00Z: request_created by developer@example.com
#   Details: {'project': 'my-app', 'environment': 'prod'}

5. Pending Reviews

View all deployments awaiting approval:

# Get pending approvals for reviewer
pending = hitl.get_pending_approvals(reviewer='tech_lead@example.com')

print(f"Pending reviews for tech_lead: {len(pending)}")
for request in pending:
    print(f"  - {request['project_id']}")
    print(f"    Risk: {request['security_assessment']['risk_level']}")
    print(f"    Requested: {request['requested_at']}")

Approval Policies

Environment Required Approvers Allowed Reviewers Timeout
dev 0 (auto-approve) N/A N/A
staging 0 (auto-approve) N/A N/A
prod 1 admin, tech_lead, qa_lead 24 hours

API Reference

HITLApprovalSystem


Layer 4: Licensing & Usage Control

Purpose

Ensures users respect license terms and controls access to features based on subscription tier.

License Tiers

Free Tier ($0/month)

Starter ($10.99/month)

Professional ($199.99/month)

Enterprise (Custom pricing)

Features

1. License Validation

Validate license before operations:

from services.licensing_control import LicensingControl

licensing = LicensingControl()

# Validate user's license
validation = licensing.validate_license(license_key='XXXX-XXXX-XXXX-XXXX')

if validation['is_valid']:
    print(f"✅ License valid: {validation['tier_name']}")
    print(f"   Features: {', '.join(validation['features'])}")
    print(f"   Expires: {validation['expires_at']}")
else:
    print(f"❌ {validation['reason']}")

2. Feature Gating

Check feature access based on tier:

# Check if user can access code protection
access = licensing.check_feature_access(license_key, 'code_protection')

if not access['has_access']:
    print(f"⚠️ {access['reason']}")
    print(f"   Current tier: {access['current_tier']}")
    print(f"   Required tier: {access['required_tier']}")
    # Output: "Feature 'code_protection' not available in Starter tier"
    # Output: "Required tier: professional"

3. Usage Limits

Track and enforce monthly limits:

# Check current usage
usage = licensing.check_usage_limits(license_key)

if not usage['within_limits']:
    print(f"⚠️ Usage limit exceeded!")
else:
    print(f"Projects this month: {usage['usage']['projects_this_month']}")
    print(f"Remaining: {usage['usage']['projects_remaining']}")

4. Record Usage

Track usage for billing and compliance:

# Record project creation
result = licensing.record_usage(
    license_key=license_key,
    usage_type='project_created',
    metadata={'project_name': 'my-app', 'goal': 'mvp'}
)

if not result['within_limits']:
    print(f"⚠️ Monthly limit reached!")
    print(f"   Upgrade to continue creating projects")

5. Environment Access

Gate environments by license tier:

# Check if user can deploy to production
access = licensing.can_deploy_to_environment(license_key, 'prod')

if not access['can_deploy']:
    print(f"❌ {access['reason']}")
    print(f"   Upgrade to {access['required_tier']} tier for production deployment")
else:
    print(f"✅ Production deployment allowed")

API Reference

LicensingControl


Integration Example

Complete Flow: Dev → Production

from shared.agents.code_protection_agent import CodeProtectionAgent
from services.environment_promotion import EnvironmentPromotion
from services.hitl_approval_system import HITLApprovalSystem
from services.licensing_control import LicensingControl

# Initialize systems
code_protection = CodeProtectionAgent()
promotion_system = EnvironmentPromotion()
hitl_system = HITLApprovalSystem()
licensing = LicensingControl()

license_key = 'USER-LICENSE-KEY'

# Step 1: Validate license
validation = licensing.validate_license(license_key)
if not validation['is_valid']:
    raise Exception(f"Invalid license: {validation['reason']}")

# Step 2: Check production access
prod_access = licensing.can_deploy_to_environment(license_key, 'prod')
if not prod_access['can_deploy']:
    raise Exception(f"Production not available: {prod_access['reason']}")

# Step 3: Sign code for dev
signed_dev = code_protection.sign_artifact(
    content=generated_code,
    artifact_type='python',
    environment='dev',
    metadata={'project': 'my-app'}
)

# Step 4: Deploy to dev (auto-approved)
print("✅ Deployed to development")

# Step 5: Promote dev → staging
promo_staging = promotion_system.create_promotion_request(
    project_id='my-app',
    from_environment='dev',
    to_environment='staging',
    artifacts=[signed_dev],
    requested_by='developer@example.com'
)

if promo_staging['success']:
    # Re-sign for staging
    signed_staging = code_protection.tag_for_environment(
        artifacts=[signed_dev],
        target_environment='staging',
        promotion_metadata=promo_staging['request']
    )
    print("✅ Promoted to staging")

# Step 6: Promote staging → prod (requires approval)
promo_prod = promotion_system.create_promotion_request(
    project_id='my-app',
    from_environment='staging',
    to_environment='prod',
    artifacts=signed_staging,
    requested_by='developer@example.com'
)

# Step 7: Create HITL approval request
approval_request = hitl_system.create_approval_request(
    promotion_request_id=promo_prod['request_id'],
    project_id='my-app',
    environment='prod',
    artifacts=signed_staging,
    requested_by='developer@example.com',
    security_assessment={'risk_level': 'HIGH', 'controls': 12}
)

print(f"⏳ Awaiting approval: {approval_request['approval_id']}")

# Step 8: Tech lead reviews and approves
approval = hitl_system.approve(
    approval_id=approval_request['approval_id'],
    approved_by='tech_lead@example.com',
    approval_notes='Security validated, tests passing, ready for production'
)

if approval['status'] == 'approved':
    # Step 9: Complete promotion
    promotion_system.complete_promotion(promo_prod['request_id'])
    
    # Step 10: Re-sign for production
    signed_prod = code_protection.tag_for_environment(
        artifacts=signed_staging,
        target_environment='prod',
        promotion_metadata={
            'approved_by': 'tech_lead@example.com',
            'promotion_id': promo_prod['request_id']
        }
    )
    
    # Step 11: Record usage
    licensing.record_usage(
        license_key=license_key,
        usage_type='production_deployment',
        metadata={'project': 'my-app'}
    )
    
    print("✅ Deployed to production!")

Error Handling

Common Scenarios

1. Tampering Detected

validation = code_protection.validate_artifact(artifact)
if validation['tampering_detected']:
    # BLOCK DEPLOYMENT
    raise Exception(f"⚠️ Code tampering detected: {validation['reason']}")

2. Skipping Environments

result = promotion_system.create_promotion_request(
    from_environment='dev',
    to_environment='prod',  # Skips staging
    ...
)
if not result['success']:
    # BLOCK PROMOTION
    print(f"❌ {result['reason']}")
    print(f"Next step: Promote to {result['next_environment']}")

3. License Expired

validation = licensing.validate_license(license_key)
if not validation['is_valid'] and validation.get('expired'):
    # BLOCK ALL OPERATIONS
    print(f"⚠️ License expired: {validation['reason']}")
    print("Please renew your subscription")

4. Usage Limit Exceeded

usage = licensing.check_usage_limits(license_key)
if not usage['within_limits']:
    # BLOCK NEW PROJECTS
    print(f"⚠️ Monthly limit reached")
    print(f"Projects used: {usage['usage']['projects_this_month']}")
    print("Upgrade your plan to continue")

Monitoring & Compliance

Statistics

All systems provide statistics for monitoring:

# Code protection stats
stats = code_protection.get_statistics()
print(f"Artifacts signed: {stats['artifacts_signed']}")
print(f"Tampering detected: {stats['tampering_detected']}")

# Promotion stats
stats = promotion_system.get_statistics()
print(f"Promotions completed: {stats['promotions_completed']}")
print(f"Direct prod blocked: {stats['direct_prod_blocked']}")

# HITL stats
stats = hitl_system.get_statistics()
print(f"Approval rate: {stats['approval_rate']}%")
print(f"Pending reviews: {stats['pending_reviews']}")

# Licensing stats
stats = licensing.get_statistics()
print(f"Licenses validated: {stats['licenses_validated']}")
print(f"Feature blocks: {stats['feature_blocks']}")

Audit Reports

Generate compliance reports:

# Promotion audit
history = promotion_system.get_promotion_history(limit=100)
report = {
    'total_promotions': len(history),
    'by_environment': {},
    'by_status': {}
}

for promo in history:
    env_key = f"{promo['from_environment']}{promo['to_environment']}"
    report['by_environment'][env_key] = report['by_environment'].get(env_key, 0) + 1
    report['by_status'][promo['status']] = report['by_status'].get(promo['status'], 0) + 1

# HITL audit
audit_trail = hitl_system.get_audit_trail(limit=500)
report = {
    'total_approvals': len([a for a in audit_trail if a['action'] == 'approval']),
    'total_rejections': len([a for a in audit_trail if a['action'] == 'rejection']),
    'approvers': list(set(a['actor'] for a in audit_trail if a['action'] == 'approval'))
}

Best Practices

For Developers

  1. Never modify generated code directly
    • Use 8’s refinement workflow instead
    • Modifications break cryptographic signatures
  2. Follow promotion workflow
    • Always test in dev before staging
    • Always test in staging before production
  3. Respect license limits
    • Monitor monthly usage
    • Upgrade when approaching limits

For Reviewers

  1. Review security assessment before approval
    • Check risk level (CRITICAL/HIGH/MEDIUM/LOW)
    • Verify security controls are implemented
  2. Test in staging before approving production
    • Run integration tests
    • Verify deployment scripts
  3. Document rejection reasons
    • List specific blocking issues
    • Provide remediation guidance

For Administrators

  1. Configure approval policies
    • Define required approvers per environment
    • Set reviewer access controls
  2. Monitor compliance
    • Review audit trails regularly
    • Track tampering attempts
  3. Manage licenses
    • Issue appropriate tier licenses
    • Monitor usage and renewals

Troubleshooting

Q: Code protection header shows in final output

A: Headers are comment-based and don’t affect execution. For production, headers serve as legal protection.

Q: Can I manually edit 8-generated code?

A: No. Use 8’s refinement workflow. Manual edits break signatures and block deployment.

Q: How do I bypass approval for hotfixes?

A: You can’t. This is by design. Emergency hotfixes must follow the same governance to maintain audit trail.

Q: What if my license expires mid-project?

A: Existing projects remain accessible but no new projects or production deployments until renewal.

Q: Can I rollback production to staging code?

A: No. Use promotion system’s rollback feature which creates a new promotion request for downgrade.


Summary

The Code Governance System provides:

Code Immutability - Cryptographic signing prevents tampering
Environment Control - Enforced dev → staging → prod progression
Human Oversight - Required approvals for production
License Compliance - Feature and usage control by tier
Complete Audit Trail - Full compliance documentation
Statistical Monitoring - Real-time governance metrics

Result: Enterprise-grade code governance that ensures only validated, approved, and licensed code reaches production.


Status: Production-ready governance system 🔒
Last Updated: December 5, 2025
Version: 1.0