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.
┌─────────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────────┘
Prevents unauthorized modification of 8-generated code and enforces immutability.
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)
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
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."
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
CodeProtectionAgent
sign_artifact(content, artifact_type, environment, metadata) - Sign code artifactvalidate_artifact(signed_artifact) - Check for tamperingcheck_environment_compatibility(artifact_env, target_env) - Verify deployment eligibilitydetect_modifications(original, current) - Detailed diff analysistag_for_environment(artifacts, target_env, metadata) - Re-sign for promotionEnforces proper environment progression and prevents unauthorized production deployments.
Development → Staging → Production
↓ ↓ ↓
dev staging prod
(auto) (auto) (approval)
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
# }
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"
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']}")
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']}")
EnvironmentPromotion
can_promote(from_env, to_env, artifacts) - Check promotion eligibilitycreate_promotion_request(project_id, from_env, to_env, artifacts, user) - Request promotionapprove_promotion(request_id, approver, notes) - Approve promotionreject_promotion(request_id, rejector, reason) - Reject promotioncomplete_promotion(request_id) - Mark as completedget_pending_approvals(to_environment) - Get pending requestsget_promotion_history(project_id, limit) - View historyblock_direct_production_deployment(artifacts) - Check for violationsRequires explicit human approval before any code reaches production environment.
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)."
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"
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"
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'}
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']}")
| 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 |
HITLApprovalSystem
create_approval_request(promotion_id, project_id, env, artifacts, user) - Request approvalapprove(approval_id, approver, notes, artifacts) - Approve deploymentreject(approval_id, rejector, reason, issues) - Reject deploymentget_pending_approvals(reviewer, project_id) - View pendingget_approval_history(project_id, limit) - View historyget_audit_trail(approval_id, limit) - View audit logEnsures users respect license terms and controls access to features based on subscription tier.
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']}")
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"
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']}")
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")
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")
LicensingControl
validate_license(license_key) - Validate and get license detailscheck_feature_access(license_key, feature) - Check feature availabilitycheck_usage_limits(license_key) - Get current usage vs limitsrecord_usage(license_key, usage_type, metadata) - Track usage eventcan_deploy_to_environment(license_key, environment) - Check env accessgenerate_license_key(tier, user, org, duration) - Generate new license (admin)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!")
validation = code_protection.validate_artifact(artifact)
if validation['tampering_detected']:
# BLOCK DEPLOYMENT
raise Exception(f"⚠️ Code tampering detected: {validation['reason']}")
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']}")
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")
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")
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']}")
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'))
}
A: Headers are comment-based and don’t affect execution. For production, headers serve as legal protection.
A: No. Use 8’s refinement workflow. Manual edits break signatures and block deployment.
A: You can’t. This is by design. Emergency hotfixes must follow the same governance to maintain audit trail.
A: Existing projects remain accessible but no new projects or production deployments until renewal.
A: No. Use promotion system’s rollback feature which creates a new promotion request for downgrade.
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