CODITECT UI/UX Agent Architecture
Version: 1.0
Date: January 19, 2026
Status: Design Specification
Based On: Anthropic Claude Code agent lifecycle model
Executive Summary
This document defines the architecture for CODITECT's UI/UX agent system, modeled after Anthropic's Claude Code skill lifecycle. The system transforms CODITECT from generating "AI-looking" interfaces to producing professional, enterprise-grade UI/UX through a structured agent capability layer.
Core Innovation: Event-based agent-UI protocol with explicit lifecycle phases (Discovery → Activation → Execution → Reflection) that enables:
- Consistent professional design output
- Human-in-the-loop quality gates
- Continuous improvement from user feedback
- Reusable design system enforcement
System Architecture Overview
High-Level Architecture
┌─────────────────────────────────────────────────────────────────┐
│ CODITECT Platform Layer │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌────────────────┐ ┌──────────────────┐ │
│ │ Lead Agent │──────│ UI/UX Agent │ │
│ │ (Orchestrator)│ │ (Specialist) │ │
│ └────────────────┘ └──────────────────┘ │
│ │ │ │
│ │ │ │
│ ┌──────▼────────────────────────▼──────────────────────────┐ │
│ │ Agent Capability Layer (Skills Registry) │ │
│ ├───────────────────────────────────────────────────────────┤ │
│ │ • UI/UX Skills • Design System Tools │ │
│ │ • Commands • Scripts & Hooks │ │
│ │ • Lifecycle Hooks • Quality Gates │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │ │ │
│ │ │ │
│ ┌──────▼────────────────────────▼──────────────────────────┐ │
│ │ Event-Based Protocol Layer │ │
│ ├───────────────────────────────────────────────────────────┤ │
│ │ Event Stream: skill_activation_request, │ │
│ │ tool_call, human_input_request, │ │
│ │ permission_request, quality_check │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │ │ │
│ │ │ │
│ ┌──────▼────────────────────────▼──────────────────────────┐ │
│ │ Frontend/UI Rendering Layer │ │
│ ├───────────────────────────────────────────────────────────┤ │
│ │ • Generated UI Code • Quality Indicators │ │
│ │ • Design Preview • Approval Interfaces │ │
│ │ • HITL Controls • Metrics Dashboard │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
External Integrations:
├─ Customer Design Systems (Brand Assets, Style Guides)
├─ Quality Validation Services (Accessibility, Performance)
└─ Design Tool Exports (Penpot, Figma APIs)
Core Lifecycle Model
Phase 1: Discovery
Purpose: Make UI/UX capabilities discoverable without loading full instructions
Implementation:
skill_registry:
storage: /mnt/H.P.003-SKILLS/public/ui_ux/
metadata_only_load: true # Keep context lean
H.P.003-SKILLS:
- name: "ui_ux_agent_skill"
description: "Professional UI/UX design with header consolidation, navigation optimization"
tags: ["design", "frontend", "ui", "ux", "enterprise"]
visibility: "auto-discovered"
- name: "header_consolidation"
description: "Compress multi-level headers into single navigation bar"
tags: ["design", "navigation", "optimization"]
visibility: "user-invocable"
- name: "navigation_frequency"
description: "Optimize navigation hierarchy based on access patterns"
tags: ["ux", "navigation", "information-architecture"]
visibility: "auto-discovered"
- name: "design_system_generator"
description: "Generate brand-aligned design systems from customer assets"
tags: ["branding", "design-system", "consistency"]
visibility: "user-invocable"
- name: "quality_validation"
description: "Validate UI against accessibility and design standards"
tags: ["qa", "accessibility", "standards"]
visibility: "auto-discovered"
UX Affordances:
// Contextual skill suggestions
interface SkillSuggestion {
skill_name: string;
reason: string;
confidence: number;
auto_apply?: boolean;
}
// Example: When generating dashboard UI
const suggestions: SkillSuggestion[] = [
{
skill_name: "ui_ux_agent_skill",
reason: "Dashboard detected - apply professional layout patterns",
confidence: 0.95,
auto_apply: true
},
{
skill_name: "navigation_frequency",
reason: "Multiple navigation sections found - optimize hierarchy",
confidence: 0.88,
auto_apply: true
}
];
// Slash-command palette
const H.P.002-COMMANDS = [
{ trigger: "/optimize-ui", skill: "ui_ux_agent_skill" },
{ trigger: "/compress-headers", skill: "header_consolidation" },
{ trigger: "/design-system", skill: "design_system_generator" }
];
Discovery Flow:
Phase 2: Activation & Permissions
Purpose: Load full skill instructions only after user approval
Implementation:
interface SkillActivationRequest {
event_type: "skill_activation_request";
skill_name: string;
rationale: string;
scope: ActivationScope;
permissions_required: Permission[];
estimated_impact: ImpactEstimate;
}
interface ActivationScope {
scope_type: "session" | "file" | "folder" | "project" | "customer";
target: string;
duration?: "one-time" | "persistent";
}
interface Permission {
permission_type: string;
resource: string;
justification: string;
risk_level: "low" | "medium" | "high";
}
interface ImpactEstimate {
files_affected: number;
code_changes: number;
style_changes: number;
breaking_changes: boolean;
}
// Example activation request
const activationRequest: SkillActivationRequest = {
event_type: "skill_activation_request",
skill_name: "ui_ux_agent_skill",
rationale: "Dashboard UI requires professional header consolidation and navigation optimization to meet enterprise design standards",
scope: {
scope_type: "project",
target: "avivate-financial-dashboard",
duration: "persistent"
},
permissions_required: [
{
permission_type: "file_write",
resource: "src/components/**/*.tsx",
justification: "Rewrite UI components to apply design patterns",
risk_level: "medium"
},
{
permission_type: "style_modification",
resource: "src/styles/**/*.css",
justification: "Apply design system tokens and consolidated styles",
risk_level: "low"
}
],
estimated_impact: {
files_affected: 12,
code_changes: 350,
style_changes: 120,
breaking_changes: false
}
};
UX Prompt Example:
┌─────────────────────────────────────────────────────────────┐
│ 🎨 Skill Activation Request │
├─────────────────────────────────────────────────────────────┤
│ │
│ Skill: UI/UX Agent (Professional Design) │
│ │
│ Why: Dashboard UI requires professional header │
│ consolidation and navigation optimization to meet │
│ enterprise design standards │
│ │
│ Scope: Entire project (avivate-financial-dashboard) │
│ │
│ Permissions Required: │
│ ⚠️ Modify UI components (12 files, ~350 changes) │
│ ✓ Update styles (120 changes) │
│ │
│ Impact: Medium - Will restructure navigation and headers │
│ No breaking changes expected │
│ │
│ ┌──────────┐ ┌──────────┐ ┌────────────────────┐ │
│ │ Approve │ │ Deny │ │ Limit to Dashboard │ │
│ └──────────┘ └──────────┘ └────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Approval Workflow:
class SkillActivationManager:
"""Manages skill activation and permission negotiation."""
def __init__(self):
self.pending_activations: Dict[str, SkillActivationRequest] = {}
self.active_H.P.003-SKILLS: Dict[str, ActivatedSkill] = {}
self.user_preferences: ActivationPreferences = None
async def request_activation(
self,
skill_name: str,
context: ExecutionContext
) -> ActivationResponse:
"""Request skill activation with context-aware permissions."""
# Build activation request
request = SkillActivationRequest(
skill_name=skill_name,
rationale=self.generate_rationale(skill_name, context),
scope=self.determine_scope(context),
permissions_required=self.calculate_permissions(skill_name),
estimated_impact=self.estimate_impact(skill_name, context)
)
# Check user preferences for auto-approval
if self.should_auto_approve(request):
return await self.activate_skill(skill_name, request.scope)
# Request human approval
self.pending_activations[request.id] = request
await self.emit_event({
"event_type": "skill_activation_request",
"request": request
})
# Wait for user decision
response = await self.wait_for_approval(request.id)
if response.approved:
return await self.activate_skill(
skill_name,
response.approved_scope or request.scope
)
else:
return ActivationResponse(
approved=False,
reason=response.reason
)
async def activate_skill(
self,
skill_name: str,
scope: ActivationScope
) -> ActivationResponse:
"""Activate skill and load full instructions."""
# Load full skill from registry
skill = await self.skill_registry.load_full_skill(skill_name)
# Apply scope constraints
skill.apply_scope(scope)
# Register activated skill
self.active_H.P.003-SKILLS[skill_name] = ActivatedSkill(
skill=skill,
scope=scope,
activated_at=time.time()
)
# Load associated H.P.005-HOOKS
await self.hook_manager.register_H.P.005-HOOKS(skill.H.P.005-HOOKS, scope)
return ActivationResponse(
approved=True,
skill=skill,
scope=scope
)
Phase 3: Execution & Monitoring
Purpose: Execute with visible intermediate steps and quality gates
Implementation:
// Event stream for execution monitoring
interface ExecutionEvent {
event_type:
| "tool_call"
| "tool_result"
| "hook_triggered"
| "quality_check"
| "human_input_request"
| "skill_step_complete"
| "skill_complete";
timestamp: number;
skill_name?: string;
details: Record<string, any>;
}
// Tool execution with streaming
interface ToolExecution {
tool_name: string;
input: Record<string, any>;
streaming: boolean;
// Hook points
pre_execution_hook?: string;
post_execution_hook?: string;
// Quality gates
quality_checks?: QualityCheck[];
}
// Example execution flow
class UIUXExecutor {
async execute_ui_generation(
requirements: UIRequirements,
active_H.P.003-SKILLS: ActivatedSkill[]
): Promise<UIOutput> {
// Phase 1: Header consolidation
await this.emit_event({
event_type: "skill_step_complete",
skill_name: "header_consolidation",
details: { step: "analyzing_current_headers" }
});
const header_analysis = await this.tools.analyze_headers(
requirements.current_ui
);
await this.emit_event({
event_type: "tool_result",
details: {
tool: "analyze_headers",
result: header_analysis,
finding: `Found ${header_analysis.header_count} nested headers`
}
});
// Trigger quality check
const quality_result = await this.quality_gates.check(
"header_count",
header_analysis
);
await this.emit_event({
event_type: "quality_check",
details: {
check: "header_count",
passed: quality_result.passed,
threshold: quality_result.threshold,
actual: quality_result.actual
}
});
// Phase 2: Navigation optimization
await this.emit_event({
event_type: "skill_step_complete",
skill_name: "navigation_frequency",
details: { step: "calculating_access_patterns" }
});
const navigation_plan = await this.tools.optimize_navigation(
requirements.sections,
requirements.user_personas
);
// Human-in-loop checkpoint for critical changes
if (navigation_plan.requires_approval) {
const approval = await this.request_human_input({
event_type: "human_input_request",
reason: "Navigation restructuring will change user flow",
options: ["Approve", "Modify", "Skip"],
details: navigation_plan
});
if (approval.response !== "Approve") {
navigation_plan = await this.modify_navigation_plan(
navigation_plan,
approval.feedback
);
}
}
// Phase 3: Design system application
const design_system = await this.load_design_system(
requirements.customer_id
);
const styled_ui = await this.tools.apply_design_system(
base_ui,
design_system
);
// Final quality validation
const final_validation = await this.quality_gates.validate_all(
styled_ui
);
await this.emit_event({
event_type: "skill_complete",
skill_name: "ui_ux_agent_skill",
details: {
quality_score: final_validation.score,
improvements: final_validation.improvements,
files_generated: styled_ui.files.length
}
});
return styled_ui;
}
}
Visual Monitoring UI:
┌─────────────────────────────────────────────────────────────┐
│ 🎨 UI/UX Generation Progress │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✓ Header Consolidation [2.3s] │
│ ├─ Analyzed 4 nested headers │
│ ├─ Compressed to 1 navigation bar │
│ └─ ✓ Quality: Header height < 100px │
│ │
│ ⚙️ Navigation Optimization [in progress]│
│ ├─ Calculated access frequency patterns │
│ ├─ Projects: Daily (landing page) │
│ ├─ Settings: Monthly (nested) │
│ └─ ⏸️ Awaiting approval for restructuring │
│ │
│ ⏳ Design System Application [pending] │
│ │
│ ⏳ Quality Validation [pending] │
│ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 🔍 Quality Checks │
├─────────────────────────────────────────────────────────────┤
│ ✓ Header count: 1 (target: ≤1) │
│ ✓ Navigation depth: 2 (target: ≤2) │
│ ✓ Accessibility: WCAG AA (target: AA) │
│ ⚠️ Visual complexity: 3.2 (target: ≤3.0) │
└─────────────────────────────────────────────────────────────┘
Phase 4: Reflection & Learning
Purpose: Capture improvements and update H.P.003-SKILLS based on feedback
Implementation:
interface SkillReflection {
skill_name: string;
execution_id: string;
outcomes: ExecutionOutcome;
user_feedback: UserFeedback;
proposed_updates: SkillUpdate[];
}
interface ExecutionOutcome {
success: boolean;
quality_score: number;
user_satisfaction: number;
issues_encountered: Issue[];
improvements_identified: Improvement[];
}
interface UserFeedback {
rating: number; // 1-10
comments: string;
specific_likes: string[];
specific_dislikes: string[];
correction_applied: boolean;
}
interface SkillUpdate {
update_type: "rule_addition" | "rule_modification" | "example_addition";
section: string;
current_content: string;
proposed_content: string;
rationale: string;
confidence: number;
}
class SkillLearningEngine {
async reflect_on_execution(
skill_name: string,
execution_context: ExecutionContext,
user_feedback: UserFeedback
): Promise<SkillReflection> {
// Analyze what worked and what didn't
const analysis = await this.analyze_execution(
execution_context,
user_feedback
);
// Generate proposed updates
const proposed_updates = await this.generate_skill_updates(
skill_name,
analysis
);
// Create reflection
const reflection: SkillReflection = {
skill_name,
execution_id: execution_context.id,
outcomes: analysis.outcomes,
user_feedback,
proposed_updates
};
// If high-confidence updates, propose to user
const high_confidence_updates = proposed_updates.filter(
u => u.confidence > 0.85
);
if (high_confidence_updates.length > 0) {
await this.propose_skill_updates(
skill_name,
high_confidence_updates
);
}
// Store reflection for future learning
await this.reflection_store.save(reflection);
return reflection;
}
async propose_skill_updates(
skill_name: string,
updates: SkillUpdate[]
): Promise<void> {
await this.emit_event({
event_type: "skill_update_proposal",
skill_name,
updates: updates.map(u => ({
section: u.section,
change_preview: this.generate_diff(
u.current_content,
u.proposed_content
),
rationale: u.rationale,
confidence: u.confidence
}))
});
}
}
User Feedback Collection:
┌─────────────────────────────────────────────────────────────┐
│ 📊 Rate This UI Generation │
├─────────────────────────────────────────────────────────────┤
│ │
│ Overall Quality: ⭐⭐⭐⭐⭐⭐⭐⭐⚪⚪ (8/10) │
│ │
│ What worked well? │
│ ☑ Header consolidation │
│ ☑ Navigation organization │
│ ☐ Visual design │
│ ☑ Accessibility │
│ │
│ What needs improvement? │
│ ☐ Color contrast too low │
│ ☑ Spacing inconsistent in cards │
│ ☐ Icons too large │
│ │
│ Additional comments: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ The header compression worked great, but the card │ │
│ │ spacing feels uneven. Some cards have 16px padding │ │
│ │ while others have 24px. │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ [ Submit Feedback ] │
│ │
└─────────────────────────────────────────────────────────────┘
Skill Update Proposal UI:
┌─────────────────────────────────────────────────────────────┐
│ 🔄 Proposed Skill Update │
├─────────────────────────────────────────────────────────────┤
│ │
│ Skill: ui_ux_agent_skill │
│ Section: Card Component Spacing │
│ Confidence: 92% │
│ │
│ Based on 3 instances of user feedback about inconsistent │
│ card spacing, propose adding this rule: │
│ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ - card: │ │
│ │ padding: 24 │ │
│ │ + padding: 24 # Standardize to 24px │ │
│ │ + enforce_consistency: true # Validate all cards │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ This will ensure all card components use consistent 24px │
│ padding and automatically flag violations during QA. │
│ │
│ ┌──────────┐ ┌──────────┐ ┌────────────┐ │
│ │ Accept │ │ Reject │ │ Preview │ │
│ └──────────┘ └──────────┘ └────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Skills, Commands, Tools, Scripts, Hooks
Skill Structure
skill_definition:
metadata:
name: "ui_ux_agent_skill"
version: "1.0.0"
description: "Professional UI/UX design patterns"
author: "CODITECT"
tags: ["design", "ui", "ux", "enterprise"]
visibility: "auto-discovered"
instructions:
file: "SKILL.md"
sections:
- header_consolidation
- navigation_optimization
- visual_design_principles
- content_prioritization
- design_system_application
H.P.005-HOOKS:
pre_generation:
- validate_requirements
- load_design_system
post_generation:
- quality_validation
- accessibility_check
on_error:
- rollback_changes
- notify_user
H.P.004-SCRIPTS:
- name: "generate_design_system"
path: "H.P.004-SCRIPTS/design_system_generator.py"
parameters:
- logo_path
- brand_colors
- industry
- name: "validate_accessibility"
path: "H.P.004-SCRIPTS/wcag_validator.js"
parameters:
- html_content
- wcag_level
tools:
- name: "analyze_headers"
type: "analysis"
input_schema: { ui_code: "string" }
output_schema: { header_count: "int", structure: "object" }
- name: "optimize_navigation"
type: "transformation"
input_schema: { sections: "array", personas: "array" }
output_schema: { navigation_tree: "object", priority_map: "object" }
- name: "apply_design_system"
type: "generation"
input_schema: { base_ui: "string", design_system: "object" }
output_schema: { styled_ui: "string", applied_tokens: "array" }
quality_gates:
- name: "header_count"
threshold: 1
severity: "error"
- name: "navigation_depth"
threshold: 2
severity: "warning"
- name: "wcag_aa_compliance"
threshold: "pass"
severity: "error"
- name: "visual_complexity"
threshold: 3.0
severity: "warning"
Commands (User-Invocable)
// Command registry
const H.P.002-COMMANDS: Command[] = [
{
id: "optimize-ui",
name: "Optimize UI/UX",
description: "Apply professional design patterns to current UI",
category: "design",
shortcut: "Cmd+Shift+U",
skill: "ui_ux_agent_skill",
parameters: []
},
{
id: "compress-headers",
name: "Compress Headers",
description: "Consolidate multiple headers into single navigation",
category: "design",
shortcut: "Cmd+Shift+H",
skill: "header_consolidation",
parameters: []
},
{
id: "optimize-navigation",
name: "Optimize Navigation",
description: "Reorganize navigation based on access frequency",
category: "ux",
skill: "navigation_frequency",
parameters: [
{
name: "user_persona",
type: "select",
options: ["manager", "developer", "end_user"],
default: "manager"
}
]
},
{
id: "generate-design-system",
name: "Generate Design System",
description: "Create brand-aligned design system from assets",
category: "branding",
skill: "design_system_generator",
parameters: [
{
name: "logo_file",
type: "file",
accept: ".svg,.png"
},
{
name: "brand_color",
type: "color"
}
]
},
{
id: "validate-quality",
name: "Validate UI Quality",
description: "Run all quality checks on current UI",
category: "qa",
skill: "quality_validation",
parameters: []
}
];
// Command palette implementation
class CommandPalette {
private H.P.002-COMMANDS: Command[];
private fuzzy_matcher: FuzzyMatcher;
search(query: string): Command[] {
return this.fuzzy_matcher.match(query, this.H.P.002-COMMANDS, {
keys: ["name", "description", "tags"],
threshold: 0.6
});
}
async execute(command_id: string, parameters: Record<string, any>): Promise<void> {
const command = this.H.P.002-COMMANDS.find(c => c.id === command_id);
if (!command) {
throw new Error(`Command ${command_id} not found`);
}
// Request skill activation
const activation = await this.skill_manager.request_activation(
command.skill,
{ trigger: "user_command", parameters }
);
if (activation.approved) {
await this.execute_skill(command.skill, parameters);
}
}
}
Tools & Programmatic Tool Use
from typing import Protocol, Dict, Any, List
from dataclasses import dataclass
class Tool(Protocol):
"""Base protocol for all UI/UX tools."""
name: str
description: str
input_schema: Dict[str, Any]
output_schema: Dict[str, Any]
async def execute(self, **kwargs) -> Dict[str, Any]:
"""Execute the tool with given parameters."""
...
@dataclass
class ToolExecution:
"""Tool execution context with error handling."""
tool: Tool
input: Dict[str, Any]
dry_run: bool = False
preview: bool = False
async def execute(self) -> Dict[str, Any]:
"""Execute with safety checks."""
# Validate input
if not self.validate_input(self.input):
raise ValueError("Invalid input for tool")
# Dry run mode
if self.dry_run:
return await self.tool.simulate(**self.input)
# Preview mode
if self.preview:
return await self.tool.preview(**self.input)
# Actual execution
try:
result = await self.tool.execute(**self.input)
return result
except Exception as e:
# Error surface
return {
"success": False,
"error": str(e),
"recovery_suggestions": self.generate_recovery_suggestions(e)
}
# Example: Header analysis tool
class HeaderAnalysisTool:
"""Analyzes header structure in UI code."""
name = "analyze_headers"
description = "Analyze nested header structure and identify consolidation opportunities"
input_schema = {
"ui_code": {"type": "string", "required": True},
"framework": {"type": "string", "enum": ["react", "vue", "html"], "default": "react"}
}
output_schema = {
"header_count": {"type": "integer"},
"nesting_depth": {"type": "integer"},
"structure": {"type": "object"},
"consolidation_opportunities": {"type": "array"}
}
async def execute(self, ui_code: str, framework: str = "react") -> Dict[str, Any]:
"""Analyze header structure."""
# Parse UI code
ast = self.parse_ui_code(ui_code, framework)
# Find all header elements
headers = self.extract_headers(ast)
# Analyze nesting
structure = self.build_header_tree(headers)
# Identify consolidation opportunities
opportunities = self.find_consolidation_opportunities(structure)
return {
"header_count": len(headers),
"nesting_depth": self.calculate_depth(structure),
"structure": structure,
"consolidation_opportunities": opportunities,
"recommendation": self.generate_recommendation(opportunities)
}
def find_consolidation_opportunities(self, structure: Dict) -> List[Dict]:
"""Identify where headers can be consolidated."""
opportunities = []
# Check for multiple top-level headers
if structure.get("top_level_count", 0) > 1:
opportunities.append({
"type": "multiple_top_headers",
"current": structure["top_level_count"],
"target": 1,
"action": "Merge into single navigation bar"
})
# Check for redundant breadcrumb + page title
if structure.get("has_breadcrumb") and structure.get("has_page_title"):
opportunities.append({
"type": "redundant_breadcrumb",
"action": "Remove breadcrumb or integrate into top nav"
})
# Check for excessive nesting
if structure.get("max_depth", 0) > 2:
opportunities.append({
"type": "excessive_nesting",
"current_depth": structure["max_depth"],
"target_depth": 2,
"action": "Flatten header hierarchy"
})
return opportunities
# Tool chaining
class ToolChain:
"""Chain multiple tools together."""
def __init__(self):
self.tools: Dict[str, Tool] = {}
self.execution_graph: Dict[str, List[str]] = {}
def add_tool(self, tool: Tool):
"""Register a tool."""
self.tools[tool.name] = tool
def define_chain(self, chain: List[str]):
"""Define a sequence of tools to execute."""
for i in range(len(chain) - 1):
current = chain[i]
next_tool = chain[i + 1]
if current not in self.execution_graph:
self.execution_graph[current] = []
self.execution_graph[current].append(next_tool)
async def execute_chain(
self,
start_tool: str,
initial_input: Dict[str, Any]
) -> Dict[str, Any]:
"""Execute a chain of tools."""
result = initial_input
current = start_tool
while current:
tool = self.tools[current]
result = await tool.execute(**result)
# Get next tool in chain
next_tools = self.execution_graph.get(current, [])
current = next_tools[0] if next_tools else None
return result
# Example chain: Complete UI optimization
ui_optimization_chain = [
"analyze_headers",
"consolidate_headers",
"analyze_navigation",
"optimize_navigation",
"apply_design_system",
"validate_quality"
]
Scripts & Automation
#!/bin/bash
# H.P.004-SCRIPTS/generate_design_system.sh
# Generate design system from brand assets
set -e
LOGO_PATH=$1
BRAND_COLOR=$2
INDUSTRY=${3:-"general"}
OUTPUT_DIR=${4:-"/mnt/user-data/outputs"}
echo "🎨 Generating design system..."
# Extract colors from logo
echo "📊 Analyzing logo colors..."
python3 /home/claude/H.P.004-SCRIPTS/extract_logo_colors.py \
--logo "$LOGO_PATH" \
--output "$OUTPUT_DIR/extracted_colors.json"
# Generate color palette
echo "🌈 Generating color palette..."
python3 /home/claude/H.P.004-SCRIPTS/generate_color_palette.py \
--base-color "$BRAND_COLOR" \
--extracted-colors "$OUTPUT_DIR/extracted_colors.json" \
--output "$OUTPUT_DIR/color_palette.json"
# Select typography
echo "🔤 Selecting typography..."
python3 /home/claude/H.P.004-SCRIPTS/select_typography.py \
--industry "$INDUSTRY" \
--output "$OUTPUT_DIR/typography.json"
# Generate component library
echo "🧩 Generating components..."
python3 /home/claude/H.P.004-SCRIPTS/generate_components.py \
--colors "$OUTPUT_DIR/color_palette.json" \
--typography "$OUTPUT_DIR/typography.json" \
--output "$OUTPUT_DIR/components.json"
# Compile design system
echo "📦 Compiling design system..."
python3 /home/claude/H.P.004-SCRIPTS/compile_design_system.py \
--colors "$OUTPUT_DIR/color_palette.json" \
--typography "$OUTPUT_DIR/typography.json" \
--components "$OUTPUT_DIR/components.json" \
--output "$OUTPUT_DIR/design_system.yaml"
# Validate accessibility
echo "✓ Validating accessibility..."
python3 /home/claude/H.P.004-SCRIPTS/validate_design_system.py \
--design-system "$OUTPUT_DIR/design_system.yaml" \
--wcag-level "AA"
echo "✅ Design system generated: $OUTPUT_DIR/design_system.yaml"
# H.P.004-SCRIPTS/validate_accessibility.py
# WCAG accessibility validation
from typing import Dict, List
import re
class AccessibilityValidator:
"""Validate UI against WCAG standards."""
WCAG_AA_CONTRAST = {
"normal_text": 4.5,
"large_text": 3.0,
"ui_components": 3.0
}
def validate_color_contrast(
self,
foreground: str,
background: str,
text_size: str = "normal"
) -> Dict:
"""Validate color contrast ratio."""
ratio = self.calculate_contrast_ratio(foreground, background)
if text_size == "large":
threshold = self.WCAG_AA_CONTRAST["large_text"]
else:
threshold = self.WCAG_AA_CONTRAST["normal_text"]
return {
"ratio": ratio,
"threshold": threshold,
"passed": ratio >= threshold,
"level": "AA" if ratio >= threshold else "fail"
}
def validate_ui_code(self, html_content: str) -> Dict:
"""Comprehensive UI validation."""
issues = []
# Check for missing alt text
img_tags = re.findall(r'<img[^>]*>', html_content)
for img in img_tags:
if 'alt=' not in img:
issues.append({
"type": "missing_alt_text",
"severity": "error",
"element": img
})
# Check for proper heading hierarchy
headings = re.findall(r'<h([1-6])[^>]*>', html_content)
if headings and headings[0] != '1':
issues.append({
"type": "invalid_heading_hierarchy",
"severity": "warning",
"message": "First heading should be h1"
})
# Check for form labels
inputs = re.findall(r'<input[^>]*>', html_content)
for input_tag in inputs:
if 'aria-label=' not in input_tag and 'id=' not in input_tag:
issues.append({
"type": "missing_form_label",
"severity": "error",
"element": input_tag
})
return {
"passed": len([i for i in issues if i["severity"] == "error"]) == 0,
"issues": issues,
"score": self.calculate_accessibility_score(issues)
}
Hooks (Lifecycle Integration)
// Hook types
type HookType =
| "PreToolUse"
| "PostToolUse"
| "PreSkillActivation"
| "PostSkillActivation"
| "OnError"
| "OnComplete";
interface Hook {
type: HookType;
name: string;
handler: (context: HookContext) => Promise<HookResult>;
scope: "session" | "skill" | "tool";
enabled: boolean;
}
interface HookContext {
event: string;
data: Record<string, any>;
metadata: Record<string, any>;
}
interface HookResult {
continue: boolean;
modified_data?: Record<string, any>;
messages?: string[];
}
// Hook manager
class HookManager {
private H.P.005-HOOKS: Map<HookType, Hook[]> = new Map();
register(hook: Hook): void {
if (!this.H.P.005-HOOKS.has(hook.type)) {
this.H.P.005-HOOKS.set(hook.type, []);
}
this.H.P.005-HOOKS.get(hook.type)!.push(hook);
}
async trigger(
hook_type: HookType,
context: HookContext
): Promise<HookResult> {
const H.P.005-HOOKS = this.H.P.005-HOOKS.get(hook_type) || [];
const enabled_H.P.005-HOOKS = H.P.005-HOOKS.filter(h => h.enabled);
let result: HookResult = { continue: true };
for (const hook of enabled_H.P.005-HOOKS) {
const hook_result = await hook.handler(context);
if (!hook_result.continue) {
return hook_result;
}
if (hook_result.modified_data) {
context.data = { ...context.data, ...hook_result.modified_data };
}
result.messages = [...(result.messages || []), ...(hook_result.messages || [])];
}
return result;
}
}
// Example H.P.005-HOOKS
const H.P.005-HOOKS: Hook[] = [
{
type: "PreToolUse",
name: "validate_design_system_loaded",
scope: "skill",
enabled: true,
handler: async (context) => {
// Ensure design system is loaded before applying
if (context.data.tool === "apply_design_system") {
if (!context.data.design_system) {
return {
continue: false,
messages: ["Design system not loaded. Loading customer design system..."]
};
}
}
return { continue: true };
}
},
{
type: "PostToolUse",
name: "quality_check_ui_output",
scope: "skill",
enabled: true,
handler: async (context) => {
// Automatically run quality checks after UI generation
if (context.data.tool === "generate_ui") {
const quality_result = await runQualityChecks(context.data.output);
if (!quality_result.passed) {
return {
continue: false,
messages: ["Quality checks failed. Refining output..."],
modified_data: { needs_refinement: true }
};
}
}
return { continue: true };
}
},
{
type: "OnError",
name: "rollback_on_failure",
scope: "session",
enabled: true,
handler: async (context) => {
// Rollback changes if error occurs
await rollbackChanges(context.data.session_id);
return {
continue: false,
messages: ["Error occurred. Changes rolled back."]
};
}
}
];
Event-Based Protocol (Agent ↔ UI Communication)
Protocol Definition
// Core event types
type EventType =
| "message" // Chat message
| "tool_call" // Tool invocation
| "tool_result" // Tool output
| "skill_activation_request" // Request to activate skill
| "skill_activated" // Skill activated
| "permission_request" // Permission needed
| "permission_granted" // Permission approved
| "layout_update" // UI layout change
| "human_input_request" // Need user input
| "human_input_received" // User provided input
| "action_guard" // High-risk action approval
| "memory_update" // Agent learned something
| "quality_check" // Quality validation result
| "progress_update" // Execution progress
| "error" // Error occurred
| "complete"; // Task complete
interface AgentEvent {
event_type: EventType;
event_id: string;
timestamp: number;
session_id: string;
skill_name?: string;
data: Record<string, any>;
metadata?: Record<string, any>;
}
// Event stream
interface EventStream {
subscribe(
event_type: EventType | EventType[],
handler: (event: AgentEvent) => void
): () => void;
publish(event: AgentEvent): void;
replay(session_id: string): AgentEvent[];
}
// WebSocket transport
class WebSocketEventStream implements EventStream {
private ws: WebSocket;
private handlers: Map<EventType, Set<(event: AgentEvent) => void>>;
private event_buffer: AgentEvent[] = [];
constructor(url: string) {
this.ws = new WebSocket(url);
this.handlers = new Map();
this.ws.onmessage = (msg) => {
const event: AgentEvent = JSON.parse(msg.data);
this.event_buffer.push(event);
this.dispatch(event);
};
}
subscribe(
event_type: EventType | EventType[],
handler: (event: AgentEvent) => void
): () => void {
const types = Array.isArray(event_type) ? event_type : [event_type];
types.forEach(type => {
if (!this.handlers.has(type)) {
this.handlers.set(type, new Set());
}
this.handlers.get(type)!.add(handler);
});
// Return unsubscribe function
return () => {
types.forEach(type => {
this.handlers.get(type)?.delete(handler);
});
};
}
publish(event: AgentEvent): void {
this.ws.send(JSON.stringify(event));
}
private dispatch(event: AgentEvent): void {
const handlers = this.handlers.get(event.event_type) || new Set();
handlers.forEach(handler => handler(event));
}
replay(session_id: string): AgentEvent[] {
return this.event_buffer.filter(e => e.session_id === session_id);
}
}
Frontend Integration
// React hook for event stream
function useAgentEventStream(session_id: string) {
const [events, setEvents] = useState<AgentEvent[]>([]);
const [stream] = useState(() => new WebSocketEventStream(WS_URL));
useEffect(() => {
// Subscribe to all events for this session
const unsubscribe = stream.subscribe(
[
"message",
"tool_call",
"tool_result",
"skill_activation_request",
"human_input_request",
"quality_check",
"progress_update",
"complete"
],
(event) => {
if (event.session_id === session_id) {
setEvents(prev => [...prev, event]);
}
}
);
return unsubscribe;
}, [session_id, stream]);
return { events, stream };
}
// UI component
function AgentExecutionView({ session_id }: { session_id: string }) {
const { events, stream } = useAgentEventStream(session_id);
const handleApproval = (event_id: string, approved: boolean) => {
stream.publish({
event_type: "permission_granted",
event_id: generateEventId(),
timestamp: Date.now(),
session_id,
data: { original_event_id: event_id, approved }
});
};
return (
<div className="execution-view">
{events.map(event => (
<EventRenderer
key={event.event_id}
event={event}
onApproval={handleApproval}
/>
))}
</div>
);
}
// Event renderer
function EventRenderer({ event, onApproval }: EventRendererProps) {
switch (event.event_type) {
case "message":
return <ChatMessage message={event.data.content} />;
case "tool_call":
return (
<ToolCallCard
tool={event.data.tool_name}
input={event.data.input}
/>
);
case "skill_activation_request":
return (
<SkillActivationPrompt
request={event.data}
onApprove={() => onApproval(event.event_id, true)}
onDeny={() => onApproval(event.event_id, false)}
/>
);
case "human_input_request":
return (
<HumanInputPrompt
request={event.data}
onSubmit={(response) => {
// Submit user input back to agent
}}
/>
);
case "quality_check":
return (
<QualityCheckResult
check={event.data.check}
result={event.data.result}
/>
);
case "progress_update":
return (
<ProgressIndicator
current={event.data.current}
total={event.data.total}
message={event.data.message}
/>
);
default:
return null;
}
}
Human-in-the-Loop (HITL) Patterns
Interaction Modes
// Co-planning mode
interface TaskPlan {
steps: TaskStep[];
estimated_duration: number;
risk_level: "low" | "medium" | "high";
}
interface TaskStep {
id: string;
description: string;
tools: string[];
estimated_duration: number;
requires_approval: boolean;
dependencies: string[];
}
class CoPlanningInterface {
async propose_plan(plan: TaskPlan): Promise<TaskPlan> {
// Show plan to user with editable steps
await this.emit_event({
event_type: "human_input_request",
data: {
request_type: "plan_approval",
plan,
actions: ["approve", "edit", "reject"]
}
});
const response = await this.wait_for_user_input();
if (response.action === "edit") {
// User modified the plan
return response.modified_plan;
} else if (response.action === "approve") {
return plan;
} else {
throw new Error("Plan rejected by user");
}
}
render_plan_editor(plan: TaskPlan): ReactElement {
return (
<PlanEditor
steps={plan.steps}
onReorder={(new_order) => this.reorderSteps(new_order)}
onEdit={(step_id, new_step) => this.editStep(step_id, new_step)}
onDelete={(step_id) => this.deleteStep(step_id)}
onApprove={() => this.approvePlan(plan)}
/>
);
}
}
// Action guards for high-risk operations
const ACTION_GUARDS = {
file_write: {
paths: ["/src/**/*.tsx", "/src/**/*.css"],
requires_approval: true,
approval_message: "About to modify UI components. Review changes?"
},
design_system_change: {
requires_approval: true,
approval_message: "This will update design system affecting all pages. Continue?"
},
navigation_restructure: {
requires_approval: true,
approval_message: "Navigation changes will affect user flow. Approve restructuring?"
}
};
class ActionGuardManager {
async check_guard(
action: string,
context: Record<string, any>
): Promise<boolean> {
const guard = ACTION_GUARDS[action];
if (!guard || !guard.requires_approval) {
return true;
}
await this.emit_event({
event_type: "action_guard",
data: {
action,
message: guard.approval_message,
context,
risk_assessment: this.assess_risk(action, context)
}
});
const response = await this.wait_for_approval();
return response.approved;
}
}
HumanInputRequest UX
interface HumanInputRequest {
event_type: "human_input_request";
request_id: string;
reason: string;
input_type: "approval" | "choice" | "freeform" | "review";
options?: string[];
default_value?: string;
timeout_seconds?: number;
deferrable?: boolean;
context: Record<string, any>;
}
// Example: Review UI changes before applying
const review_request: HumanInputRequest = {
event_type: "human_input_request",
request_id: generateId(),
reason: "Review consolidated header before applying",
input_type: "review",
options: ["Apply", "Modify", "Reject"],
default_value: "Apply",
timeout_seconds: 300,
deferrable: true,
context: {
before_preview: "<!-- Current header structure -->",
after_preview: "<!-- Consolidated header structure -->",
changes_summary: {
headers_removed: 3,
navigation_items_moved: 5,
height_reduction_px: 320
}
}
};
// UI Component
function ReviewChangesModal({ request }: { request: HumanInputRequest }) {
const [selected, setSelected] = useState(request.default_value);
return (
<Modal title="Review Changes">
<div className="split-view">
<div className="before">
<h3>Current</h3>
<CodePreview code={request.context.before_preview} />
</div>
<div className="after">
<h3>After Changes</h3>
<CodePreview code={request.context.after_preview} />
</div>
</div>
<div className="changes-summary">
<h4>Summary</h4>
<ul>
<li>Headers removed: {request.context.changes_summary.headers_removed}</li>
<li>Navigation items reorganized: {request.context.changes_summary.navigation_items_moved}</li>
<li>Vertical space reclaimed: {request.context.changes_summary.height_reduction_px}px</li>
</ul>
</div>
<div className="actions">
{request.options.map(option => (
<Button
key={option}
variant={option === selected ? "primary" : "secondary"}
onClick={() => setSelected(option)}
>
{option}
</Button>
))}
</div>
</Modal>
);
}
Oversight & Auditability
// Session timeline
interface SessionTimeline {
session_id: string;
started_at: number;
ended_at?: number;
events: TimelineEvent[];
summary: SessionSummary;
}
interface TimelineEvent {
timestamp: number;
event_type: EventType;
actor: "agent" | "user" | "system";
action: string;
details: Record<string, any>;
artifacts?: Artifact[];
}
interface Artifact {
type: "code_diff" | "file_created" | "file_modified" | "screenshot";
path: string;
before?: string;
after?: string;
metadata: Record<string, any>;
}
interface SessionSummary {
H.P.003-SKILLS_used: string[];
tools_called: string[];
files_modified: string[];
human_interventions: number;
quality_score: number;
duration_seconds: number;
}
// Timeline viewer component
function SessionTimelineViewer({ session_id }: { session_id: string }) {
const timeline = useSessionTimeline(session_id);
return (
<div className="timeline-viewer">
<SessionSummary summary={timeline.summary} />
<div className="timeline">
{timeline.events.map(event => (
<TimelineEventCard
key={event.timestamp}
event={event}
artifacts={event.artifacts}
/>
))}
</div>
<div className="export-options">
<Button onClick={() => exportTimeline(timeline, "json")}>
Export JSON
</Button>
<Button onClick={() => exportTimeline(timeline, "pdf")}>
Export PDF Report
</Button>
</div>
</div>
);
}
// Exportable audit log
function exportTimeline(timeline: SessionTimeline, format: "json" | "pdf"): void {
if (format === "json") {
const blob = new Blob([JSON.stringify(timeline, null, 2)], {
type: "application/json"
});
download(blob, `session-${timeline.session_id}.json`);
} else if (format === "pdf") {
// Generate PDF report with timeline visualization
generatePDFReport(timeline);
}
}
Implementation Roadmap for CODITECT
Phase 1: Foundation (Week 1 - Jan 19-25)
Goal: Core skill system with UI/UX capabilities
deliverables:
- skill_registry_implementation:
- Metadata-only loading
- Discovery API
- Activation flow
- ui_ux_H.P.003-SKILLS:
- header_consolidation (SKILL.md)
- navigation_frequency (SKILL.md)
- visual_design_principles (SKILL.md)
- design_system_application (SKILL.md)
- basic_event_protocol:
- Event types defined
- WebSocket server
- Frontend event subscription
- quality_gates:
- Header count validation
- Navigation depth validation
- Basic accessibility checks
success_criteria:
- Skills load without errors
- Avivate UI regenerated with improvements
- Will McKinley approval
- Before/after comparison shows measurable quality gain
Phase 2: Human-in-Loop (Week 2 - Jan 26-Feb 1)
Goal: HITL approval flows and action guards
deliverables:
- approval_ui_components:
- SkillActivationPrompt
- ActionGuardModal
- ReviewChangesModal
- action_guards:
- File write protection
- Design system changes
- Navigation restructuring
- permission_negotiation:
- Scope selection
- Risk assessment
- User preferences
success_criteria:
- Users can approve/deny skill activations
- High-risk actions trigger approval H.P.007-PROMPTS
- Preference system reduces approval fatigue
Phase 3: Tools & Automation (Week 3-4 - Feb 2-15)
Goal: Programmatic tools and H.P.004-SCRIPTS
deliverables:
- core_tools:
- analyze_headers
- optimize_navigation
- apply_design_system
- validate_quality
- automation_H.P.004-SCRIPTS:
- generate_design_system.sh
- validate_accessibility.py
- extract_logo_colors.py
- tool_chaining:
- Define common chains
- Dependency management
- Error recovery
success_criteria:
- Tools execute reliably
- Scripts generate valid design systems
- Tool chains complete without manual intervention
Phase 4: Reflection & Learning (Month 2 - Feb 16-Mar 15)
Goal: Continuous improvement from feedback
deliverables:
- feedback_collection:
- Post-execution surveys
- Rating system
- Comment capture
- skill_evolution:
- Identify update opportunities
- Generate proposed changes
- User approval flow
- learning_engine:
- Pattern detection
- Rule extraction
- Confidence scoring
success_criteria:
- 80%+ users provide feedback
- 3+ skill improvements identified
- 1+ skill update applied successfully
Integration with Existing CODITECT Platform
Current Architecture Touchpoints
integration_points:
agent_orchestrator:
- Register UI/UX agent as specialist
- Route UI generation requests
- Coordinate with lead agent
skill_loader:
- Load H.P.003-SKILLS from /mnt/H.P.003-SKILLS/public/ui_ux/
- Cache metadata for quick discovery
- Inject into agent context
event_bus:
- Publish skill events
- Subscribe to approval responses
- Maintain event log
customer_data:
- Load design systems from customer profiles
- Store user preferences
- Track quality metrics
output_pipeline:
- Apply quality gates before delivery
- Generate before/after comparisons
- Package artifacts for customer
Backward Compatibility
class BackwardCompatibilityLayer:
"""Ensure existing CODITECT functionality continues working."""
async def generate_ui(
self,
requirements: Dict[str, Any],
use_new_system: bool = True
) -> Dict[str, Any]:
"""Generate UI with optional new skill system."""
if not use_new_system:
# Fallback to legacy generation
return await self.legacy_ui_generator.generate(requirements)
# New skill-based generation
try:
# Discover applicable H.P.003-SKILLS
H.P.003-SKILLS = await self.skill_registry.discover_for_context(
requirements
)
# Request activation
activated = await self.activation_manager.request_activation_batch(
H.P.003-SKILLS,
requirements
)
# Execute with H.P.003-SKILLS
result = await self.ui_executor.generate(
requirements,
activated_H.P.003-SKILLS=activated
)
return result
except Exception as e:
# Fallback to legacy on error
logger.warning(f"New system failed, falling back: {e}")
return await self.legacy_ui_generator.generate(requirements)
Success Metrics & KPIs
Quality Metrics
ui_quality:
header_efficiency:
metric: "Average header count per page"
target: "≤ 1.2"
baseline: "3.8"
vertical_space:
metric: "Pixels to first content"
target: "< 100px"
baseline: "380px"
navigation_depth:
metric: "Clicks to most-accessed content"
target: "≤ 1.5"
baseline: "3.2"
accessibility:
metric: "WCAG AA compliance rate"
target: "> 95%"
baseline: "68%"
visual_complexity:
metric: "Visual layers per component"
target: "< 2.5"
baseline: "4.1"
customer_satisfaction:
design_quality_rating:
metric: "Post-project design rating (1-10)"
target: "> 8.0"
baseline: "6.2"
looks_ai_generated:
metric: "% mentioning 'looks AI-generated'"
target: "< 5%"
baseline: "42%"
professional_appearance:
metric: "% rating as 'professional/enterprise'"
target: "> 90%"
baseline: "58%"
nps_score:
metric: "Net Promoter Score"
target: "> 50"
baseline: "28"
operational:
skill_activation_rate:
metric: "% of UI tasks using H.P.003-SKILLS"
target: "100%"
current: "0%"
approval_fatigue:
metric: "Average approvals per session"
target: "< 3"
baseline: "N/A"
skill_improvement_cycle:
metric: "Days between skill updates"
target: "< 30"
baseline: "N/A"
Conclusion: Competitive Advantage Through Architecture
This Claude-style agentic architecture transforms CODITECT's UI/UX generation from ad-hoc AI output to a systematic, continuously-improving capability. The key advantages:
1. Quality Assurance: Built-in quality gates ensure professional output every time
2. Human Oversight: HITL patterns prevent errors while building user trust
3. Continuous Improvement: Reflection loop updates H.P.003-SKILLS based on real feedback
4. Auditability: Complete execution logs support enterprise compliance
5. Extensibility: Modular skill system enables rapid capability expansion
6. Differentiation: Structured approach impossible for competitors to replicate quickly
By implementing this architecture, CODITECT moves from "AI that generates code" to "AI that generates professional, enterprise-grade applications" - the difference between commodity tool and platform category leader.