Version: 5.4.0
Date: December 31, 2025
Status: Living Document
Last Update: All 16 AI/ML & Specialized Agents upgraded to Modern 4-Layer Architecture
Purple8 Builder is an enterprise-grade AI software development framework that transforms natural language requirements into production-ready applications. Unlike simple code generators, Builder implements a complete Software Development Lifecycle (SDLC) through 50+ specialized AI agents orchestrated by a sophisticated 4-layer architecture with knowledge graph-based dynamic agent selection.
Feature Parity Score:
├── vs Devin: ████████████████████████ 100% (Feature complete!)
├── vs Replit AI: ████████████████████████ 100%+ (We surpass with Live Preview + IDE)
├── vs Cursor: ████████████████████████ 100%+ (We surpass with 50+ agents)
└── vs Copilot: ████████████████████████ 100%+ (We surpass with full SDLC)
Unique Advantages (We're BETTER):
✅ 50-Agent Architecture (vs 1-10 for competitors)
✅ 4-Layer Architecture (UNIQUE - no competitor has this)
✅ Knowledge Graph Agent Selection (Dynamic routing - no hardcoded sequences)
✅ Purple8 IDE (Self-contained - NO external tool dependencies)
✅ Purple8 Copilot (Built-in AI coding assistant - Edit & Agent modes)
✅ MoE Cost Control ($0-50/mo vs Devin's $500/mo)
✅ Self-Hosting Capability (UNIQUE - data sovereignty)
✅ Requirements Tracing (Enterprise compliance-ready)
✅ Proactive Code Review (Built-in vulnerability scanning)
✅ Live Preview (Real-time app preview in browser)
✅ Git/PR Automation (LLM-powered commits and PRs)
✅ Chain-of-Thought Streaming (Transparent AI reasoning)
✅ Context Optimization V2 (Persistent relevance caching)
✅ Chatbot/Conversational AI Support (NEW - Dialog, Intent, NLU agents)
✅ Modern 4-Layer Integration (100% of AI/ML agents upgraded - Dec 31, 2025)
See: Full Competitive Analysis
Traditional software development requires:
Purple8 Builder automates the entire SDLC:
┌─────────────────────────────────────────────────────────────────────────────┐
│ PURPLE8 BUILDER │
│ │
│ "Build me a task management app with user auth and real-time updates" │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ 46 AI AGENTS WORKING TOGETHER │ │
│ │ │ │
│ │ Ideation → Design → Architecture → Database → API → Frontend → │ │
│ │ Backend → Infrastructure → Unit Tests → Integration Tests → │ │
│ │ API Tests → Load Tests → SIT → UAT → DevOps → Packaging → Deploy │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ PRODUCTION-READY APPLICATION │ │
│ │ • Complete source code (frontend + backend) │ │
│ │ • Database schemas and migrations │ │
│ │ • API documentation │ │
│ │ • Docker/Kubernetes configs │ │
│ │ • CI/CD pipelines │ │
│ │ • Test suites (unit, integration, e2e) │ │
│ │ • Deployment scripts │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
| Feature | Purple8 Builder | LangChain | AutoGPT | Devin |
|---|---|---|---|---|
| Full SDLC Coverage | ✅ 46 agents | ❌ | ❌ | Partial |
| 4-Layer Architecture | ✅ | ❌ | ❌ | ❌ |
| Persistent Memory | ✅ PostgreSQL/Redis/Qdrant | Plugin | Limited | ✅ |
| Cross-Session Learning | ✅ | ❌ | ❌ | ✅ |
| Quality Gates | ✅ | ❌ | ❌ | ❌ |
| Parallel Execution | ✅ | ❌ | ❌ | ❌ |
| Requirements Tracing | ✅ | ❌ | ❌ | ❌ |
| Code Execution Sandbox | ✅ Docker | ❌ | ❌ | ✅ |
| Multi-Language Runtime | ✅ Python/Node/Go | ❌ | ❌ | ✅ |
| Self-Debugging Loop | ✅ | ❌ | ❌ | ✅ |
| Structured Planning | ✅ | ❌ | Limited | ✅ |
| Proactive UI | ✅ | ❌ | ❌ | ✅ |
| Context Window Optimization | ✅ | ❌ | ❌ | ✅ |
Every execution is governed by an immutable Purpose that defines:
Agents are selected based on context relevance, not arbitrary priority numbers:
Each layer has a specific responsibility:
The 4-Layer Architecture is the brain of Purple8 Builder:
┌─────────────────────────────────────────────────────────────────────────────┐
│ 4-LAYER ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ LAYER 1: PURPOSE (Strategic Spine) ║ │
│ ║ ║ │
│ ║ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ║ │
│ ║ │ Intent │ │ Strategic │ │ Success │ │ Constraints │ ║ │
│ ║ │ │ │ Goal │ │ Criteria │ │ │ ║ │
│ ║ │ "Build task │ │ "Minimize │ │ - Tests ✓ │ │ - Budget │ ║ │
│ ║ │ manager" │ │ tech debt" │ │ - Perf <1s │ │ - Timeline │ ║ │
│ ║ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ ║ │
│ ║ ║ │
│ ║ 🔒 IMMUTABLE - Set once, referenced throughout execution ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │ │
│ │ Read Purpose │
│ ▼ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ LAYER 2: MEMORY (Persistent Session State) ║ │
│ ║ ║ │
│ ║ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────┐ ║ │
│ ║ │ Task Queue │ │ Completions │ │ Artifacts │ ║ │
│ ║ │ │ │ │ │ │ ║ │
│ ║ │ • pending: 5 │ │ • ideation: ✓ │ │ • requirements.md │ ║ │
│ ║ │ • active: 1 │ │ • design: ✓ │ │ • architecture.json │ ║ │
│ ║ │ • blocked: 0 │ │ • arch: 🔄 │ │ • src/main.py │ ║ │
│ ║ └────────────────┘ └────────────────┘ └────────────────────────┘ ║ │
│ ║ ║ │
│ ║ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────┐ ║ │
│ ║ │ Requirements │ │ Handoff Log │ │ Session State │ ║ │
│ ║ │ │ │ │ │ │ ║ │
│ ║ │ REQ-001: ✓ │ │ design→arch: │ │ phase: implementation │ ║ │
│ ║ │ REQ-002: 🔄 │ │ {context} │ │ iteration: 2 │ ║ │
│ ║ │ REQ-003: ⏳ │ │ │ │ rework_count: 0 │ ║ │
│ ║ └────────────────┘ └────────────────┘ └────────────────────────┘ ║ │
│ ║ ║ │
│ ║ 📝 LIVING DOCUMENT - Updated by agents, read by supervisor ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │ ▲ │
│ Get Task │ │ Store Output │
│ ▼ │ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ LAYER 3: EXECUTION AGENTS (Workers) ║ │
│ ║ ║ │
│ ║ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ║ │
│ ║ │Ideation │ │ Design │ │ Arch │ │Database │ │ API │ ║ │
│ ║ │ Agent │ │ Agent │ │ Agent │ │ Agent │ │ Agent │ ║ │
│ ║ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ ║ │
│ ║ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ║ │
│ ║ │Frontend │ │Backend │ │ Infra │ │ Unit │ │ Integ │ ║ │
│ ║ │ Agent │ │ Agent │ │ Agent │ │ Test │ │ Test │ ║ │
│ ║ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ ║ │
│ ║ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ║ │
│ ║ │API Test │ │Load Test│ │ SIT │ │ UAT │ │ DevOps │ ║ │
│ ║ │ Agent │ │ Agent │ │ Agent │ │ Agent │ │ Agent │ ║ │
│ ║ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ ║ │
│ ║ ┌─────────┐ ┌─────────┐ ║ │
│ ║ │Packaging│ │ Deploy │ + 29 Specialist Agents ║ │
│ ║ │ Agent │ │ Agent │ (AI/ML, Security, Mobile, etc.) ║ │
│ ║ └─────────┘ └─────────┘ ║ │
│ ║ ║ │
│ ║ ⚙️ FOCUSED WORKERS - Each agent does ONE thing well ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │ │
│ │ Signal Complete │
│ ▼ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ LAYER 4: SUPERVISOR (Loop Controller) ║ │
│ ║ ║ │
│ ║ ┌─────────────────────────────────────────────────────────────────┐ ║ │
│ ║ │ DECISION ENGINE │ ║ │
│ ║ │ │ ║ │
│ ║ │ while not purpose_satisfied: │ ║ │
│ ║ │ 1. Read L2 Memory (completions, failures, artifacts) │ ║ │
│ ║ │ 2. Compare against L1 Purpose (criteria met?) │ ║ │
│ ║ │ 3. Decide next action: │ ║ │
│ ║ │ • CONTINUE → Queue next agent │ ║ │
│ ║ │ • REWORK → Send back to previous agent │ ║ │
│ ║ │ • PARALLEL → Spawn multiple agents │ ║ │
│ ║ │ • TERMINATE → Purpose satisfied, stop │ ║ │
│ ║ │ 4. Update L2 task queue │ ║ │
│ ║ │ 5. Trigger L3 agent(s) │ ║ │
│ ║ │ │ ║ │
│ ║ └─────────────────────────────────────────────────────────────────┘ ║ │
│ ║ ║ │
│ ║ 🔄 LOOP CONTROLLER - Runs until all success criteria are met ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Location: shared/layers/purpose.py
The Purpose layer defines the immutable strategic context for the entire execution:
from shared.layers.purpose import PurposeBuilder, SuccessCriterion, Constraint
purpose = (PurposeBuilder()
.set_project("task-manager-app")
.set_intent("Build a collaborative task management application")
.set_strategic_goal("Deliver production-ready app in 2 hours")
.set_domain("web_application")
.set_tech_stack(["React", "FastAPI", "PostgreSQL"])
.add_criterion(SuccessCriterion(
id="SC-001",
description="All unit tests pass",
verification_method="unittest_agent"
))
.add_criterion(SuccessCriterion(
id="SC-002",
description="API response time < 200ms",
verification_method="load_test_agent"
))
.add_constraint(Constraint(
id="CON-001",
type=ConstraintType.SECURITY,
description="No PII stored in logs",
violation_action=ViolationAction.BLOCK
))
.build())
Key Classes:
PurposeContext - Immutable container for strategic intentSuccessCriterion - Measurable success conditionConstraint - Boundary that cannot be violatedQualityGate - Phase transition checkpointLocation: shared/layers/memory.py
The Memory layer maintains living session state throughout execution:
from shared.layers.memory import SharedMemoryStore, Task, TaskCompletion
# Initialize with purpose
memory = SharedMemoryStore(purpose=purpose)
# Queue a task
task = Task(
id="task-001",
agent="architecture",
description="Design system architecture",
dependencies=["ideation", "design"]
)
memory.task_queue.add_task(task)
# Complete a task
completion = TaskCompletion(
task_id="task-001",
agent="architecture",
status="success",
output="Architecture document generated",
artifacts=["architecture.json"]
)
memory.complete_task("task-001", completion)
Key Classes:
SharedMemoryStore - Central state containerTaskQueue - Pending/active/completed tasksTaskCompletion - Record of agent executionArtifact - Generated code/document/testLocation: shared/agents/
Agents are focused workers that execute specific tasks:
from shared.agents.base_agent import BaseAgent
from shared.agents.four_layer_mixin import FourLayerMixin
class ArchitectureAgent(FourLayerMixin, BaseAgent):
def __init__(self, llm_instance=None):
super().__init__(
llm_instance=llm_instance,
agent_name="ArchitectureAgent"
)
async def run(self, prompt: str, context: Dict = None) -> str:
# Access purpose context (from L1)
purpose_context = self.get_purpose_context()
# Access previous agent outputs (from L2)
handoff_summary = self.get_handoff_summary()
# Execute agent logic
result = await self._generate_architecture(prompt, context)
# Store artifacts (to L2)
self.store_document_artifact(
"architecture.md",
result,
"architecture-doc"
)
return result
Key Patterns:
BaseAgentFourLayerMixin adds 4-layer capabilitiesLocation: shared/layers/supervisor.py
The Supervisor orchestrates the entire execution loop:
from shared.layers.supervisor import SupervisorAgent
supervisor = SupervisorAgent(
memory=memory,
agent_registry={"architecture": arch_agent, ...},
max_iterations=100,
max_rework_cycles=3
)
# Register callbacks for observability
supervisor.on_decision(lambda d: print(f"Decision: {d}"))
supervisor.on_phase_change(lambda p: print(f"Phase: {p}"))
# Run the loop
result = await supervisor.run()
Decision Types:
CONTINUE - Proceed to next agent in sequenceREWORK - Quality issue, send back to previous agentPARALLEL - Execute multiple agents concurrentlyWAIT - Dependencies not met, holdTERMINATE - All criteria satisfied, done┌─────────────────────────────────────────────────────────────────────────────┐
│ 50+ SPECIALIZED AGENTS │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ FOUNDATIONAL AGENTS (17) │ │
│ │ Always run for every project │ │
│ │ │ │
│ │ CONCEPTION PLANNING IMPLEMENTATION │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────────────────┐ │ │
│ │ │ Ideation │────▶│ Design │──┐ │ API Development │ │ │
│ │ └──────────┘ └──────────┘ │ │ Frontend Development │ │ │
│ │ ┌──────────┐ │ │ Backend Development │ │ │
│ │ │ Arch │◀─┘ │ Infrastructure Dev │ │ │
│ │ └──────────┘ └──────────────────────┘ │ │
│ │ ┌──────────┐ │ │
│ │ │ Database │ │ │
│ │ └──────────┘ │ │
│ │ │ │
│ │ QUALITY ASSURANCE DELIVERY │ │
│ │ ┌──────────────────────────┐ ┌──────────────────────┐ │ │
│ │ │ Unit Test │ │ DevOps │ │ │
│ │ │ Integration Test (BARRIER)│ │ Software Packaging │ │ │
│ │ │ API Test │ │ Deployment │ │ │
│ │ │ Load Test │ └──────────────────────┘ │ │
│ │ │ SIT (E2E) │ │ │
│ │ │ UAT │ │ │
│ │ └──────────────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ SPECIALIST AGENTS (33+) │ │
│ │ Selected dynamically via Knowledge Graph │ │
│ │ │ │
│ │ AI/ML (17) QA (10) SPECIALIZED (10+) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ ML Agent │ │ Security QA │ │ Mobile Agent │ │ │
│ │ │ AI Engineer │ │ Performance │ │ DevOps Agent │ │ │
│ │ │ Data Science │ │ Accessibility│ │ Legal Agent │ │ │
│ │ │ NLP Agent │ │ Chaos Agent │ │ Visual Design│ │ │
│ │ │ Computer Vis │ │ Visual Regr │ │ Observability│ │ │
│ │ │ MLOps Agent │ │ Mobile Test │ └──────────────┘ │ │
│ │ │ LLMOps Agent │ │ Beta UAT │ │ │
│ │ │ Recommender │ └──────────────┘ CHATBOT (4) - NEW │ │
│ │ │ Time Series │ ┌──────────────┐ │ │
│ │ │ Speech Agent │ │ Conversation │ │ │
│ │ │ Multimodal │ │ Dialog Mgmt │ │ │
│ │ │ ... +6 more │ │ Intent Recog │ │ │
│ │ └──────────────┘ │ Chatbot FW │ │ │
│ │ └──────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Status: ✅ 100% COMPLETE - All 16 AI/ML and specialized agents upgraded to modern 4-layer architecture
| # | Agent | File | Technologies | Status |
|---|---|---|---|---|
| 1 | NLPAgent | aiml/nlp_agent.py |
BERT, Transformers, spaCy, NLTK | ✅ Complete |
| 2 | MachineLearningAgent | aiml/machine_learning_agent.py |
scikit-learn, PyTorch, TensorFlow, MLflow | ✅ Complete |
| 3 | DataScienceAgent | aiml/data_science_agent.py |
Pandas, NumPy, Matplotlib, Statistical Analysis | ✅ Complete |
| 4 | ComputerVisionAgent | aiml/computer_vision_agent.py |
ResNet, YOLO, ViT, OpenCV | ✅ Complete |
| 5 | RecommenderAgent | aiml/recommender_agent.py |
SVD, NCF, LightFM, Collaborative Filtering | ✅ Complete |
| 6 | TimeSeriesAgent | aiml/time_series_agent.py |
ARIMA, Prophet, LSTM, Forecasting | ✅ Complete |
| 7 | SpeechAgent | aiml/speech_agent.py |
Whisper, Wav2Vec2, TTS, ASR | ✅ Complete |
| 8 | MultimodalAgent | aiml/multimodal_agent.py |
CLIP, BLIP, VQA, Cross-modal Learning | ✅ Complete |
| 9 | GraphAnalyticsAgent | aiml/graph_analytics_agent.py |
Neo4j, NetworkX, PageRank, Cypher | ✅ Complete |
| 10 | DevOpsAgent | specialized/dev_ops_agent.py |
CI/CD, Docker, Kubernetes, Terraform | ✅ Complete |
| 11 | LoadTestAgent | qa/load_test_agent.py |
Locust, k6, JMeter, Performance Testing | ✅ Complete |
| 12 | AuditAgent | enterprise/audit_agent.py |
Audit trails, Compliance tracking | ✅ Complete |
| 13 | ComplianceAgent | enterprise/compliance_agent.py |
SOC2, HIPAA, GDPR, Regulatory compliance | ✅ Complete |
| 14 | CyberSecurityAgent | enterprise/cyber_security_agent.py |
STRIDE, DREAD, OWASP, Security analysis | ✅ Complete |
| 15 | DataEngineeringAgent | enterprise/data_engineering_agent.py |
ETL, Airflow, dbt, Data pipelines | ✅ Complete |
| 16 | MobileAgent | specialized/mobile_agent.py |
React Native, Flutter, Swift, Kotlin | ✅ Complete |
Each upgraded agent now includes:
class NLPAgent(FourLayerMixin, BaseAgent):
def __init__(self, llm_instance=None):
super().__init__(llm_instance, agent_name="NLPAgent")
run() Method
async def run(self, requirements, architecture, context, **kwargs):
# L1: Strategic context
purpose_context = self.get_purpose_context()
# L2: Previous agent outputs
handoff_summary = self.get_handoff_summary()
# L3: Execute agent logic with expert system prompt
result = await self._generate_nlp_solution(...)
# L2: Store artifacts
self.extract_and_store_code_blocks(result)
# L4: Requirements tracking
addressed_reqs = self._identify_addressed_requirements(requirements)
self.check_in_requirements(addressed_reqs, "implementation", "complete", ...)
return result
_format_architecture(architecture) - Standardized architecture formatting_build_X_prompt(requirements, architecture, context) - Concise expert prompts_parse_code_output(output) - Extract code blocks from LLM output_identify_addressed_requirements(requirements) - Parse REQ-IDs_create_human_summary(output, requirements) - HITL summaries with tech stack details✅ Consistent Architecture: All agents follow same 4-layer pattern
✅ Artifact Storage: Automatic code/document extraction and storage
✅ Requirements Tracing: Track which requirements each agent addresses
✅ HITL Summaries: Human-readable tech stack summaries for review
✅ Memory Integration: Agents share context via SharedMemoryStore
✅ Expert Prompts: Domain expertise retained while gaining modern capabilities
✅ Maintainability: Cleaner, more concise code (60% size reduction)
Before (Old Pattern):
class OldNLPAgent(BaseAgent):
async def run(self, prompt, context):
# 400+ lines of embedded template code
# No 4-layer integration
# Manual artifact handling
# No requirements tracking
return output
After (Modern Pattern):
class NLPAgent(FourLayerMixin, BaseAgent):
async def run(self, requirements, architecture, context, **kwargs):
# L1/L2: Context access
purpose = self.get_purpose_context()
handoff = self.get_handoff_summary()
# L3: Execution with expert prompt
prompt = self._build_nlp_prompt(requirements, architecture, context)
result = await self.llm.generate(prompt)
# L2: Automatic storage
self.extract_and_store_code_blocks(result)
# L4: Requirements check-in
reqs = self._identify_addressed_requirements(requirements)
self.check_in_requirements(reqs, "implementation", "complete", ...)
return result
These agents run for every project without exception:
| Phase | Agent | Purpose | Dependencies |
|---|---|---|---|
| Conception | ideation |
Requirements analysis | None |
| Planning | design |
UI/UX design | ideation |
architecture |
System architecture | ideation, design | |
database |
Data modeling | architecture | |
| Implementation | api_development |
API contracts | architecture, database |
frontend_development |
UI code | design, api_development | |
backend_development |
Server code | architecture, database, api_development | |
infrastructure_development |
DevOps configs | architecture, database, frontend, backend | |
| QA | unittest |
Unit tests | frontend, backend |
integration_test |
Integration tests (BARRIER) | unittest, all dev agents | |
api_test |
API contract tests | backend, api_development | |
load_test |
Performance tests | integration_test | |
sit |
E2E system tests | integration_test | |
uat |
User acceptance | sit | |
| Delivery | devops |
CI/CD pipelines | infrastructure, uat |
software_packaging |
Build artifacts | devops, uat | |
deployment |
Deploy to environment | software_packaging |
The SmartAgentOrchestrator selects additional agents based on project characteristics:
# Project analysis determines which specialists to add
project = ProjectAnalyzer.analyze(prompt)
if project.has_mobile:
add_agent("mobile_agent")
add_agent("mobile_test_agent")
if project.has_ai_ml:
add_agent("machine_learning_agent")
add_agent("mlops_agent")
add_agent("evaluation_metrics_agent")
if project.security_critical:
add_agent("security_qa_agent")
add_agent("guardrails_agent")
if project.needs_observability:
add_agent("observability_agent")
All agents MUST inherit from BaseAgent:
# Location: shared/agents/base_agent.py
class BaseAgent:
def __init__(
self,
llm_instance=None,
agent_name: str = "BaseAgent",
enable_moe: bool = False # Multi-model execution
):
self.agent_name = agent_name
self.llm = llm_instance or get_default_llm()
self.enable_moe = enable_moe
async def run(self, prompt: str, context: Dict = None) -> str:
"""Execute agent logic - MUST be overridden"""
raise NotImplementedError
async def execute_with_metadata(self, prompt, context) -> Dict:
"""Returns output + timing + status"""
start = time.time()
output = await self.run(prompt, context)
return {
"output": output,
"duration_ms": (time.time() - start) * 1000,
"status": "success",
"agent": self.agent_name
}
async def stream(self, prompt, context):
"""Real-time streaming for SSE"""
...
Adds 4-layer capabilities to any agent:
# Location: shared/agents/four_layer_mixin.py
class FourLayerMixin:
"""Add to agents: class MyAgent(FourLayerMixin, BaseAgent)"""
def set_memory(self, memory: SharedMemoryStore):
"""Connect agent to L2 memory"""
self._memory = memory
def get_purpose_context(self) -> str:
"""Get L1 purpose as formatted prompt text"""
return self._memory.purpose.to_prompt_context()
def get_handoff_summary(self) -> str:
"""Get outputs from previous agents"""
return self._memory.get_handoff_summary()
def store_code_artifact(self, name, content, task_id):
"""Store generated code in L2"""
...
def store_document_artifact(self, name, content, task_id):
"""Store generated documentation in L2"""
...
def store_test_artifact(self, name, content, task_id):
"""Store generated tests in L2"""
...
Location: services/knowledge_graph/agent_selection_graph.py
The Knowledge Graph Agent Selection system replaces hardcoded agent sequences with dynamic, context-aware routing. Instead of always starting with the ideation agent, the system analyzes project requirements and selects the most appropriate agents and execution order using Neo4j graph relationships.
┌─────────────────────────────────────────────────────────────────────────────┐
│ KNOWLEDGE GRAPH AGENT SELECTION │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ User Prompt │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ PROJECT ANALYZER │ │
│ │ • detect_project_type() → web, mobile, chatbot, ai_ml, etc. │ │
│ │ • extract_capabilities() → auth, database, api, nlp, etc. │ │
│ │ • assess_complexity() → simple, medium, complex, enterprise │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ NEO4J KNOWLEDGE GRAPH │ │
│ │ │ │
│ │ (Agent)──[:REQUIRES]──▶(Agent) │ │
│ │ (Agent)──[:PROVIDES]──▶(Capability) │ │
│ │ (Agent)──[:DOMAIN]──▶(Domain) │ │
│ │ │ │
│ │ Query: "Which agents provide {capabilities} for {domain}?" │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ EXECUTION GRAPH BUILDER │ │
│ │ • build_execution_graph() → topological sort of required agents │ │
│ │ • resolve_dependencies() → ensure all prerequisites are met │ │
│ │ • optimize_parallelism() → identify agents that can run in parallel │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ [Ordered Agent Sequence for Execution] │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
from services.knowledge_graph.agent_selection_graph import AgentSelectionGraph
# Initialize with Neo4j connection
graph = AgentSelectionGraph(neo4j_manager)
# Analyze project and get agents
prompt = "Build a customer support chatbot with sentiment analysis"
capabilities = graph.analyze_requirements(prompt)
# Returns: ProjectCapabilities(
# project_type="chatbot",
# domains=["conversational_ai", "nlp"],
# required_capabilities=["dialog_management", "intent_recognition", "sentiment"],
# complexity="medium"
# )
# Get agent execution graph
agents = graph.get_agents_for_capabilities(capabilities)
# Returns ordered list:
# 1. conversational_ai_agent (entry point - NOT ideation for chatbot)
# 2. dialog_management_agent
# 3. intent_recognition_agent
# 4. backend_development (for API)
# 5. ... testing agents
| Project Type | Entry Agent | Domain Agents |
|---|---|---|
web_application |
ideation | frontend, backend, database |
mobile_app |
mobile_agent | ios, android, react_native |
chatbot |
conversational_ai | dialog, intent, nlu |
ai_ml_pipeline |
ml_agent | data_science, mlops |
api_service |
api_development | backend, database |
data_analytics |
data_science | analytics, visualization |
Purple8 includes a complete, self-contained development environment that eliminates the need for external tools like VSCode, GitHub, or paid AI assistants. This section covers all IDE capabilities.
📚 Related Sections
- Purple8 Sandbox - Detailed sandbox architecture, runtimes, and API reference
- Proactive UI System - Advanced UI components and real-time insights
- Purple8 Copilot - AI coding assistant details (in this section)
Location: frontend-vue/src/components/sandbox/, services/gateway/routers/sandbox.py
Purple8 IDE provides:
┌─────────────────────────────────────────────────────────────────────────────┐
│ PURPLE8 IDE COMPONENTS │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐│
│ │ SANDBOX PANEL │ │ PROACTIVE PANEL │ │ PREVIEW PANEL ││
│ │ │ │ │ │ ││
│ │ 📝 Code Editor │ │ 📝 Code Review │ │ 🖥️ Live Preview ││
│ │ 📁 File Manager │ │ 🔒 Security Scan │ │ 📱 Device Modes ││
│ │ 💻 Terminal │ │ ⚡ Performance │ │ 🎯 Inspector ││
│ │ 📦 Packages │ │ Analysis │ │ 📸 Screenshots ││
│ │ │ │ │ │ ⏺️ Recording ││
│ └─────────────────────┘ └─────────────────────┘ └─────────────────────┘│
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐│
│ │ SANDBOX BACKEND (Docker) ││
│ │ ││
│ │ • Isolated container per session ││
│ │ • Multi-language support (Python, JS, TS, Go, Rust, Bash) ││
│ │ • Resource limits (CPU, memory, disk) ││
│ │ • Real-time streaming output ││
│ │ • Auto-debugging with fix suggestions ││
│ └─────────────────────────────────────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────────────────┘
| Endpoint | Method | Description |
|---|---|---|
/api/sandbox/sessions |
POST | Create sandbox session |
/api/sandbox/sessions/{id} |
GET | Get session info |
/api/sandbox/sessions/{id} |
DELETE | Destroy session |
/api/sandbox/sessions/{id}/execute |
POST | Execute code |
/api/sandbox/execute/debug |
POST | Execute with auto-debug |
/api/sandbox/sessions/{id}/files/write |
POST | Write file |
/api/sandbox/sessions/{id}/files/read |
GET | Read file |
/api/sandbox/sessions/{id}/files/list |
GET | List files |
/api/sandbox/sessions/{id}/packages/install |
POST | Install package |
/api/sandbox/tests/run |
POST | Run tests |
/api/sandbox/validate/syntax |
POST | Validate code syntax |
/api/sandbox/validate/pipeline |
POST | Validate pipeline artifacts |
Code Review Panel (ProactivePanel.vue):
Security Panel:
Performance Panel:
Enhanced Preview Panel (EnhancedPreviewPanel.vue):
Purple8 is designed for complete independence:
| Feature | Purple8 IDE | VSCode | GitHub |
|---|---|---|---|
| Code Editing | ✅ Built-in | Requires install | N/A |
| File Management | ✅ Built-in | Requires install | Requires account |
| Terminal | ✅ Sandboxed | Local only | N/A |
| Version Control | ✅ Built-in Git | Git CLI | External service |
| Live Preview | ✅ Built-in | Extension needed | Pages/Actions |
| Security Scan | ✅ Real-time | Extensions | Dependabot |
| CI/CD | ✅ Integrated | External | GitHub Actions |
| AI Copilot | ✅ Built-in | Copilot ($10/mo) | Copilot ($10/mo) |
Benefits:
Location: services/gateway/routers/ide_copilot.py, frontend-vue/src/components/sandbox/IDECopilot.vue
Purple8 Copilot is the built-in AI coding assistant that provides VS Code Copilot-like functionality directly in the Purple8 IDE. It operates in two modes:
Provides inline code assistance similar to GitHub Copilot:
| Action | Description | Keyboard |
|---|---|---|
| Complete | Auto-complete code at cursor | Tab to accept |
| Suggest | Suggest next lines of code | - |
| Refactor | Refactor selected code | - |
| Explain | Explain what code does | - |
| Fix | Fix errors in code | - |
| Optimize | Optimize for performance | - |
| Document | Add documentation/comments | - |
| Test | Generate unit tests | - |
A conversational AI assistant for complex coding tasks:
┌─────────────────────────────────────────────────────────────────────────────┐
│ 💬 Purple8 Copilot - Agent Mode │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 👤 User: "Add error handling to this function" │
│ │
│ 🤖 Copilot: Here's the updated code with proper error handling: │
│ │
│ ```python │
│ async def fetch_data(url: str) -> dict: │
│ try: │
│ response = await client.get(url) │
│ response.raise_for_status() │
│ return response.json() │
│ except httpx.HTTPError as e: │
│ logger.error(f"HTTP error: {e}") │
│ raise DataFetchError(f"Failed to fetch: {e}") │
│ ``` │
│ │
│ 💡 Follow-up questions: │
│ • Would you like me to add retry logic? │
│ • Should I add request timeout handling? │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
| Endpoint | Method | Description |
|---|---|---|
/api/ide/copilot/edit/complete |
POST | Get code completion at cursor |
/api/ide/copilot/edit/action |
POST | Perform edit action (refactor, fix, etc.) |
/api/ide/copilot/edit/suggest |
POST | Stream code suggestions |
/api/ide/copilot/agent/chat |
POST | Chat with coding assistant |
/api/ide/copilot/agent/chat/stream |
POST | Stream chat response |
/api/ide/copilot/quick/explain |
POST | Quick explain code |
/api/ide/copilot/quick/fix |
POST | Quick fix code |
/api/ide/copilot/quick/test |
POST | Quick generate tests |
/api/ide/copilot/health |
GET | Check copilot health |
// Edit Mode - Complete code
const completion = await axios.post('/api/ide/copilot/edit/complete', {
code: 'def calculate_total(',
cursor_line: 1,
cursor_column: 21,
language: 'python'
});
// Returns: { suggestions: ['items):\n return sum(item.price for item in items)'] }
// Agent Mode - Chat
const response = await axios.post('/api/ide/copilot/agent/chat', {
message: 'Add validation to this function',
code_context: 'def save_user(name, email):\n db.save(name, email)',
language: 'python'
});
// Returns: { message: '...', code_blocks: [...], follow_up_questions: [...] }
| Feature | Purple8 Copilot | GitHub Copilot | Cursor |
|---|---|---|---|
| Price | ✅ Included | $10/mo | $20/mo |
| Edit Mode | ✅ | ✅ | ✅ |
| Agent Mode | ✅ | ❌ (Chat only) | ✅ |
| Inline Completions | ✅ | ✅ | ✅ |
| Code Actions | ✅ 8 actions | Limited | ✅ |
| Self-Hosted | ✅ | ❌ | ❌ |
| Custom Models | ✅ MoE | ❌ GPT-4 only | ❌ |
| Context Aware | ✅ Full IDE context | Limited | ✅ |
📖 Development Environment Detailed Documentation
- Purple8 Sandbox - Container architecture, runtimes, executor API, security
- Proactive UI System - Suggestion bar, insights panel, UI components
PURPLE8 BUILDER PIPELINE v3.0
═══════════════════════════════════════════════════════════════════════════════
PHASE 1: CONCEPTION
┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ User Prompt ───▶ [IDEATION AGENT] ───▶ Requirements Document │
│ • REQ-001, REQ-002, ... │
│ • User Stories │
│ • Acceptance Criteria │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
PHASE 2: PLANNING
┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ Requirements ───▶ [DESIGN] ───▶ UI/UX Spec │
│ │ • Components │
│ │ • User Flows │
│ ▼ • Wireframes │
│ [ARCHITECTURE] ───▶ System Design │
│ │ • Components │
│ │ • Tech Stack │
│ │ • API Contracts │
│ ▼ │
│ [DATABASE] ───▶ Data Model │
│ • Schema (DDL) │
│ • Migrations │
│ • ORM Models │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
PHASE 3: IMPLEMENTATION (Parallel Execution)
┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ [API DEVELOPMENT] │
│ │ │
│ ┌───────────────┼───────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ [FRONTEND DEV] [BACKEND DEV] [INFRA DEV] │
│ │ │ │ │
│ │ ┌─────────────┼───────────────┤ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ React/Vue Code FastAPI/Node Docker/K8s │
│ Components Routes/Models CI/CD Configs │
│ State Mgmt Business Logic Cloud Setup │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
PHASE 4: QUALITY ASSURANCE (4-Layer Testing)
┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ Layer 1: UNIT TESTS (parallel with dev) │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ [UNITTEST AGENT] ───▶ pytest/jest tests per component │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ Layer 2: API TESTS │ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ [API TEST AGENT] ───▶ Contract tests, endpoint validation │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ════════════════════════ BARRIER ══════════════════════════════════════ │
│ │ │
│ Layer 3: INTEGRATION TESTS ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ [INTEGRATION TEST AGENT] ───▶ Module interaction tests │ │
│ │ (Waits for ALL dev agents to complete before running) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ Layer 4: E2E & ACCEPTANCE ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ [LOAD TEST] ───▶ Performance under stress │ │
│ │ [SIT AGENT] ───▶ Full user workflow tests │ │
│ │ [UAT AGENT] ───▶ Requirements validation │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
PHASE 5: DELIVERY
┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ [DEVOPS AGENT] ───▶ CI/CD Pipelines │
│ │ • GitHub Actions │
│ │ • Container Registry │
│ ▼ │
│ [SOFTWARE PACKAGING] ───▶ Build Artifacts │
│ │ • Docker Images │
│ │ • Helm Charts │
│ ▼ │
│ [DEPLOYMENT AGENT] ───▶ Production Deployment │
│ • Rolling Update │
│ • Health Checks │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────┐
│ ✅ PRODUCTION APP │
│ DELIVERED │
└─────────────────────┘
# From: services/smart_orchestrator.py
FOUNDATIONAL_AGENTS = {
# Conception
'ideation': {'dependencies': []},
# Planning
'design': {'dependencies': ['ideation']},
'architecture': {'dependencies': ['ideation', 'design']},
'database': {'dependencies': ['architecture']},
# Implementation
'api_development': {'dependencies': ['architecture', 'database']},
'frontend_development': {'dependencies': ['design', 'api_development']},
'backend_development': {'dependencies': ['architecture', 'database', 'api_development']},
'infrastructure_development': {'dependencies': ['architecture', 'database', 'frontend_development', 'backend_development']},
# QA
'unittest': {'dependencies': ['frontend_development', 'backend_development']},
'api_test': {'dependencies': ['backend_development', 'api_development']},
'integration_test': {'dependencies': ['unittest', 'frontend_development', 'backend_development', 'infrastructure_development']}, # BARRIER
'load_test': {'dependencies': ['integration_test']},
'sit': {'dependencies': ['integration_test']},
'uat': {'dependencies': ['sit']},
# Delivery
'devops': {'dependencies': ['infrastructure_development', 'uat']},
'software_packaging': {'dependencies': ['devops', 'uat', 'infrastructure_development']},
'deployment': {'dependencies': ['software_packaging']},
}
Location: services/smart_orchestrator.py
The brain that selects and sequences agents:
class SmartAgentOrchestrator:
"""
Intelligent orchestrator that:
1. Analyzes project characteristics
2. Selects foundational + specialist agents
3. Resolves dependencies into execution order
4. Provides agent recommendations
"""
async def compose_workflow(self, prompt: str) -> List[AgentRecommendation]:
# 1. Analyze project
characteristics = await self.analyzer.analyze(prompt)
# 2. Add foundational agents (always)
agents = self._add_foundational_agents()
# 3. Add specialist agents (context-driven)
if characteristics.has_ai_ml:
agents += self._add_ai_ml_agents()
if characteristics.is_mobile:
agents += self._add_mobile_agents()
# 4. Sort by dependencies
ordered = self._topological_sort(agents)
return ordered
Location: services/pipeline_runner.py
Integrates SmartOrchestrator with 4-layer architecture:
class FourLayerPipelineRunner:
"""
Executes the pipeline using 4-layer architecture:
- Creates L1 Purpose from user prompt
- Initializes L2 Memory
- Runs L3 Agents through L4 Supervisor
"""
async def run(self, prompt: str) -> PipelineResult:
# 1. Create L1 Purpose
purpose = await self._create_purpose(prompt)
# 2. Initialize L2 Memory
memory = SharedMemoryStore(purpose=purpose)
# 3. Get agent workflow
workflow = await self.orchestrator.compose_workflow(prompt)
# 4. Initialize L4 Supervisor
supervisor = SupervisorAgent(memory=memory)
# 5. Register L3 Agents
for agent_rec in workflow:
agent = self._instantiate_agent(agent_rec)
agent.set_memory(memory)
supervisor.register_agent(agent_rec.agent_id, agent)
# 6. Run supervisor loop
result = await supervisor.run()
return result
Location: services/project_analyzer.py
Analyzes user prompts to determine project characteristics:
class ProjectAnalyzer:
"""
Analyzes project requirements to determine:
- Project type (web, mobile, API, etc.)
- Complexity (simple, medium, complex)
- Domain signals (AI/ML, security, mobile, etc.)
- Resource requirements
"""
async def analyze(self, prompt: str) -> ProjectCharacteristics:
return ProjectCharacteristics(
project_type=self._detect_project_type(prompt),
complexity=self._assess_complexity(prompt),
has_ai_ml=self._detect_ai_ml(prompt),
has_mobile=self._detect_mobile(prompt),
security_critical=self._detect_security(prompt),
needs_observability=self._detect_observability(prompt),
tech_stack=self._extract_tech_stack(prompt),
)
Location: shared/agents/registry.py
Single source of truth for all agent contracts:
AGENT_CONTRACT_TEMPLATES = {
"ideation": {
"phase": "conception",
"dependencies": [],
"required_inputs": ["prompt"],
"optional_inputs": ["context", "mode"],
"output_format": "markdown",
"output_schema": {
"requirements_specification": {...},
"features": {...},
"user_stories": {...},
}
},
"architecture": {
"phase": "planning",
"dependencies": ["ideation", "design"],
"required_inputs": ["requirements"],
"output_format": "json",
"output_schema": {
"system_design": {...},
"components": {...},
"technology_stack": {...},
}
},
# ... 44 more agent contracts
}
Location: services/purple8/moe_orchestrator.py
Dynamic model selection across 30+ LLMs:
class Purple8MoEOrchestrator:
"""
Intelligently routes tasks to optimal LLM based on:
- Task complexity
- Domain requirements
- Cost constraints
- Latency requirements
"""
TIERS = {
"free": ["deepseek-coder", "mistral", "llama3.2"], # Ollama
"balanced": ["gpt-4o-mini", "gemini-flash"], # ~$0.40/MTok
"premium": ["gpt-4o", "claude-sonnet", "gemini-pro"] # ~$2-4/MTok
}
async def select_model(self, task_type: str, context: Dict) -> str:
# "FREE FIRST, PREMIUM WHEN NEEDED"
if self._is_simple_task(task_type):
return self.TIERS["free"][0]
elif self._needs_reasoning(context):
return self.TIERS["premium"][0]
else:
return self.TIERS["balanced"][0]
Location: shared/agents/llm_factory.py
Critical agents automatically receive premium models for better output quality:
# Tier 1: Critical agents that need premium models (complex reasoning, code generation)
TIER_1_AGENTS = [
"architecture", "design", "ideation", # Planning agents
"frontend_development", "backend_development", "api_development", # All development agents
"infrastructure_development", "database" # Infrastructure agents
]
# Tier 2: Supporting agents (can use balanced models)
# Tier 3: Testing/documentation agents (fast models sufficient)
def get_model_for_agent(agent_name: str) -> str:
"""
Select appropriate model based on agent tier.
Tier 1 agents get GPT-4o/Gemini Pro for complex reasoning.
"""
agent_lower = agent_name.lower().replace("agent", "").strip("_")
if agent_lower in TIER_1_AGENTS:
# Premium models: GPT-4o, Gemini Pro, Claude Sonnet
return select_premium_model()
else:
# Balanced/Fast models: GPT-4o-mini, Gemini Flash
return select_balanced_model()
Agent Tier Classification:
| Tier | Agents | Model Class | Reasoning |
|---|---|---|---|
| Tier 1 | Architecture, Design, Ideation, All Development, Database | GPT-4o, Gemini Pro | Complex reasoning, code generation |
| Tier 2 | Integration Test, API Test, DevOps | GPT-4o-mini, Gemini Flash | Supporting tasks |
| Tier 3 | Unit Test, Documentation, Packaging | Fast models | Simple generation |
Location: shared/utils/diagram_generator.py
Purple8 uses the Python Diagrams library for generating architecture and database diagrams. This replaces the deprecated Mermaid-based diagrams.
from shared.utils.diagram_generator import DiagramGenerator
generator = DiagramGenerator()
# Generate architecture diagram
result = await generator.generate_architecture_diagram(
components=[
{"name": "API Gateway", "type": "api"},
{"name": "Auth Service", "type": "service"},
{"name": "PostgreSQL", "type": "database"},
{"name": "Redis Cache", "type": "cache"},
],
connections=[
{"from": "API Gateway", "to": "Auth Service"},
{"from": "Auth Service", "to": "PostgreSQL"},
{"from": "Auth Service", "to": "Redis Cache"},
],
title="Task Manager Architecture"
)
# Returns: {"available": True, "image_base64": "...", "format": "png"}
# Generate ERD diagram
erd = await generator.generate_database_erd(
tables=[
{"name": "users", "columns": ["id", "email", "name"], "pk": "id"},
{"name": "tasks", "columns": ["id", "title", "user_id"], "pk": "id", "fk": {"user_id": "users.id"}},
],
title="Task Manager ERD"
)
Supported Diagram Types:
generate_architecture_diagram() - System architecture with cloud iconsgenerate_database_erd() - Entity-Relationship Diagramsgenerate_ai_pipeline_diagram() - AI/ML data flow pipelinesgenerate_microservices_diagram() - Service communication diagramsFrontend Component: DiagramViewer.vue
<!-- frontend-vue/src/components/visualizations/DiagramViewer.vue -->
<template>
<div class="diagram-viewer">
<img :src="currentDiagramSrc" :alt="currentDiagramTitle" />
<div class="controls">
<button @click="zoomIn">🔍+</button>
<button @click="zoomOut">🔍-</button>
<button @click="toggleFullscreen">⛶</button>
<button @click="download">⬇️</button>
</div>
</div>
</template>
Agent Integration:
output.diagramsoutput.erd_diagramLocation: shared/services/penpot_integration.py, docker-compose.penpot.yml
Self-hosted Penpot design platform for UI/UX wireframe creation:
from shared.services.penpot_integration import PenpotIntegration
penpot = PenpotIntegration()
# Check availability
if await penpot.is_available():
# Login
await penpot.login("designer@purple8.ai", "password")
# Create project
project = await penpot.create_project("Task Manager Design", team_id="...")
# Create design file
file = await penpot.create_file(project.id, "Mobile Wireframes")
# Export as PNG
export = await penpot.export_file(file.id, format="png")
Docker Deployment:
# Start Penpot services
docker-compose -f docker-compose.penpot.yml up -d
# Access Penpot UI
open http://localhost:9002
Service Ports:
| Service | Container | Port | Purpose |
|---|---|---|---|
| Penpot Frontend | 8-penpot-frontend | 9002 | Design UI |
| Penpot Backend | 8-penpot-backend | 6060 | API server |
| Penpot Exporter | 8-penpot-exporter | 6061 | Export service |
| Penpot PostgreSQL | 8-penpot-postgres | (internal) | Penpot data |
| Penpot Redis | 8-penpot-redis | (internal) | Penpot cache |
Design Agent Integration:
The Design agent outputs screen_navigation JSON structure for navigation flows. Visual wireframes are created manually in Penpot or via the API.
🔗 Part of: Purple8 Development Environment Related: Purple8 IDE · Purple8 Copilot
The Purple8 Sandbox is a Docker-based secure code execution environment that enables Builder to run, test, and debug generated code in real-time. This is a critical differentiator that allows Purple8 to compete with Devin and Replit.
┌─────────────────────────────────────────────────────────────────────────────┐
│ WITHOUT SANDBOX vs WITH SANDBOX │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ WITHOUT SANDBOX (Traditional): WITH SANDBOX (Purple8): │
│ ┌─────────────────────────────┐ ┌─────────────────────────────┐ │
│ │ 1. Generate code │ │ 1. Generate code │ │
│ │ 2. Return to user │ │ 2. Execute in sandbox │ │
│ │ 3. User runs manually │ │ 3. Capture errors │ │
│ │ 4. User reports errors │ │ 4. Auto-fix and retry │ │
│ │ 5. Regenerate code │ │ 5. Return working code │ │
│ │ 6. Repeat until works... │ └─────────────────────────────┘ │
│ └─────────────────────────────┘ │
│ │
│ ❌ Multiple round-trips ✅ Self-healing in single execution │
│ ❌ User must debug ✅ Agent debugs automatically │
│ ❌ No runtime validation ✅ Full runtime validation │
│ ❌ Hope it works ✅ Know it works │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Location: shared/sandbox/
┌─────────────────────────────────────────────────────────────────────────────┐
│ PURPLE8 SANDBOX ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ SANDBOX MANAGER (Orchestrator) ║ │
│ ║ shared/sandbox/manager.py ║ │
│ ║ ║ │
│ ║ • Session lifecycle management ║ │
│ ║ • Resource quota enforcement ║ │
│ ║ • Container orchestration ║ │
│ ║ • Automatic cleanup ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │ │
│ ┌──────────────────────────┼──────────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │
│ │ CONTAINER POOL │ │ CODE EXECUTOR │ │ VIRTUAL FILESYSTEM│ │
│ │ container_pool │ │ executor.py │ │ filesystem.py │ │
│ │ │ │ │ │ │ │
│ │ • Pre-warmed │ │ • Multi-language │ │ • Secure paths │ │
│ │ • Docker lifecycle│ │ • Streaming out │ │ • Disk quotas │ │
│ │ • Multi-runtime │ │ • Timeout enforce │ │ • Change tracking │ │
│ │ • Idle recycling │ │ • Package install │ │ • File search │ │
│ └───────────────────┘ └───────────────────┘ └───────────────────┘ │
│ │ │ │ │
│ └──────────────────────────┼──────────────────────────┘ │
│ │ │
│ ▼ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ RESOURCE MANAGEMENT ║ │
│ ║ resources.py ║ │
│ ║ ║ │
│ ║ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ║ │
│ ║ │ CPU Limits │ │ Memory Lim │ │ Disk Quota │ │ Time Limits │ ║ │
│ ║ │ 0.5-4 cores │ │ 256MB-4GB │ │ 256MB-4GB │ │ 60s-600s │ ║ │
│ ║ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ ║ │
│ ║ ║ │
│ ║ Resource Presets: minimal() | standard() | heavy() ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
| Runtime | Docker Image | Use Case |
|---|---|---|
| Python 3.12 | python:3.12-slim |
Default for most projects |
| Python 3.11 | python:3.11-slim |
Legacy compatibility |
| Node.js 20 | node:20-slim |
JavaScript/TypeScript |
| Node.js 22 | node:22-slim |
Latest JS features |
| Go 1.22 | golang:1.22-alpine |
Go projects |
| Rust 1.75 | rust:1.75-slim |
Rust projects |
| Multi-lang | purple8/sandbox-multi:latest |
Mixed projects |
Location: shared/sandbox/manager.py
Central orchestrator for all sandbox operations:
from shared.sandbox import get_sandbox_manager, Language
# Get global sandbox manager
manager = await get_sandbox_manager()
# Create a session
session = await manager.create_session(
language=Language.PYTHON,
resource_limits=ResourceLimits.standard(),
user_id="user-123",
project_id="project-456",
)
# Execute code
result = await manager.execute_code(
session_id=session.id,
code="print('Hello, Purple8!')",
timeout_seconds=30,
)
print(result.stdout) # "Hello, Purple8!"
print(result.exit_code) # 0
# Cleanup
await manager.terminate_session(session.id)
Location: shared/sandbox/container_pool.py
Manages pre-warmed containers for instant startup:
from shared.sandbox import ContainerPool, ContainerConfig, RuntimeType
pool = ContainerPool(
min_pool_size=2, # Keep 2 warm containers per runtime
max_pool_size=10, # Maximum 10 total containers
idle_timeout_minutes=30,
)
# Acquire a container (instant if pre-warmed)
container = await pool.acquire(
config=ContainerConfig(runtime=RuntimeType.PYTHON_3_12),
session_id="session-123",
)
# Use container...
# Release back to pool (reused, not destroyed)
await pool.release(container.id)
Location: shared/sandbox/filesystem.py
Secure file operations with path traversal protection:
from shared.sandbox import VirtualFilesystem
fs = VirtualFilesystem(
root_path="/tmp/sandbox/session-123",
max_size_mb=1024, # 1GB limit
max_files=10000,
)
# Write files (creates directories automatically)
await fs.write_file("src/main.py", "print('hello')")
await fs.write_file("tests/test_main.py", "def test_main(): pass")
# Read files
content = await fs.read_file_text("src/main.py")
# List directory
files = await fs.list_directory("src", recursive=True)
# Search files
py_files = await fs.search("*.py")
# Get directory tree
tree = await fs.get_tree()
# {'type': 'directory', 'children': {'src': {...}, 'tests': {...}}}
# Path traversal is blocked
await fs.write_file("../../../etc/passwd", "evil") # Raises PermissionError
Location: shared/sandbox/executor.py
Multi-language code execution with streaming:
from shared.sandbox.executor import CodeExecutor, ExecutionRequest, Language
executor = CodeExecutor(container=container, filesystem=fs)
# Execute Python
result = await executor.execute(ExecutionRequest(
code="print('Hello')",
language=Language.PYTHON,
timeout_seconds=30,
))
# Execute with streaming output
async for chunk in executor.execute_streaming(request):
if chunk["type"] == "stdout":
print(chunk["data"], end="")
elif chunk["type"] == "stderr":
print(chunk["data"], end="", file=sys.stderr)
# Install packages
await executor.install_package("requests", Language.PYTHON)
await executor.install_package("express", Language.JAVASCRIPT)
Location: shared/sandbox/resources.py
Define resource constraints:
from shared.sandbox import ResourceLimits
# Presets
minimal = ResourceLimits.minimal() # 0.5 CPU, 256MB RAM, 60s timeout
standard = ResourceLimits.standard() # 1 CPU, 512MB RAM, 300s timeout
heavy = ResourceLimits.heavy() # 2 CPU, 2GB RAM, 600s timeout
# Custom limits
custom = ResourceLimits(
cpu_cores=1.5,
memory_mb=1024,
disk_mb=2048,
max_processes=100,
execution_timeout_seconds=120,
network_enabled=True,
)
# Convert to Docker config
docker_config = custom.to_docker_config()
# {'mem_limit': '1024m', 'cpus': 1.5, 'pids_limit': 100, ...}
Location: services/gateway/routers/sandbox.py
POST /api/sandbox/sessions
Create a new sandbox session
Body: { "language": "python", "resource_preset": "standard" }
Returns: { "session_id": "...", "container_id": "...", ... }
GET /api/sandbox/sessions
List all sessions (optional filters: user_id, state)
Returns: { "sessions": [...], "count": N }
GET /api/sandbox/sessions/{session_id}
Get session details
Returns: { "id": "...", "state": "active", ... }
DELETE /api/sandbox/sessions/{session_id}
Terminate a session
Returns: { "status": "terminated" }
POST /api/sandbox/sessions/{session_id}/execute
Execute code in session
Body: { "code": "...", "language": "python", "stream": false }
Returns: { "stdout": "...", "stderr": "...", "exit_code": 0 }
POST /api/sandbox/execute
Quick execution (temporary session)
Body: { "code": "...", "language": "python" }
Returns: { "stdout": "...", "exit_code": 0 }
GET /api/sandbox/sessions/{session_id}/files
List files in workspace
Returns: { "files": [...], "count": N }
GET /api/sandbox/sessions/{session_id}/files/{path}
Read file content
Returns: { "path": "...", "content": "..." }
PUT /api/sandbox/sessions/{session_id}/files/{path}
Write file
Body: { "content": "..." }
Returns: { "path": "...", "size_bytes": N }
POST /api/sandbox/sessions/{session_id}/packages
Install package
Body: { "package": "requests", "language": "python" }
Returns: { "status": "success", "stdout": "..." }
GET /api/sandbox/stats
Get sandbox system stats
Returns: { "active_sessions": N, "pool_stats": {...} }
The sandbox enables a self-debugging loop in the Builder pipeline:
class SelfDebuggingPipelineRunner:
async def execute_with_validation(self, agent_output: str) -> str:
# 1. Extract code from agent output
code_blocks = extract_code_blocks(agent_output)
# 2. Create sandbox session
session = await self.sandbox.create_session(Language.PYTHON)
try:
# 3. Write files to sandbox
for file in code_blocks:
await self.sandbox.write_file(
session.id,
file.path,
file.content
)
# 4. Execute and capture errors
result = await self.sandbox.execute_code(
session.id,
code="python main.py",
timeout_seconds=60,
)
# 5. If errors, send back for fixing
if result.exit_code != 0:
fix_prompt = f"""
The code failed with error:
{result.stderr}
Please fix the following code:
{agent_output}
"""
return await self.agent.run(fix_prompt)
# 6. Return validated code
return agent_output
finally:
await self.sandbox.terminate_session(session.id)
network_enabled=False)no-new-privileges security optionshared/sandbox/
├── __init__.py # Module exports
├── manager.py # SandboxManager - central orchestrator
├── container_pool.py # ContainerPool - Docker container lifecycle
├── executor.py # CodeExecutor - multi-language execution
├── filesystem.py # VirtualFilesystem - secure file operations
└── resources.py # ResourceLimits, ResourceMonitor, ResourceQuotaManager
The Memory and Learning System enables Builder to learn from interactions, remember user preferences, and apply learned patterns across sessions. This is a key Devin-like capability that makes Builder smarter over time.
┌─────────────────────────────────────────────────────────────────────────────┐
│ MEMORY AND LEARNING SYSTEM │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ STORAGE LAYER (Persistent) ║ │
│ ║ ║ │
│ ║ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ║ │
│ ║ │ PostgreSQL │ │ Redis │ │ Qdrant Builder │ ║ │
│ ║ │ (Primary) │ │ (Cache) │ │ (Vectors) │ ║ │
│ ║ │ │ │ │ │ │ ║ │
│ ║ │ • memories │ │ • Fast lookup │ │ • Embeddings │ ║ │
│ ║ │ • learnings │ │ • Session data │ │ • Semantic │ ║ │
│ ║ │ • sessions │ │ • TTL expiry │ │ search │ ║ │
│ ║ │ │ │ │ │ │ ║ │
│ ║ │ Port: 5432 │ │ Port: 6379 │ │ Port: 6335 │ ║ │
│ ║ └─────────────────┘ └─────────────────┘ └─────────────────┘ ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │ │
│ ┌──────────┴──────────┐ │
│ │ │ │
│ ▼ ▼ │
│ ╔═══════════════════════════════╗ ╔═══════════════════════════════════╗ │
│ ║ MEMORY STORE ║ ║ LEARNING ENGINE ║ │
│ ║ memory_store.py ║ ║ learning_engine.py ║ │
│ ║ ║ ║ ║ │
│ ║ • Store/retrieve memories ║ ║ • Extract patterns from feedback ║ │
│ ║ • Semantic search ║ ║ • Build confidence scores ║ │
│ ║ • Priority management ║ ║ • Apply learned rules ║ │
│ ║ • TTL-based expiration ║ ║ • Success/failure tracking ║ │
│ ╚═══════════════════════════════╝ ╚═══════════════════════════════════╝ │
│ │ │
│ ▼ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ CONTEXT MANAGER ║ │
│ ║ context_manager.py ║ │
│ ║ ║ │
│ ║ • Builds optimal context for agents ║ │
│ ║ • Retrieves relevant memories for current task ║ │
│ ║ • Applies learned patterns to agent prompts ║ │
│ ║ • Context window optimization (token limits) ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │ │
│ ▼ │
│ ╔═══════════════════════════════════════════════════════════════════════╗ │
│ ║ MEMORY MIXIN ║ │
│ ║ memory_mixin.py ║ │
│ ║ ║ │
│ ║ Adds memory capabilities to any BaseAgent: ║ │
│ ║ class MyAgent(MemoryMixin, BaseAgent): ║ │
│ ║ async def run(self, prompt, context): ║ │
│ ║ # Automatically enriched with memories ║ │
│ ║ enriched = await self.enrich_with_memory(prompt, context) ║ │
│ ║ ... ║ │
│ ╚═══════════════════════════════════════════════════════════════════════╝ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
| Type | Description | Example |
|---|---|---|
USER_PREFERENCE |
User’s coding style preferences | “User prefers TypeScript over JavaScript” |
CODE_PATTERN |
Recognized code patterns | “React hooks pattern: useEffect cleanup” |
CODE_SOLUTION |
Successful solutions | “Fixed CORS by adding middleware” |
CODE_FIX |
Bug fixes and corrections | “Added null check for undefined props” |
PROJECT_CONTEXT |
Project-specific information | “This project uses PostgreSQL 15” |
LEARNED_RULE |
Patterns extracted from feedback | “Always add error handling to async” |
SESSION_STATE |
Current session information | “Working on authentication module” |
Location: migrations/004_create_memory_tables.sql
-- Memories table: Primary storage for all memory types
CREATE TABLE IF NOT EXISTS memories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
type VARCHAR(50) NOT NULL, -- USER_PREFERENCE, CODE_PATTERN, etc.
scope VARCHAR(50) NOT NULL, -- global, project, session
priority INTEGER DEFAULT 0,
content TEXT NOT NULL,
data JSONB DEFAULT '{}',
embedding VECTOR(384), -- For semantic search (pgvector)
user_id VARCHAR(255),
project_id VARCHAR(255),
session_id VARCHAR(255),
tags TEXT[] DEFAULT '{}',
language VARCHAR(50),
framework VARCHAR(100),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE,
access_count INTEGER DEFAULT 0,
last_accessed_at TIMESTAMP WITH TIME ZONE
);
-- Learnings table: Patterns extracted from feedback
CREATE TABLE IF NOT EXISTS learnings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
source VARCHAR(100) NOT NULL, -- feedback, correction, success, failure
feedback_type VARCHAR(50),
pattern_type VARCHAR(100) NOT NULL,
pattern_key VARCHAR(255) NOT NULL,
pattern_value JSONB NOT NULL,
confidence FLOAT DEFAULT 0.5,
evidence_count INTEGER DEFAULT 1,
evidence JSONB DEFAULT '[]',
agent_name VARCHAR(100),
original_output TEXT,
corrected_output TEXT,
user_id VARCHAR(255),
project_id VARCHAR(255),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Sessions table: Active session state
CREATE TABLE IF NOT EXISTS sessions (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) UNIQUE NOT NULL,
user_id VARCHAR(255),
project_id VARCHAR(255),
project_name VARCHAR(255),
current_phase VARCHAR(50),
current_agent VARCHAR(100),
pipeline_state JSONB DEFAULT '{}',
agent_outputs JSONB DEFAULT '{}',
conversation JSONB DEFAULT '[]',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
last_activity_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CRITICAL: Purple8 Builder and Purple8 Chat use separate Qdrant instances to avoid data conflicts:
| Product | Qdrant Instance | Port | Collection | Purpose |
|---|---|---|---|---|
| Purple8 Chat | 8-qdrant |
6333 | purple8_documents |
Document search, RAG |
| Purple8 Builder | 8-qdrant-builder |
6335 | builder_memories |
Memory & learning vectors |
This separation ensures:
Location: shared/agents/memory/memory_store.py
from shared.agents.memory import MemoryStore, Memory, MemoryType, MemoryScope
# Initialize store (uses PostgreSQL, Redis, Qdrant-Builder)
store = MemoryStore()
await store.initialize()
# Store a memory
memory = Memory(
type=MemoryType.USER_PREFERENCE,
scope=MemoryScope.GLOBAL,
content="User prefers async/await over callbacks",
priority=10,
user_id="user-123"
)
await store.store(memory)
# Retrieve memories
memories = await store.search(
query="coding preferences",
user_id="user-123",
limit=10
)
# Semantic search (uses Qdrant vectors)
similar = await store.semantic_search(
embedding=embedding_vector,
limit=5
)
Location: shared/agents/memory/learning_engine.py
from shared.agents.memory import LearningEngine, LearningSource
engine = LearningEngine(memory_store=store)
await engine.initialize()
# Learn from user feedback
await engine.learn_from_feedback(
agent_name="ArchitectureAgent",
original_output="Use MongoDB",
feedback="We're a PostgreSQL shop",
feedback_type="correction"
)
# Learn from successful outcome
await engine.learn_from_success(
agent_name="FrontendAgent",
output=successful_code,
context={"language": "TypeScript", "framework": "React"}
)
# Apply learnings to new prompt
enhanced_prompt = await engine.apply_learnings(
prompt="Generate database schema",
agent_name="DatabaseAgent",
context=context
)
Location: shared/agents/memory/context_manager.py
from shared.agents.memory import ContextManager
manager = ContextManager(
memory_store=store,
learning_engine=engine,
max_tokens=8000 # Context window limit
)
# Build optimal context for an agent
context = await manager.build_context(
agent_name="BackendAgent",
prompt="Implement user authentication",
user_id="user-123",
project_id="proj-456"
)
# Context includes:
# - Relevant memories
# - Applied learnings
# - User preferences
# - Project context
# - Optimized for token limit
Location: shared/agents/memory/memory_mixin.py
from shared.agents.base_agent import BaseAgent
from shared.agents.memory import MemoryMixin
class SmartAgent(MemoryMixin, BaseAgent):
"""Agent with built-in memory capabilities"""
async def run(self, prompt: str, context: dict = None):
# Automatically enrich with memories
enriched = await self.enrich_with_memory(prompt, context)
# Execute with memory-enhanced context
result = await self._generate(enriched["prompt"])
# Store successful patterns
if context.get("feedback_positive"):
await self.remember_success(result, context)
return result
Location: services/gateway/routers/memory.py
GET /api/memory/
List all memories (with filters)
Query: ?user_id=...&type=...&scope=...&limit=50
Returns: { "memories": [...], "count": N }
POST /api/memory/
Store a new memory
Body: { "type": "USER_PREFERENCE", "content": "...", ... }
Returns: { "id": "...", "status": "stored" }
GET /api/memory/{memory_id}
Get specific memory by ID
Returns: { "id": "...", "type": "...", "content": "...", ... }
DELETE /api/memory/{memory_id}
Delete a memory
Returns: { "status": "deleted" }
POST /api/memory/search
Search memories (keyword + semantic)
Body: { "query": "...", "limit": 10 }
Returns: { "results": [...] }
GET /api/memory/learnings
List learned patterns
Query: ?agent_name=...&confidence_min=0.7
Returns: { "learnings": [...] }
POST /api/memory/learn
Submit feedback for learning
Body: { "agent": "...", "output": "...", "feedback": "..." }
Returns: { "learned": true, "pattern_id": "..." }
GET /api/memory/stats
Get memory system statistics
Returns: { "total_memories": N, "by_type": {...}, "learnings": N }
shared/agents/memory/
├── __init__.py # Module exports
├── memory_store.py # MemoryStore - CRUD operations
├── learning_engine.py # LearningEngine - pattern extraction
├── context_manager.py # ContextManager - context building
├── memory_mixin.py # MemoryMixin - agent integration
└── storage_backend.py # StorageBackend - PostgreSQL/Redis/Qdrant
migrations/
└── 004_create_memory_tables.sql # Database schema
🔗 Part of: Purple8 Development Environment Related: Purple8 IDE · Purple8 Copilot · Purple8 Sandbox
The Proactive UI System makes Builder’s interface anticipate user needs, provide intelligent suggestions, and show real-time insights. This creates a Devin-like interactive experience.
┌─────────────────────────────────────────────────────────────────────────────┐
│ PROACTIVE UI SYSTEM │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ FRONTEND COMPONENTS │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ SuggestionBar │ │ InsightsPanel │ │ ContextPreview │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • Quick actions │ │ • Code quality │ │ • Memory items │ │ │
│ │ │ • Suggestions │ │ • Complexity │ │ • Learnings │ │ │
│ │ │ • Shortcuts │ │ • Improvements │ │ • Session state │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ MemoryPanel │ │ PlanViewer │ │ DebugLogs │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • View memories │ │ • Current plan │ │ • Execution log │ │ │
│ │ │ • Search │ │ • Step progress │ │ • Debug details │ │ │
│ │ │ • Stats │ │ • Edit steps │ │ • Errors │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────┴──────────┐ │
│ │ Vuex Store │ │
│ │ proactive/index.js │ │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ API LAYER │ │
│ │ │ │
│ │ proactiveApi.js memoryApi.js plannerApi.js debugApi.js │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ BACKEND ENDPOINTS │ │
│ │ │ │
│ │ /api/proactive/* /api/memory/* /api/planner/* /api/debug/* │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Provides intelligent quick actions and suggestions based on current context:
<template>
<div class="suggestion-bar">
<div v-for="suggestion in suggestions" :key="suggestion.id"
class="suggestion-chip" @click="applySuggestion(suggestion)">
<span class="icon"></span>
<span class="text"></span>
<span class="confidence" v-if="suggestion.confidence">
%
</span>
</div>
</div>
</template>
Shows real-time analysis of generated code:
<template>
<div class="insights-panel">
<div class="insight-card" v-for="insight in insights">
<h4></h4>
<div class="metrics">
<span class="score">/100</span>
<span class="label"></span>
</div>
<ul class="recommendations">
<li v-for="rec in insight.recommendations"></li>
</ul>
</div>
</div>
</template>
Displays and manages memories:
<template>
<div class="memory-panel">
<div class="memory-stats">
<span> memories</span>
<span> learnings</span>
</div>
<div class="memory-search">
<input v-model="searchQuery" placeholder="Search memories..." />
</div>
<div class="memory-list">
<MemoryCard v-for="memory in filteredMemories"
:key="memory.id" :memory="memory" />
</div>
</div>
</template>
Location: frontend-vue/src/views/InteractiveBuilderView.vue
The main Builder view integrates all proactive components:
<template>
<div class="interactive-builder">
<!-- Main content area -->
<div class="builder-content">
<!-- Input and output panels -->
</div>
<!-- Proactive sidebar with tabs -->
<div class="proactive-sidebar">
<div class="tab-header">
<button @click="activeTab = 'suggestions'"
:class="{ active: activeTab === 'suggestions' }">
💡 Suggestions
</button>
<button @click="activeTab = 'insights'"
:class="{ active: activeTab === 'insights' }">
📊 Insights
</button>
<button @click="activeTab = 'plan'"
:class="{ active: activeTab === 'plan' }">
📋 Plan
</button>
<button @click="activeTab = 'memory'"
:class="{ active: activeTab === 'memory' }">
🧠 Memory
</button>
<button @click="activeTab = 'debug'"
:class="{ active: activeTab === 'debug' }">
🐛 Debug
</button>
</div>
<div class="tab-content">
<SuggestionBar v-if="activeTab === 'suggestions'" />
<InsightsPanel v-if="activeTab === 'insights'" />
<PlanViewer v-if="activeTab === 'plan'" />
<MemoryPanel v-if="activeTab === 'memory'" />
<DebugLogs v-if="activeTab === 'debug'" />
</div>
</div>
</div>
</template>
frontend-vue/src/
├── components/
│ ├── proactive/
│ │ ├── SuggestionBar.vue # Quick action suggestions
│ │ ├── InsightsPanel.vue # Code analysis insights
│ │ └── ContextPreview.vue # Context window preview
│ ├── memory/
│ │ └── MemoryPanel.vue # Memory display & search
│ ├── planner/
│ │ └── PlanViewer.vue # Plan visualization
│ └── debug/
│ └── DebugLogs.vue # Debug information
├── api/
│ ├── proactiveApi.js # Proactive API calls
│ ├── memoryApi.js # Memory API calls
│ ├── plannerApi.js # Planner API calls
│ └── debugApi.js # Debug API calls
├── store/
│ ├── modules/
│ │ ├── proactive/
│ │ │ └── index.js # Proactive state management
│ │ └── memory/
│ │ └── index.js # Memory state management
│ └── index.js # Root store
└── views/
└── InteractiveBuilderView.vue # Main builder view
Purple8 Builder requires the following infrastructure services:
# docker-compose.yml - Builder-specific services
services:
# ==========================================================================
# SHARED INFRASTRUCTURE (Used by all products)
# ==========================================================================
postgres:
image: postgres:15-alpine
container_name: 8-postgres
ports: ["5432:5432"]
volumes: [postgres_data:/var/lib/postgresql/data]
environment:
POSTGRES_USER: 8
POSTGRES_PASSWORD: 8_dev_password
POSTGRES_DB: 8
redis:
image: redis:7-alpine
container_name: 8-redis
ports: ["6379:6379"]
volumes: [redis_data:/data]
rabbitmq:
image: rabbitmq:3-management
container_name: 8-rabbitmq
ports: ["5672:5672", "15672:15672"]
volumes: [rabbitmq_data:/var/lib/rabbitmq]
# ==========================================================================
# PURPLE8 CHAT - Vector Database (Documents/Search)
# ==========================================================================
qdrant:
image: qdrant/qdrant:latest
container_name: 8-qdrant
ports: ["6333:6333", "6334:6334"]
volumes: [qdrant_data:/qdrant/storage]
# ==========================================================================
# PURPLE8 BUILDER - Vector Database (Memory/Learning System)
# Separate instance to avoid conflicts with Chat product
# ==========================================================================
qdrant-builder:
image: qdrant/qdrant:latest
container_name: 8-qdrant-builder
ports: ["6335:6333", "6336:6334"] # Different host ports
volumes: [qdrant_builder_data:/qdrant/storage]
minio:
image: minio/minio:latest
container_name: 8-minio
ports: ["9000:9000", "9001:9001"]
volumes: [minio_data:/data]
command: server /data --console-address ":9001"
volumes:
postgres_data:
redis_data:
rabbitmq_data:
qdrant_data:
qdrant_builder_data: # Dedicated volume for Builder
minio_data:
| Service | Container | Host Port | Purpose |
|---|---|---|---|
| PostgreSQL | 8-postgres | 5432 | Primary database |
| Redis | 8-redis | 6379 | Caching, sessions |
| RabbitMQ | 8-rabbitmq | 5672, 15672 | Message queue |
| Qdrant (Chat) | 8-qdrant | 6333, 6334 | Chat document vectors |
| Qdrant (Builder) | 8-qdrant-builder | 6335, 6336 | Builder memory vectors |
| MinIO | 8-minio | 9000, 9001 | Object storage |
| Penpot UI | 8-penpot-frontend | 9002 | Design platform |
| Penpot Backend | 8-penpot-backend | 6060 | Penpot API |
# .env file - Builder-specific variables
# Database (shared)
DATABASE_URL=postgresql://8:8_dev_password@localhost:5432/8
POSTGRES_USER=8
POSTGRES_PASSWORD=8_dev_password
POSTGRES_DB=8
# Redis (shared)
REDIS_URL=redis://localhost:6379
# Qdrant - PRODUCT SEPARATION
QDRANT_URL=http://localhost:6333 # For Purple8 Chat
QDRANT_BUILDER_URL=http://localhost:6335 # For Purple8 Builder
# LLM Providers
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_API_KEY=...
# Ollama (optional)
OLLAMA_BASE_URL=http://localhost:11434
# Start all Builder-required services
docker-compose up -d postgres redis qdrant-builder
# Start Penpot design platform (optional but recommended)
docker-compose -f docker-compose.penpot.yml up -d
# Verify services are running
docker-compose ps
# Check Builder's Qdrant health
curl http://localhost:6335/collections
# Expected: {"result":{"collections":[]},"status":"ok",...}
# Check Penpot health
curl -s http://localhost:9002 | head -1
# Expected: <!DOCTYPE html>
# Apply database migrations
docker exec -i 8-postgres psql -U 8 -d 8 < migrations/004_create_memory_tables.sql
purple8-platform/
├── services/ # Backend services
│ ├── gateway/ # FastAPI API Gateway (port 8000)
│ │ ├── main.py # App initialization, CORS, routers
│ │ └── routers/ # Feature routers
│ │ ├── purple8.py # Chat endpoints
│ │ ├── pipeline.py # Pipeline endpoints
│ │ ├── builder.py # Builder endpoints
│ │ ├── sandbox.py # Sandbox endpoints
│ │ └── memory.py # Memory endpoints (NEW)
│ │
│ ├── smart_orchestrator.py # Agent selection & workflow composition
│ ├── pipeline_runner.py # 4-layer pipeline execution
│ ├── project_analyzer.py # Project characteristics analysis
│ └── purple8/ # Purple8 Chat product
│ ├── moe_orchestrator.py # Multi-model selection
│ ├── chat_manager.py # Conversation state
│ └── document_parser.py # Multi-format document processing
│
├── shared/ # Shared modules
│ ├── agents/ # Agent system (46 agents)
│ │ ├── base_agent.py # BaseAgent pattern (all agents inherit)
│ │ ├── four_layer_mixin.py # 4-layer capabilities mixin
│ │ ├── registry.py # Agent contracts & dependencies
│ │ │
│ │ ├── core/ # Core SDLC agents (12)
│ │ ├── qa/ # QA agents (11)
│ │ ├── aiml/ # AI/ML agents (17)
│ │ └── specialized/ # Domain agents (6)
│ │
│ ├── layers/ # 4-Layer Architecture
│ │ ├── purpose.py # L1: Purpose (immutable strategy)
│ │ ├── memory.py # L2: Memory (persistent state)
│ │ ├── supervisor.py # L4: Supervisor (loop controller)
│ │ ├── session_persistence.py # Session recovery
│ │ ├── validation.py # Output validation
│ │ └── parallel_executor.py # Parallel execution
│ │
│ ├── sandbox/ # Code Execution Sandbox (NEW)
│ │ ├── __init__.py # Module exports
│ │ ├── manager.py # SandboxManager orchestrator
│ │ ├── container_pool.py # Docker container pool
│ │ ├── executor.py # Multi-language execution
│ │ ├── filesystem.py # Virtual filesystem
│ │ └── resources.py # Resource limits & monitoring
│ │
│ ├── utils/ # Utility modules
│ │ └── diagram_generator.py # Diagrams library wrapper (NEW)
│ │
│ └── services/ # Shared services
│ ├── search/ # Purple8 Search (RAG, keyword, hybrid)
│ └── penpot_integration.py # Penpot design platform integration (NEW)
│
├── frontend-vue/ # Vue 3 frontend (port 8080)
│ ├── src/
│ │ ├── views/
│ │ │ ├── BuilderPage.vue # Builder UI
│ │ │ ├── InteractiveBuilderView.vue # Interactive builder with diagrams
│ │ │ └── ChatPage.vue # Chat UI
│ │ ├── utils/
│ │ │ └── visualization.js # Diagram rendering utilities
│ │ └── components/
│ │ ├── visualizations/ # Visualization components (NEW)
│ │ │ ├── DiagramViewer.vue # PNG/SVG diagram viewer
│ │ │ └── MermaidDiagram.vue # Legacy Mermaid (deprecated)
│ │ ├── proactive/ # Proactive UI components
│ │ │ ├── SuggestionBar.vue
│ │ │ ├── InsightsPanel.vue
│ │ │ └── ContextPreview.vue
│ │ ├── memory/ # Memory UI components
│ │ │ └── MemoryPanel.vue
│ │ ├── planner/ # Planner UI components
│ │ │ └── PlanViewer.vue
│ │ └── debug/ # Debug UI components
│ │ └── DebugLogs.vue
│ │
│ └── public/
│
├── migrations/ # Database migrations
│ └── 004_create_memory_tables.sql # Memory system schema
│
├── docs/ # Documentation
│ ├── BUILDER_COMPLETE_ARCHITECTURE.md # This document
│ ├── purple8/
│ │ ├── FOUR_LAYER_ARCHITECTURE.md
│ │ └── PIPELINE_FLOW.md
│ └── products/
│ └── builder/
│ └── README.md
│
├── docker-compose.yml # Infrastructure services
├── docker-compose.penpot.yml # Penpot design platform (NEW)
├── requirements.txt # Python dependencies
└── start.py # Full stack startup
shared/agents/
├── base_agent.py # BaseAgent pattern
├── four_layer_mixin.py # 4-layer capabilities
├── registry.py # Agent contracts
├── llm_factory.py # Tier-based model selection (UPDATED)
│
├── memory/ # Memory System (Week 7)
│ ├── __init__.py # Module exports
│ ├── memory_store.py # MemoryStore - CRUD operations
│ ├── learning_engine.py # LearningEngine - pattern extraction
│ ├── context_manager.py # ContextManager - context building
│ ├── memory_mixin.py # MemoryMixin - agent integration
│ └── storage_backend.py # StorageBackend - PostgreSQL/Redis/Qdrant
│
├── core/ # Core SDLC agents (12)
│ ├── ideation_agent.py # Tier 1 model
│ ├── design_agent.py # Tier 1 model, screen_navigation output
│ ├── architecture_agent.py # Tier 1 model, Diagrams library integration
│ ├── database_agent.py # Tier 1 model, ERD diagram generation
│ ├── api_development_agent.py # Tier 1 model
│ ├── frontend_development_agent.py # Tier 1 model
│ ├── backend_development_agent.py # Tier 1 model
│ └── infrastructure_development_agent.py # Tier 1 model
│
├── qa/ # QA agents (11)
│ ├── unittest_agent.py
│ ├── integration_test_agent.py
│ ├── api_test_agent.py
│ ├── load_test_agent.py
│ ├── sit_agent.py
│ └── uat_agent.py
│
├── aiml/ # AI/ML agents (17)
│ ├── machine_learning_agent.py
│ ├── mlops_agent.py
│ └── ...
│
└── specialized/ # Domain agents (6)
├── mobile_agent.py
├── devops_agent.py
├── security_qa_agent.py
└── ...
┌─────────────────────────────────────────────────────────────────────────────┐
│ COMPLETE DATA FLOW │
└─────────────────────────────────────────────────────────────────────────────┘
1. USER REQUEST
┌────────────────────────────────────────────────────────────────────────┐
│ POST /api/builder/execute │
│ { "prompt": "Build a task management app with real-time updates" } │
└────────────────────────────────────────────────────────────────────────┘
│
▼
2. API GATEWAY (services/gateway/routers/builder.py)
┌────────────────────────────────────────────────────────────────────────┐
│ @router.post("/execute") │
│ async def execute_pipeline(request: BuilderRequest): │
│ runner = FourLayerPipelineRunner() │
│ result = await runner.run(request.prompt) │
│ return result │
└────────────────────────────────────────────────────────────────────────┘
│
▼
3. PIPELINE RUNNER (services/pipeline_runner.py)
┌────────────────────────────────────────────────────────────────────────┐
│ class FourLayerPipelineRunner: │
│ async def run(self, prompt): │
│ # Create L1 Purpose │
│ purpose = await self._create_purpose(prompt) │
│ # Initialize L2 Memory │
│ memory = SharedMemoryStore(purpose=purpose) │
│ # Get workflow from SmartOrchestrator │
│ workflow = await self.orchestrator.compose_workflow(prompt) │
│ # Initialize L4 Supervisor │
│ supervisor = SupervisorAgent(memory=memory) │
│ # Run │
│ return await supervisor.run() │
└────────────────────────────────────────────────────────────────────────┘
│
▼
4. SMART ORCHESTRATOR (services/smart_orchestrator.py)
┌────────────────────────────────────────────────────────────────────────┐
│ # Analyze project │
│ characteristics = await analyzer.analyze(prompt) │
│ # -> ProjectType.WEB_APP, has_realtime=True │
│ │
│ # Select agents │
│ agents = foundational_agents + [ │
│ "observability_agent", # Real-time needs monitoring │
│ ] │
│ │
│ # Sort by dependencies │
│ ordered = topological_sort(agents) │
└────────────────────────────────────────────────────────────────────────┘
│
▼
5. L4 SUPERVISOR LOOP (shared/layers/supervisor.py)
┌────────────────────────────────────────────────────────────────────────┐
│ while not purpose_satisfied: │
│ # Get next task from L2 queue │
│ task = memory.task_queue.get_next() │
│ │
│ # Execute L3 agent │
│ agent = agents[task.agent] │
│ result = await agent.run(task.description, context) │
│ │
│ # Store completion in L2 │
│ memory.complete_task(task.id, result) │
│ │
│ # Decide next action │
│ decision = self._decide(memory, purpose) │
│ # -> CONTINUE | REWORK | PARALLEL | TERMINATE │
└────────────────────────────────────────────────────────────────────────┘
│
▼
6. L3 AGENT EXECUTION (shared/agents/core/*.py)
┌────────────────────────────────────────────────────────────────────────┐
│ class ArchitectureAgent(FourLayerMixin, BaseAgent): │
│ async def run(self, prompt, context): │
│ # Get L1 purpose context │
│ purpose = self.get_purpose_context() │
│ # Get L2 handoff from previous agents │
│ handoff = self.get_handoff_summary() │
│ │
│ # Generate architecture using LLM │
│ result = await self.llm.generate( │
│ system_prompt + purpose + handoff + prompt │
│ ) │
│ │
│ # Store artifacts in L2 │
│ self.store_document_artifact("architecture.md", result) │
│ │
│ return result │
└────────────────────────────────────────────────────────────────────────┘
│
▼
7. RESPONSE
┌────────────────────────────────────────────────────────────────────────┐
│ { │
│ "status": "success", │
│ "project_id": "proj_abc123", │
│ "artifacts": [ │
│ {"name": "requirements.md", "type": "document"}, │
│ {"name": "architecture.json", "type": "document"}, │
│ {"name": "src/main.py", "type": "code"}, │
│ {"name": "tests/test_main.py", "type": "test"}, │
│ {"name": "Dockerfile", "type": "infrastructure"}, │
│ ... │
│ ], │
│ "agents_executed": ["ideation", "design", "architecture", ...], │
│ "duration_ms": 45000 │
│ } │
└────────────────────────────────────────────────────────────────────────┘
# .env file (project root)
# LLM Providers (at least one required)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_API_KEY=...
# Ollama (optional, for local/free models)
OLLAMA_BASE_URL=http://localhost:11434
# Database
POSTGRES_USER=purple8
POSTGRES_PASSWORD=purple8_dev_password
POSTGRES_DB=purple8
# Redis
REDIS_URL=redis://localhost:6379
# Qdrant (Vector DB for RAG)
QDRANT_HOST=localhost
QDRANT_PORT=6333
services:
postgres:
image: postgres:15
ports: ["5432:5432"]
environment:
POSTGRES_USER: purple8
POSTGRES_PASSWORD: purple8_dev_password
POSTGRES_DB: purple8
redis:
image: redis:7
ports: ["6379:6379"]
rabbitmq:
image: rabbitmq:3-management
ports: ["5672:5672", "15672:15672"]
qdrant:
image: qdrant/qdrant
ports: ["6333:6333"]
minio:
image: minio/minio
ports: ["9000:9000", "9001:9001"]
# 1. Start infrastructure
docker-compose up -d postgres redis rabbitmq qdrant minio
# 2. Start Penpot design platform (for Design Agent wireframes)
docker-compose -f docker-compose.penpot.yml up -d
# 3. Start backend
python3 -m uvicorn services.gateway.main:app --reload --port 8000
# 4. Start frontend
cd frontend-vue && npm run serve
# OR use the unified start script
python3 start.py
POST /api/builder/execute
Execute full pipeline from prompt
Body: { "prompt": "...", "options": {...} }
Returns: { "status": "...", "artifacts": [...] }
POST /api/builder/analyze
Analyze project without execution
Body: { "prompt": "..." }
Returns: { "characteristics": {...}, "recommended_agents": [...] }
GET /api/builder/status/{project_id}
Get pipeline execution status
Returns: { "phase": "...", "progress": 0.75, "current_agent": "..." }
GET /api/builder/artifacts/{project_id}
Get generated artifacts
Returns: { "artifacts": [...] }
GET /api/agents/list
List all available agents
Returns: { "agents": [...] }
GET /api/agents/{agent_id}/contract
Get agent contract specification
Returns: { "inputs": [...], "outputs": [...], "dependencies": [...] }
POST /api/agents/{agent_id}/execute
Execute single agent
Body: { "prompt": "...", "context": {...} }
Returns: { "output": "...", "artifacts": [...] }
┌─────────────────────────────────────────────────────────────────────────────┐
│ PRODUCTION DEPLOYMENT │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ CloudFlare │────▶│ Load Balancer │────▶│ API Gateway │ │
│ │ (CDN/WAF) │ │ (nginx) │ │ (FastAPI) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │ │
│ ┌───────────────────────────────┼─────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ PostgreSQL │ │ Redis │ │ RabbitMQ │ │
│ │ (Primary) │ │ (Cache) │ │ (Queue) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Qdrant │ │ MinIO │ │ Prometheus │ │
│ │ (Vector DB) │ │ (Object Store) │ │ + Grafana │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: purple8-builder
spec:
replicas: 3
selector:
matchLabels:
app: purple8-builder
template:
spec:
containers:
- name: api
image: purple8/builder:latest
ports:
- containerPort: 8000
env:
- name: OPENAI_API_KEY
valueFrom:
secretKeyRef:
name: llm-secrets
key: openai-key
Purple8 Builder is a complete AI software development framework that:
| Feature | Description | Location |
|---|---|---|
| Diagrams Library | Python-based architecture & ERD diagram generation (replaces Mermaid) | shared/utils/diagram_generator.py |
| DiagramViewer UI | Vue component for PNG/SVG diagram display with zoom, fullscreen, download | frontend-vue/src/components/visualizations/DiagramViewer.vue |
| Penpot Integration | Self-hosted open-source design platform for wireframes | shared/services/penpot_integration.py, docker-compose.penpot.yml |
| Tier-Based Models | Critical agents (Architecture, Design, Development) use premium models | shared/agents/llm_factory.py |
| Mermaid Deprecated | Legacy Mermaid diagrams replaced with Diagrams library | frontend-vue/src/utils/visualization.js |
| Week | Feature | Status | Location |
|---|---|---|---|
| 1 | Code Execution Sandbox | ✅ Complete | shared/sandbox/ |
| 2 | Self-Debugging Loop | ✅ Complete | shared/sandbox/executor.py |
| 3 | Structured Planning | ✅ Complete | shared/layers/planner.py |
| 4 | Context Optimization (Basic) | ✅ Complete | shared/layers/context_optimizer.py |
| 5 | Tool System | ✅ Complete | shared/tools/ |
| 6 | Proactive UI | ✅ Complete | frontend-vue/src/components/proactive/ |
| 7 | Memory & Learning | ✅ Complete | shared/agents/memory/ |
| 8 | Live Preview | ✅ Complete | shared/preview/, services/gateway/routers/preview.py |
| 9 | Git & PR Automation | ✅ Complete | shared/git/, services/gateway/routers/git.py |
| 9.5 | CoT Streaming | ✅ Complete | shared/agents/cot_mixin.py, services/gateway/routers/cot.py |
| 10 | Context Optimization V2 | ✅ Complete | shared/context/ |
Real-time application preview with hot module replacement:
# shared/preview/dev_server.py
from shared.preview import DevServerManager, PreviewSession
# Start dev server for generated code
manager = DevServerManager(workspace_path="/tmp/projects/my-app")
session = await manager.start_server(
framework="react", # react, vue, fastapi, flask
port=3000
)
# Access live preview
print(f"Preview at: {session.url}") # http://localhost:3000
Components:
shared/preview/dev_server.py - Dev server management (npm, vite, uvicorn)shared/preview/port_proxy.py - Dynamic port allocation and proxyingshared/preview/hot_reload.py - File watcher with HMR supportservices/gateway/routers/preview.py - REST API endpointsfrontend-vue/src/components/preview/PreviewPanel.vue - Embedded preview iframeLLM-powered Git operations and GitHub integration:
# shared/git/git_agent.py
from shared.git import GitAgent, GitHubService
# Local git operations with smart commit messages
git = GitAgent(repo_path="/path/to/repo")
message = await git.generate_commit_message(staged_changes)
# Returns: "feat(auth): implement JWT token refresh with Redis caching"
# GitHub PR automation
github = GitHubService(token=os.getenv("GITHUB_TOKEN"))
pr = await github.create_pull_request(
repo="org/repo",
title="feat: Add user authentication",
body=await github.generate_pr_description(commits),
head="feature/auth",
base="main"
)
Endpoints (26 total via services/gateway/routers/git.py):
POST /api/git/commit - Smart commit with LLM-generated messagePOST /api/git/branches - Create feature branchesPOST /api/git/pull-requests - Create PRs with auto-generated descriptionsGET /api/git/pull-requests/{id}/status - CI/CD status monitoringPOST /api/git/pull-requests/{id}/review - LLM-assisted code reviewReal-time streaming of agent reasoning for transparency:
# shared/agents/cot_mixin.py
from shared.agents.cot_mixin import CoTMixin
class ArchitectureAgent(CoTMixin, BaseAgent):
async def run(self, prompt: str, context: Dict) -> str:
# Stream reasoning steps in real-time
async for step in self.stream_cot_reasoning(prompt, style="architecture"):
yield step # {"step": 1, "thought": "Analyzing requirements...", ...}
# Generate final output
enhanced_prompt = await self.wrap_with_cot(prompt, style="architecture")
return await self.llm.generate(enhanced_prompt)
CoT Styles:
structured - Step-by-step logical breakdownfreeform - Natural exploratory thinkingdebug - Root cause analysis for errorsarchitecture - System design reasoningsecurity - Threat modeling and risk assessmentcode_review - Quality and best practices analysisFrontend: frontend-vue/src/components/cot/CoTStreamPanel.vue displays animated reasoning steps.
Advanced context window management with persistent caching:
# shared/context/context_optimizer.py
from shared.context import ContextOptimizer, create_context_optimizer
optimizer = create_context_optimizer(
workspace_path="/path/to/project",
model_name="gpt-4",
max_tokens=8000
)
# Initialize persistent storage (PostgreSQL + Redis + Qdrant)
await optimizer.init_storage()
# Optimize context for a task
plan = await optimizer.optimize_context(
task_description="Fix the authentication bug in login.py",
task_type="bug_fix",
focus_files=["src/auth/login.py"]
)
# Get formatted context for LLM
context_str = optimizer.format_context_for_prompt(plan)
print(f"Selected {len(plan.files_included)} files, {plan.total_tokens} tokens")
Storage Layer (shared/context/storage.py):
Key Features:
# Start Builder infrastructure (PostgreSQL, Redis, Builder's Qdrant)
docker-compose up -d postgres redis qdrant-builder
# Start Penpot design platform
docker-compose -f docker-compose.penpot.yml up -d
# Apply migrations
docker exec -i 8-postgres psql -U 8 -d 8 < migrations/004_create_memory_tables.sql
# Start backend
python3 -m uvicorn services.gateway.main:app --reload --port 8000
# Start frontend
cd frontend-vue && npm run serve
| Resource | Location |
|---|---|
| 4-Layer Architecture | docs/purple8/FOUR_LAYER_ARCHITECTURE.md |
| Pipeline Flow | docs/purple8/PIPELINE_FLOW.md |
| Agent Registry | shared/agents/registry.py |
| Smart Orchestrator | services/smart_orchestrator.py |
| Pipeline Runner | services/pipeline_runner.py |
| API Gateway | services/gateway/main.py |
| Sandbox Manager | shared/sandbox/manager.py |
| Memory Store | shared/agents/memory/memory_store.py |
| Learning Engine | shared/agents/memory/learning_engine.py |
| Memory API | services/gateway/routers/memory.py |
| Proactive UI | frontend-vue/src/components/proactive/ |
| Memory UI | frontend-vue/src/components/memory/MemoryPanel.vue |
| Diagram Generator | shared/utils/diagram_generator.py |
| DiagramViewer UI | frontend-vue/src/components/visualizations/DiagramViewer.vue |
| Penpot Integration | shared/services/penpot_integration.py |
| Penpot Docker | docker-compose.penpot.yml |
| Tier-Based Models | shared/agents/llm_factory.py |
| Live Preview | shared/preview/, services/gateway/routers/preview.py |
| Git Agent | shared/git/git_agent.py |
| GitHub Service | shared/git/github_service.py |
| Git API | services/gateway/routers/git.py |
| CoT Mixin | shared/agents/cot_mixin.py |
| CoT API | services/gateway/routers/cot.py |
| CoT UI | frontend-vue/src/components/cot/CoTStreamPanel.vue |
| Context Optimizer | shared/context/context_optimizer.py |
| Context Storage | shared/context/storage.py |
| Context API | services/gateway/routers/context.py |
| Variable | Default | Product | Purpose |
|---|---|---|---|
DATABASE_URL |
postgresql://8:8_dev_password@localhost:5432/8 |
All | PostgreSQL connection |
REDIS_URL |
redis://localhost:6379 |
All | Redis connection |
QDRANT_URL |
http://localhost:6333 |
Chat | Chat vector DB |
QDRANT_BUILDER_URL |
http://localhost:6335 |
Builder | Builder vector DB |
PENPOT_BASE_URL |
http://localhost:9002 |
Builder | Penpot design UI |
OPENAI_API_KEY |
- | All | OpenAI LLM |
ANTHROPIC_API_KEY |
- | All | Anthropic LLM |
GOOGLE_API_KEY |
- | All | Google LLM |
GITHUB_TOKEN |
- | Builder | GitHub API for PR automation |
Last Updated: December 29, 2025
Version: 5.1.0