#!/usr/bin/env python3
"""
Feature Lifecycle Governance Engine
====================================
Tracks feature lifecycle stages: INCEPTION, EXPERIMENTATION, GA, DEPRECATION, SUNSET.
Manages artifacts (e.g., docs, PRs, tickets) per stage.
Enforces governance rules for transitions (e.g., cannot skip stages, require artifacts).
Built by Sherlock @ Trailblazer Labs. Observe the evidence, enforce the rules.
Usage:
engine = FeatureLifecycleEngine(db_path='features.db')
engine.create_feature('New Login Flow')
engine.add_artifact('New Login Flow', 'INCEPTION', 'PR-123: Initial spec')
engine.transition_stage('New Login Flow', 'INCEPTION', 'EXPERIMENTATION')
engine.get_feature_status('New Login Flow')
"""
import sqlite3
import json
import enum
import logging
from datetime import datetime
from typing import List, Dict, Optional, Any
from dataclasses import dataclass, asdict
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class LifecycleStage(enum.Enum):
"""Feature lifecycle stages."""
INCEPTION = "INCEPTION" # Idea/spec documented
EXPERIMENTATION = "EXPERIMENTATION" # PoC/MVP testing
GA = "GA" # General Availability
DEPRECATION = "DEPRECATION" # Announced end-of-life
SUNSET = "SUNSET" # Fully removed
@dataclass
class Artifact:
"""Represents an artifact tied to a stage (e.g., doc, PR, ticket)."""
id: str
type: str # e.g., 'PR', 'DOC', 'TICKET'
description: str
url: Optional[str] = None
created_at: str = None
def __post_init__(self):
if self.created_at is None:
self.created_at = datetime.utcnow().isoformat()
class GovernanceRuleViolation(Exception):
"""Raised when a lifecycle transition violates governance rules."""
pass
class FeatureLifecycleEngine:
"""
Core engine for governing feature lifecycles.
Uses SQLite for persistence.
"""
TRANSITION_RULES = {
LifecycleStage.INCEPTION: [LifecycleStage.EXPERIMENTATION],
LifecycleStage.EXPERIMENTATION: [LifecycleStage.GA],
LifecycleStage.GA: [LifecycleStage.DEPRECATION],
LifecycleStage.DEPRECATION: [LifecycleStage.SUNSET],
LifecycleStage.SUNSET: [], # Terminal state
}
MIN_ARTIFACTS_PER_STAGE = {
LifecycleStage.INCEPTION: 1,
LifecycleStage.EXPERIMENTATION: 2, # e.g., PoC code + metrics
LifecycleStage.GA: 1, # Release notes
LifecycleStage.DEPRECATION: 1, # Deprecation notice
LifecycleStage.SUNSET: 0, # Cleanup confirmation optional
}
def __init__(self, db_path: str = ":memory:"):
self.db_path = db_path
self._init_db()
logger.info(f"FeatureLifecycleEngine initialized with DB: {db_path}")
def _init_db(self):
"""Initialize SQLite schema."""
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS features (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
current_stage TEXT NOT NULL,
history TEXT NOT NULL, -- JSON list of (stage, timestamp)
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS artifacts (
id TEXT PRIMARY KEY,
feature_name TEXT NOT NULL,
stage TEXT NOT NULL,
type TEXT NOT NULL,
description TEXT NOT NULL,
url TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY (feature_name) REFERENCES features (name)
)
""")
conn.commit()
def create_feature(self, name: str) -> str:
"""Incept a new feature."""
now = datetime.utcnow().isoformat()
with sqlite3.connect(self.db_path) as conn:
try:
conn.execute(
"INSERT INTO features (name, current_stage, history, created_at) VALUES (?, ?, ?, ?)",
(name, LifecycleStage.INCEPTION.value, json.dumps([{"stage": LifecycleStage.INCEPTION.value, "timestamp": now}]), now)
)
conn.commit()
logger.info(f"Feature '{name}' incepted at {now}")
return name
except sqlite3.IntegrityError:
raise ValueError(f"Feature '{name}' already exists")
def add_artifact(self, feature_name: str, stage: str, artifact: Artifact):
"""Add an artifact to a specific stage."""
self._validate_feature_exists(feature_name)
self._validate_stage_accessible(feature_name, stage)
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"INSERT INTO artifacts (id, feature_name, stage, type, description, url, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(artifact.id, feature_name, stage, artifact.type, artifact.description, artifact.url, artifact.created_at)
)
conn.commit()
logger.info(f"Artifact '{artifact.id}' added to '{feature_name}' at stage '{stage}'")
def transition_stage(self, feature_name: str, from_stage: str, to_stage: str):
"""Transition feature to new stage, enforcing governance."""
self._validate_feature_exists(feature_name)
current_stage = self._get_current_stage(feature_name)
if current_stage != from_stage:
raise GovernanceRuleViolation(f"Current stage is '{current_stage}', not '{from_stage}'")
if to_stage not in self.TRANSITION_RULES[current_stage]:
raise GovernanceRuleViolation(f"Invalid transition: {current_stage.value} -> {to_stage}")
# Check min artifacts
artifacts_count = self._count_artifacts(feature_name, from_stage)
min_required = self.MIN_ARTIFACTS_PER_STAGE[current_stage]
if artifacts_count < min_required:
raise GovernanceRuleViolation(
f"Insufficient artifacts in '{from_stage}': {artifacts_count}/{min_required}"
)
now = datetime.utcnow().isoformat()
history = self._get_history(feature_name)
history.append({"stage": to_stage, "timestamp": now})
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"UPDATE features SET current_stage = ?, history = ? WHERE name = ?",
(to_stage, json.dumps(history), feature_name)
)
conn.commit()
logger.info(f"Feature '{feature_name}' transitioned: {from_stage} -> {to_stage}")
def get_feature_status(self, feature_name: str) -> Dict[str, Any]:
"""Get full status including artifacts."""
self._validate_feature_exists(feature_name)
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("SELECT * FROM features WHERE name = ?", (feature_name,))
row = cursor.fetchone()
if not row:
raise ValueError(f"Feature '{feature_name}' not found")
feature_data = {
"id": row[0],
"name": row[1],
"current_stage": row[2],
"history": json.loads(row[3]),
"created_at": row[4],
}
artifacts = conn.execute(
"SELECT id, type, description, url, created_at FROM artifacts WHERE feature_name = ? ORDER BY created_at",
(feature_name,)
).fetchall()
feature_data["artifacts"] = [
Artifact(id=r[0], type=r[1], description=r[2], url=r[3], created_at=r[4])
for r in artifacts
]
return feature_data
def list_all_features(self) -> List[Dict[str, str]]:
"""List all features with current stage."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("SELECT name, current_stage FROM features ORDER BY created_at DESC")
return [{"name": r[0], "stage": r[1]} for r in cursor.fetchall()]
def _validate_feature_exists(self, feature_name: str):
with sqlite3.connect(self.db_path) as conn:
if not conn.execute("SELECT 1 FROM features WHERE name = ?", (feature_name,)).fetchone():
raise ValueError(f"Feature '{feature_name}' does not exist")
def _get_current_stage(self, feature_name: str) -> LifecycleStage:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("SELECT current_stage FROM features WHERE name = ?", (feature_name,))
return LifecycleStage(cursor.fetchone()[0])
def _get_history(self, feature_name: str) -> List[Dict[str, str]]:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("SELECT history FROM features WHERE name = ?", (feature_name,))
return json.loads(cursor.fetchone()[0])
def _count_artifacts(self, feature_name: str, stage: str) -> int:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute(
"SELECT COUNT(*) FROM artifacts WHERE feature_name = ? AND stage = ?",
(feature_name, stage)
)
return cursor.fetchone()[0]
def _validate_stage_accessible(self, feature_name: str, stage: str):
current = self._get_current_stage(feature_name)
if stage not in [current.value] + [t.value for t in self.TRANSITION_RULES[current]]:
raise ValueError(f"Cannot add artifacts to '{stage}'; current/allowed: {current.value}")
# Demo / Usage Example
if __name__ == "__main__":
engine = FeatureLifecycleEngine(db_path='features_demo.db')
# Create feature
feature_name = "AI-Powered Search"
engine.create_feature(feature_name)
# Add inception artifacts
engine.add_artifact(
feature_name, "INCEPTION",
Artifact("spec-001", "DOC", "Feature specification v1.0", "https://docs.example.com/spec")
)
engine.add_artifact(
feature_name, "INCEPTION",
Artifact("ticket-456", "TICKET", "JIRA ENG-456: Kickoff", "https://jira.example.com/ENG-456")
)
# Transition to experimentation
engine.transition_stage(feature_name, "INCEPTION", "EXPERIMENTATION")
# Add experimentation artifacts
engine.add_artifact(
feature_name, "EXPERIMENTATION",
Artifact("poc-pr-789", "PR", "PoC implementation", "https://github.com/org/pull/789")
)
engine.add_artifact(
feature_name, "EXPERIMENTATION",
Artifact("metrics-001", "DOC", "A/B test results: 20% uplift", None)
)
# Get status
status = engine.get_feature_status(feature_name)
print("Feature Status:")
print(json.dumps(status, default=str, indent=2))
# List all
print("\nAll Features:")
print(json.dumps(engine.list_all_features(), indent=2))
print("\nEngine ready for production use. Governance enforced!")
Key Features (The Evidence)
- Persistence: SQLite-backed for scalability (extend to Postgres easily).
- Governance Rules: Strict transitions (no skipping), min artifacts enforced.
- Artifact Tracking: Per-stage, queryable, with metadata.
- Audit Trail: Full history JSON-logged.
- Error Handling: Descriptive exceptions for violations.
- Extensible: Easy to add notifications (e.g., Slack), approvals, or metrics.
- CLI-Ready: Run the script for a demo DB.
Architecture Decisions (My Deductions)
- State Machine: Enforced via
TRANSITION_RULES – prevents invalid paths.
- Artifacts as First-Class: Not just metadata; queryable independently.
- No Over-Engineering: Lightweight, zero-deps (beyond stdlib), but production-grade.
- Sherlock Touch: Logging, validation, immutable history.
To deploy: Integrate with GitHub Actions, Jira webhooks, or as a microservice. Need custom rules? Fork TRANSITION_RULES. Case closed – or iterate?