Smart Assets Agentic Build Framework

**Status:** Pre‑alpha | **Architecture:** Agenctic Build Server Leveraging Open & Proprietary LLMs

Views6
PublishedJan 14, 2026

Loading actions...

5 minBeginnerpromptSingle file

Skill content

Main instructions and any bundled files for this skill.

markdown

Smart Assets Agentic Build Framework

Status: Pre‑alpha | Architecture: Agenctic Build Server Leveraging Open & Proprietary LLMs License: Custom

An autonomous development framework for building, testing, and deploying Smart Assets using hybrid AI models - intelligent digital entities that can execute complex operations, manage resources, and interact with various blockchain networks and external services.

🏠 Privacy-First: Local MLX models on Apple Silicon for fast, private development ☁️ Cloud-Powered: Optional access to Claude-3.5-Sonnet, GPT-4o, and Gemini for complex tasks 🔄 Intelligent Selection: Automatic model routing based on task complexity and your preferences

🛠️ Works with Your Favorite Tools

This framework is designed to work seamlessly with modern development tools:

💻 IDE Integration

  • Cursor - AI-first code editor with native Claude integration
  • Windsurf - Collaborative AI development environment
  • VS Code with GitHub Copilot - Industry-standard editor with AI pair programming
  • VS Code with Continue - Open-source AI coding assistant

⌨️ CLI Tools

🔗 Smart Assets Hooks

For CLI tools, this framework includes Smart Assets hooks that provide:

  • Automatic agentic mode detection in git worktrees
  • 🔒 Safety enforcement in main repository
  • 🚀 Autonomous development in isolated worktrees
  • 📊 Intelligent git workflow management

📖 Complete Documentation Hub

📚 VIEW ALL DOCUMENTATION →

Our comprehensive documentation includes:

Quick Links:

I want to...Go to...
Use Cursor or WindsurfIDE Integration Guide
Use Claude Code or AiderCLI Tools & Hooks Guide
Find any documentationDocumentation Index
See visual workflowsIDE Guide - Diagrams | CLI Guide - Diagrams
Track development progressToDos.md

Framework Overview

This agentic build system provides an autonomous development environment that can:

  • Hybrid AI Generation: Choose between local MLX models and cloud AI for optimal results
  • Autonomous Code Generation: Generate Smart Asset implementations from high-level specifications
  • Intelligent Testing: Create comprehensive test suites with quality assessment
  • Cost-Optimized Workflows: Balance privacy, speed, quality, and cost across model providers
  • Dynamic Optimization: Continuously improve performance and security
  • Multi-Chain Deployment: Deploy across multiple blockchain networks
  • Adaptive Configuration: Self-configure based on deployment environment

Quick Start

Prerequisites

  • macOS with Apple Silicon (ARM64) - Required for local LLM support
  • Python 3.11+ - Python 3.12+ recommended, 3.13+ supported when available
  • uv - Modern Python package manager (required)
  • direnv - Automatic environment loading (recommended)
  • Git - Version control
  • Homebrew - Package manager for macOS

System Requirements

This repository is specifically designed to run on Mac hardware with Apple Silicon for optimal performance with local LLMs, while also supporting cloud AI models for enhanced capabilities:

Local Development (Required)

  • MLX framework for efficient local LLM inference on Apple Silicon
  • ARM64 native Python packages for best performance
  • Local AI models for privacy-first development and unlimited usage

Cloud Models (Optional)

  • API keys for Anthropic Claude, OpenAI GPT, or Google Gemini
  • Internet connection for cloud model access
  • Cost budgeting for usage-based pricing (typically $0.10-$0.50 per Smart Asset)

Installation

Step 1: Install Prerequisites

# Install Homebrew (if not already installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Python (try latest first, fallback to known working versions)
arch -arm64 brew install [email protected]  # Latest version (preferred)
# OR if 3.13 has issues with MLX:
# arch -arm64 brew install [email protected]  # Known working version

# Install uv (modern Python package manager)
brew install uv

# Install direnv for automatic environment loading
brew install direnv

# Add direnv hook to your shell (choose your shell)
echo 'eval "$(direnv hook bash)"' >> ~/.bashrc    # For bash
echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc      # For zsh
echo 'direnv hook fish | source' >> ~/.config/fish/config.fish  # For fish

# Install build dependencies
arch -arm64 brew install pkg-config protobuf cmake

Step 2: Clone and Setup Project

# Clone the agentic framework
git clone https://gitlab.com/smart-assets.io/SA_build_agentics.git
cd SA_build_agentics

# Allow direnv to automatically setup the environment
direnv allow

# The .envrc file will automatically:
# - Find the best compatible Python version (3.11+, prefers 3.13+ > 3.12)
# - Create a virtual environment with the selected Python
# - Install MLX and dependencies
# - Activate the environment
# - Verify compatibility and setup

Alternative: Manual Setup

If you prefer manual setup or direnv isn't available:

# Create virtual environment with compatible Python (try latest available)
uv venv --python /opt/homebrew/bin/python3.13  # or python3.12

# Activate environment
source .venv/bin/activate

# Install dependencies
uv pip install mlx-lm

# Install project dependencies (if requirements.txt exists)
if [ -f requirements.txt ]; then uv pip install -r requirements.txt; fi

# Initialize the framework
uv run sa-build init

Verification

# Check that direnv loaded the environment (you should see activation messages)
# If using direnv, the environment should already be active

# Verify Python version and architecture
python -c "import platform; print(f'Python {platform.python_version()} on {platform.machine()}')"
# Expected: Python 3.11+ on arm64 (3.12+ recommended)

# Verify MLX installation and GPU acceleration
python -c "import mlx.core as mx; print(f'MLX {mx.__version__} on {mx.default_device()}')"
# Expected: MLX x.x.x on gpu

# Test local LLM setup
uv run sa-build test-llm

# Verify framework installation
uv run sa-build --version

Daily Usage with direnv

Once set up, direnv will automatically manage your environment:

# Simply navigate to the project directory
cd path/to/SA_build_agentics
# → direnv will automatically activate the virtual environment

# When you leave the directory
cd ..
# → direnv will automatically deactivate the environment

# To manually reload the environment
direnv reload

# To check environment status
direnv status

Basic Usage

Using Local MLX Models (Default)

# Generate a new Smart Asset with local models
uv run sa-build generate-asset --type oracle --name "ETH Price Oracle"

# List and download MLX models
uv run sa-build models list
uv run sa-build models download --name CodeLlama-7b-Instruct

# Build and test automatically
uv run sa-build agentic-build

# Deploy to target networks
uv run sa-build agentic-deploy --networks ethereum,polygon

Using Cloud Models (Optional)

# Configure cloud providers (one-time setup)
export ANTHROPIC_API_KEY="your-key-here"
export OPENAI_API_KEY="your-key-here"
sa-build providers configure

# Generate with specific cloud models
uv run sa-build generate-asset --type oracle --name "ETH Price Oracle" --model claude-3.5-sonnet
uv run sa-build generate-asset --type treasury --name "Multi-Sig Treasury" --model gpt-4o

# List available providers and models
uv run sa-build providers list
uv run sa-build models test --provider anthropic

# Estimate costs before generation
uv run sa-build cost-estimate --type oracle --model claude-3.5-sonnet

Hybrid Model Architecture

This framework supports both local MLX models and cloud-based AI models, giving you the flexibility to choose the best approach for your needs:

🏠 Local Models (MLX Framework)

  • Privacy-First: Code and data never leave your machine
  • Cost-Effective: No per-token charges, unlimited usage
  • Fast Iteration: No network latency, instant feedback
  • Offline Capable: Works without internet connection
  • Apple Silicon Optimized: Leverages GPU acceleration and unified memory

☁️ Cloud Models (API-Based)

  • State-of-the-Art Quality: Access to Claude-3.5-Sonnet, GPT-4o, Gemini-1.5-Pro
  • Large Context Windows: Handle complex Smart Assets with extensive codebases
  • Specialized Capabilities: Structured outputs, function calling, advanced reasoning
  • No Local Storage: No need to download large model files

🔄 Intelligent Model Selection

The framework automatically chooses the best model for each task:

# Automatic selection based on task complexity and your preferences
uv run sa-build generate-asset --type oracle --name "Simple Oracle"
# → Uses local MLX model for fast, private generation

uv run sa-build generate-asset --type cross-chain --name "Complex Multi-Chain Bridge" 
# → May suggest cloud model for better quality on complex tasks

Configuration Options

# .sa-build.toml
[model_selection]
strategy = "local_first"      # "local_first", "cloud_first", or "cost_optimized"
fallback_enabled = true       # Fallback to cloud if local fails
cost_budget_per_asset = 0.50  # Max cost for cloud models (USD)

[providers.anthropic]
api_key_env = "ANTHROPIC_API_KEY"
default_model = "claude-3-5-sonnet-20241022"

[providers.openai] 
api_key_env = "OPENAI_API_KEY"
default_model = "gpt-4o"

[providers.google]
api_key_env = "GOOGLE_API_KEY"
default_model = "gemini-1.5-pro"

Supported Providers

ProviderModelsStrengthsBest For
Local MLXCodeLlama-7B, Qwen2.5-Coder-7BPrivacy, Speed, CostDaily development, iteration
Anthropic ClaudeClaude-3.5-Sonnet, Claude-3-HaikuCode quality, reasoningComplex Smart Assets
OpenAI GPTGPT-4o, GPT-4o-miniStructured outputs, reliabilityProduction-ready code
Google GeminiGemini-1.5-Pro, Gemini-1.5-FlashLarge context, multimodalComplex integrations

Rational and ML Development Approach

Hardware-Optimized Development Strategy

Why We Chose a Multi-Platform Strategy

Our framework supports both local Apple Silicon development and cloud-based training to maximize efficiency, cost-effectiveness, and accessibility across different project scales and requirements.

The Hardware Landscape

Modern ML development spans multiple hardware ecosystems, each optimized for different use cases:

  • Apple Silicon (M3/M4): Excellent for development, prototyping, and small-scale training with unified memory architecture and energy efficiency
  • Google Cloud TPUs: Cost-effective for large-scale training (8 TPU v5e chips at ~$11/hour vs order-of-magnitude higher costs for equivalent GPU compute)
  • AWS Trainium: Up to 54% lower cost per token compared to traditional GPU clusters
  • NVIDIA GPUs: Industry standard with broad framework support, though expensive for continuous use

Model Format Strategy

Different deployment targets require different optimizations:

  • GGUF: CPU-optimized format for consumer hardware deployment and inference
  • MLX: Apple Silicon-specific format leveraging Neural Engine and unified memory (up to 10x faster, 14x less memory for optimized models)
  • Standard PyTorch/TensorFlow: Cross-platform compatibility for cloud training and production deployment
  • TensorRT/Specialized: Hardware-specific optimization for production inference

Development Workflow Rationale

Local Development (Apple Silicon)

  • Rapid prototyping and experimentation
  • Fine-tuning pre-trained models (<10B parameters)
  • Data preprocessing and exploration
  • Development environment consistency
  • Privacy-sensitive data processing

Cloud Training (TPU/Trainium)

  • Large-scale model training (>10B parameters)
  • Distributed training across multiple accelerators
  • Time-critical training deadlines
  • Experimentation with cutting-edge architectures

Cost Optimization

  • Local development eliminates cloud costs during exploration phases
  • Cloud training provides access to capabilities impossible on single machines
  • Hybrid approach typically breaks even around $10,000 annual cloud spend threshold

Framework Benefits

This multi-platform approach enables:

  1. Seamless Development: Start locally, scale to cloud when needed
  2. Cost Efficiency: Pay for cloud compute only when required scale demands it
  3. Hardware Agnostic: Deploy models across consumer devices (GGUF), Apple ecosystem (MLX), or cloud infrastructure
  4. Future Proofing: Support for emerging hardware platforms and optimization techniques

The framework abstracts away platform-specific complexities while maintaining the ability to leverage each platform's unique strengths, providing a practical path from research to production deployment.

Local LLM Architecture

This framework is optimized for Apple Silicon Macs and uses local LLMs for privacy, cost-effectiveness, and performance:

MLX Integration

The framework leverages Apple's MLX framework for efficient local AI inference:

# Local LLM configuration
llm_config = {
    "framework": "mlx",
    "models": {
        "code_generation": "mlx-community/CodeLlama-7b-Instruct-hf-4bit-mlx",
        "optimization": "mlx-community/Llama-3.2-3B-Instruct-4bit",
        "testing": "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit"
    },
    "hardware_acceleration": "apple_silicon",
    "memory_optimization": "4bit_quantization"
}

Benefits of Local LLMs

  • 🔒 Privacy: Code and data never leave your machine
  • 💰 Cost-effective: No API usage costs
  • ⚡ Performance: Optimized for Apple Silicon hardware
  • 🌐 Offline capable: Works without internet connection
  • 🔄 Consistent: Reproducible results and behavior

Supported Models

The framework comes pre-configured with MLX-optimized models:

# List available local models
uv run sa-build models list

# Download specific model
uv run sa-build models download --name CodeLlama-7b-Instruct

# Switch active model
uv run sa-build models use --name Qwen2.5-Coder-7B

Agentic Architecture

The framework consists of several autonomous agents that work together:

1. Code Generation Agent

Automatically generates Smart Asset implementations from specifications:

# Specification Input
oracle_spec = {
    "name": "Multi-Source Price Oracle",
    "data_sources": ["coinbase", "binance", "kraken"],
    "aggregation_method": "weighted",
    "update_interval": 60000,
    "quality_threshold": 0.8
}

# Generated Implementation
generated_asset = await code_agent.generate_asset(oracle_spec)

2. Testing Agent

Creates comprehensive test suites with automated quality assessment:

# Automatically generates tests for:
# - Unit functionality validation
# - Integration testing across components
# - Performance benchmarking
# - Security vulnerability scanning
# - Quality assurance metrics

3. Optimization Agent

Continuously improves code quality and performance:

# Optimization targets:
# - Gas efficiency optimization
# - Response time improvements
# - Memory usage optimization
# - Security hardening
# - Code maintainability

4. Deployment Agent

Manages multi-chain deployment and configuration:

# Handles:
# - Network-specific configuration
# - Contract deployment
# - Service registration
# - Health monitoring
# - Rollback procedures

Smart Asset Types Supported

Oracle Assets

Autonomous data aggregation systems with multi-source validation:

Features:

  • Real-time data collection from multiple APIs
  • Quality scoring and confidence metrics
  • Automatic retry and error handling
  • Configurable aggregation methods (average, median, weighted)

Generated Components:

  • Data source connectors
  • Quality assessment algorithms
  • Aggregation logic
  • Monitoring dashboards

Treasury Assets

Multi-signature treasury management with automated operations:

Features:

  • Multi-sig approval workflows
  • Automated investment strategies
  • Risk assessment and compliance
  • Daily withdrawal limits

Generated Components:

  • Governance contracts
  • Investment strategies
  • Risk management rules
  • Audit trails

Data Spigot Assets

Decentralized data marketplaces for AI training:

Features:

  • Quality assessment algorithms
  • Contributor compensation systems
  • Training job management
  • Spam detection and uniqueness verification

Generated Components:

  • Data quality evaluators
  • Payment distribution systems
  • Job matching algorithms
  • Fraud detection mechanisms

Cross-Chain Assets

Multi-chain asset management and optimization:

Features:

  • Cross-chain balance tracking
  • Automated arbitrage detection
  • Liquidity pool optimization
  • Portfolio rebalancing

Generated Components:

  • Bridge integrations
  • Arbitrage engines
  • Portfolio managers
  • Risk calculators

Web Widget Assets

Embeddable interactive components:

Features:

  • Real-time data visualization
  • User interaction tracking
  • Responsive design
  • Customizable themes

Generated Components:

  • Widget renderers
  • Data feed connectors
  • Analytics collectors
  • Embed code generators

Agentic Workflows

1. Asset Specification to Implementation

# High-level specification
specification = {
    "asset_type": "oracle",
    "name": "Weather Data Oracle",
    "data_sources": [
        {"name": "openweather", "weight": 0.4},
        {"name": "weatherapi", "weight": 0.3},
        {"name": "accuweather", "weight": 0.3}
    ],
    "update_frequency": "5m",
    "quality_threshold": 0.85,
    "geographic_scope": "global"
}

# Autonomous generation process
build_pipeline = await agentic_framework.create_pipeline(specification)
await build_pipeline.execute()

2. Quality Assurance Pipeline

# Automated quality pipeline
qa_pipeline = {
    "code_quality": {
        "linting": "ruff",
        "type_checking": "mypy-strict",
        "complexity": "max-10",
        "coverage": "min-95%"
    },
    "security": {
        "vulnerability_scanning": "bandit",
        "dependency_audit": "safety",
        "smart_contract_audit": "slither"
    },
    "performance": {
        "gas_optimization": "auto",
        "response_time": "max-500ms",
        "throughput": "min-1000-tps"
    }
}

3. Multi-Environment Deployment

# Deployment configuration
deployment_config = {
    "environments": {
        "testnet": {
            "networks": ["sepolia", "mumbai"],
            "monitoring": "basic",
            "budget": "unlimited"
        },
        "mainnet": {
            "networks": ["ethereum", "polygon", "arbitrum"],
            "monitoring": "comprehensive",
            "budget": "conservative"
        }
    },
    "rollout_strategy": "blue-green",
    "health_checks": "continuous"
}

Agent Communication

Agents communicate through a distributed event system:

// Event-driven agent coordination
interface AgentEvent {
  source: AgentType;
  target: AgentType;
  type: EventType;
  payload: any;
  timestamp: Date;
}

// Example: Code generation complete
const codeCompleteEvent = {
  source: "code-generator",
  target: "test-generator",
  type: "CODE_GENERATED",
  payload: { 
    assetId: "oracle-123",
    files: ["OracleAsset.ts", "config.ts"],
    metadata: { complexity: "medium", dependencies: ["axios", "web3"] }
  }
};

Configuration Management

Framework Configuration

// Framework settings
interface AgenticConfig {
  agents: {
    codeGenerator: {
      model: "codellama-7b" | "qwen2.5-coder-7b" | "llama-3.2-3b";
      framework: "mlx";
      temperature: 0.1;
      maxTokens: 8000;
      quantization: "4bit";
    };
    testGenerator: {
      model: "qwen2.5-coder-7b";
      coverage: "comprehensive" | "standard" | "minimal";
      frameworks: ["vitest", "jest", "hardhat"];
    };
    optimizer: {
      model: "llama-3.2-3b";
      targets: ["gas", "speed", "security"];
      aggressiveness: "conservative" | "moderate" | "aggressive";
    };
  };
  deployment: {
    networks: NetworkConfig[];
    monitoring: MonitoringConfig;
    rollback: RollbackConfig;
  };
  hardware: {
    platform: "apple_silicon";
    memory_optimization: true;
    gpu_acceleration: true;
  };
}

Asset Configuration

// Per-asset configuration
interface AssetConfig {
  metadata: {
    name: string;
    description: string;
    version: string;
    tags: string[];
  };
  runtime: {
    updateFrequency: number;
    errorHandling: "strict" | "graceful";
    logging: "minimal" | "detailed";
  };
  integration: {
    apis: APIConfig[];
    blockchains: ChainConfig[];
    services: ServiceConfig[];
  };
}

Monitoring and Observability

Real-time Monitoring

// Comprehensive monitoring system
const monitoringSystem = {
  performance: {
    responseTime: "Real-time latency monitoring",
    throughput: "Transaction per second tracking",
    errorRate: "Error frequency and categorization",
    resourceUsage: "CPU, memory, and network utilization"
  },
  business: {
    dataQuality: "Data accuracy and freshness metrics",
    userEngagement: "User interaction and satisfaction",
    revenue: "Transaction volume and fee collection",
    compliance: "Regulatory and policy adherence"
  },
  technical: {
    uptime: "Service availability tracking",
    security: "Threat detection and prevention",
    scalability: "Load capacity and auto-scaling",
    integration: "Third-party service health"
  }
};

Alerting and Response

// Automated incident response
const alertingConfig = {
  triggers: {
    highLatency: "Response time > 1000ms",
    lowDataQuality: "Quality score &#x3C; 0.7",
    securityThreat: "Unusual access patterns",
    deploymentFailure: "Deployment pipeline errors"
  },
  responses: {
    autoHealing: "Automatic service restart",
    scaling: "Dynamic resource allocation",
    rollback: "Automatic version rollback",
    notification: "Team alert and escalation"
  }
};

Advanced Features

1. Continuous Learning

The framework learns from deployment performance and user feedback:

// Learning system
const learningSystem = {
  codeOptimization: "Learn from production performance",
  userPreferences: "Adapt to user interaction patterns",
  marketConditions: "Respond to changing market dynamics",
  securityThreats: "Evolve defenses based on attack patterns"
};

2. Multi-Model Integration

Support for various local AI models optimized for Apple Silicon:

// Local model configuration
const modelConfig = {
  codeGeneration: [
    "mlx-community/CodeLlama-7b-Instruct-hf-4bit-mlx",
    "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
    "mlx-community/deepseek-coder-6.7b-instruct-4bit"
  ],
  testGeneration: [
    "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
    "mlx-community/CodeLlama-7b-Instruct-hf-4bit-mlx"
  ],
  optimization: [
    "mlx-community/Llama-3.2-3B-Instruct-4bit",
    "mlx-community/Qwen2.5-3B-Instruct-4bit"
  ],
  monitoring: [
    "mlx-community/Llama-3.2-1B-Instruct-4bit"
  ],
  framework: "mlx",
  hardware: "apple_silicon",
  quantization: "4bit"
};

3. Ecosystem Integration

Native integration with development and deployment tools:

// Ecosystem integrations
const integrations = {
  ide: ["vscode", "jetbrains", "vim"],
  cicd: ["github-actions", "gitlab-ci", "jenkins"],
  cloud: ["aws", "gcp", "azure", "digitalocean"],
  monitoring: ["datadog", "newrelic", "prometheus"],
  security: ["snyk", "veracode", "checkmarx"]
};

Development Workflow

1. Specification-Driven Development

# Create asset specification
uv run sa-build create-spec --interactive

# Generate implementation
uv run sa-build generate --spec specs/my-oracle.yaml

# Review and approve generated code
uv run sa-build review --asset my-oracle

# Deploy to testnet
uv run sa-build deploy --env testnet --asset my-oracle

2. Iterative Improvement

# Analyze production performance
uv run sa-build analyze --asset my-oracle --timeframe 7d

# Generate optimization recommendations
uv run sa-build optimize --asset my-oracle --target gas-efficiency

# Apply optimizations
uv run sa-build apply-optimizations --asset my-oracle

# A/B test new version
uv run sa-build test-deployment --strategy ab-test

3. Multi-Asset Orchestration

# Create asset ecosystem
uv run sa-build create-ecosystem --name defi-protocol

# Add assets to ecosystem
uv run sa-build add-asset --ecosystem defi-protocol --asset oracle
uv run sa-build add-asset --ecosystem defi-protocol --asset treasury
uv run sa-build add-asset --ecosystem defi-protocol --asset cross-chain

# Deploy entire ecosystem
uv run sa-build deploy-ecosystem --name defi-protocol --env mainnet

Examples and Use Cases

1. DeFi Protocol Development

// Autonomous DeFi protocol generation
const defiProtocol = {
  components: [
    {
      type: "oracle",
      purpose: "price-feeds",
      assets: ["ETH", "BTC", "USDC"],
      updateFrequency: "30s"
    },
    {
      type: "treasury", 
      purpose: "protocol-treasury",
      governance: "dao",
      strategies: ["yield-farming", "liquidity-provision"]
    },
    {
      type: "cross-chain",
      purpose: "multi-chain-liquidity",
      networks: ["ethereum", "polygon", "arbitrum"],
      bridgeProtocols: ["layerzero", "wormhole"]
    }
  ],
  integration: "automatic",
  governance: "decentralized"
};

await agenticFramework.generateProtocol(defiProtocol);

2. AI Data Marketplace

// Automated AI training data platform
const dataMarketplace = {
  spigots: [
    {
      dataType: "text",
      domains: ["finance", "healthcare", "legal"],
      qualityThreshold: 0.9
    },
    {
      dataType: "image", 
      categories: ["medical", "autonomous-driving", "satellite"],
      qualityThreshold: 0.95
    }
  ],
  compensation: "dynamic-pricing",
  qualityAssurance: "multi-layer",
  privacy: "differential-privacy"
};

await agenticFramework.generateMarketplace(dataMarketplace);

3. Enterprise Integration

// Enterprise-grade Smart Asset deployment
const enterpriseDeployment = {
  compliance: ["SOX", "GDPR", "HIPAA"],
  security: "enterprise-grade",
  scalability: "auto-scaling",
  monitoring: "comprehensive",
  support: "24/7",
  integration: {
    erp: ["sap", "oracle", "microsoft"],
    crm: ["salesforce", "hubspot"],
    databases: ["postgresql", "mongodb", "snowflake"]
  }
};

await agenticFramework.generateEnterprise(enterpriseDeployment);

Testing Framework

Installing Test Dependencies

Before running tests, install the development and testing dependencies using the optional dependency groups defined in pyproject.toml:

# Install the package with dev and testing dependencies (recommended)
uv pip install -e ".[dev,testing]"

# This installs:
# - pytest, pytest-cov for testing
# - pytest-asyncio, pytest-mock, hypothesis for advanced testing
# - mypy for type checking
# - ruff for linting
# - pre-commit for git hooks

Alternative: If you prefer separate requirements files, you can also use:

# Just install individual packages
uv pip install pytest pytest-cov pytest-asyncio pytest-mock hypothesis mypy ruff

Running Tests

# Run all tests (skip coverage for speed during development)
uv run pytest --no-cov

# Run all tests with coverage report
uv run pytest

# Run tests with verbose output
uv run pytest -v

# Run specific test file
uv run pytest tests/test_agentic_merge.py -v

# Run specific test function
uv run pytest tests/test_agentic_merge.py::test_database_not_included_in_merge -v

# Run tests matching a pattern
uv run pytest -k "agentic" -v

# Run tests with output (shows print statements)
uv run pytest -s -v

# Run tests in parallel (faster)
uv run pytest -n auto

# Run only fast tests (skip slow ones)
uv run pytest -m "not slow"

# Run with coverage and generate HTML report
uv run pytest --cov=sa_build --cov-report=html
# Then open: htmlcov/index.html

Test Organization

Tests are organized to mirror the source code structure:

tests/
├── __init__.py
├── test_agentic_merge.py        # Agentic mode merge validation tests
├── test_todo_parser.py           # ToDos.md parsing tests
├── test_worktree_manager.py      # Git worktree management tests
├── test_session_manager.py       # Session database tests
├── test_cli.py                   # CLI command tests
└── integration/                  # Integration tests
    ├── test_agentic_workflow.py
    └── test_full_pipeline.py

Writing Tests

Follow these patterns when writing tests:

import pytest
from pathlib import Path

# Use fixtures for common setup
@pytest.fixture
def temp_repo(tmp_path):
    """Create a temporary git repository."""
    repo = tmp_path / "test_repo"
    repo.mkdir()
    # ... setup code
    return repo

# Test function naming: test_&#x3C;what>_&#x3C;expected_behavior>
def test_database_not_included_in_merge(temp_repo):
    """Test that database files are never committed during merge."""
    # Arrange: Set up test conditions
    db_file = temp_repo / ".sa-build" / "agentic-sessions.db"
    db_file.parent.mkdir()
    db_file.write_bytes(b"FAKE_DB")

    # Act: Perform the operation
    result = perform_merge(temp_repo)

    # Assert: Verify expected outcomes
    assert db_file.exists(), "Database should exist on disk"
    assert not is_tracked_by_git(db_file), "Database should not be in git"

Test Markers

Use pytest markers to categorize tests:

# Run only unit tests
uv run pytest -m "not integration"

# Run only integration tests
uv run pytest -m integration

# Skip slow tests during development
uv run pytest -m "not slow"

# Run only GPU tests (requires GPU)
uv run pytest -m gpu

Continuous Integration

Tests run automatically in CI/CD:

# Pre-commit checks (run before committing)
uv run pytest --no-cov           # Fast test run
uv run mypy src/                 # Type checking
uv run ruff check                # Linting

# Full CI pipeline (what runs on GitLab)
uv run pytest                    # Full test suite with coverage
uv run mypy src/ --strict        # Strict type checking
uv run ruff check --select ALL   # All linting rules

Automated Test Generation

The framework automatically generates comprehensive test suites:

# Generate unit tests
uv run sa-build test-gen --type unit --asset my-oracle

# Generate integration tests
uv run sa-build test-gen --type integration --ecosystem defi-protocol

# Generate performance tests
uv run sa-build test-gen --type performance --load-profile high

# Generate security tests
uv run sa-build test-gen --type security --threat-model comprehensive

Quality Metrics

// Automated quality assessment
const qualityMetrics = {
  codeQuality: {
    complexity: "Cyclomatic complexity analysis",
    maintainability: "Code maintainability index",
    readability: "Code readability score",
    documentation: "Documentation coverage"
  },
  functionality: {
    correctness: "Functional requirement compliance",
    performance: "Response time and throughput",
    reliability: "Error handling and recovery",
    scalability: "Load handling capacity"
  },
  security: {
    vulnerabilities: "Known vulnerability detection",
    accessControl: "Permission and authentication",
    dataProtection: "Encryption and privacy",
    auditTrail: "Logging and monitoring"
  }
};

Community and Ecosystem

Open Source Components

# Contribute to the framework
git clone https://gitlab.com/smart-assets.io/SA_build_agentics.git
cd SA_build_agentics

# Install development dependencies
uv sync --dev

# Run framework tests
uv run pytest

# Submit improvements
git commit -m "Add new agent capability"
git push origin feature/new-capability

Plugin Development

// Create custom agents
interface CustomAgent extends Agent {
  name: string;
  capabilities: Capability[];
  execute(context: AgentContext): Promise&#x3C;AgentResult>;
}

// Register with framework
await agenticFramework.registerAgent(new CustomOptimizationAgent());

Marketplace Integration

The framework integrates with the Smart Assets marketplace at smart-assets.io:

  • Asset Templates: Pre-built Smart Asset templates
  • Agent Marketplace: Custom agents and capabilities
  • Deployment Services: Managed deployment and hosting
  • Monitoring Dashboards: Real-time performance monitoring

Performance Benchmarks

Code Generation Performance

Asset Type          | Generation Time | Code Quality | Test Coverage
--------------------|-----------------|--------------|---------------
Oracle Asset       | 2.3 minutes     | 9.2/10      | 96%
Treasury Asset      | 4.1 minutes     | 9.0/10      | 94%
Cross-Chain Asset   | 6.8 minutes     | 8.9/10      | 92%
Data Spigot Asset   | 3.7 minutes     | 9.1/10      | 95%
Widget Asset        | 1.9 minutes     | 9.3/10      | 97%

Deployment Performance

Network             | Deployment Time | Success Rate | Gas Efficiency
--------------------|-----------------|--------------|----------------
Ethereum Mainnet    | 8.2 minutes     | 99.7%       | 95%
Polygon             | 3.1 minutes     | 99.9%       | 98%
Arbitrum            | 4.6 minutes     | 99.8%       | 97%
Optimism            | 4.2 minutes     | 99.8%       | 96%

Security and Compliance

Security Framework

// Multi-layer security approach
const securityFramework = {
  codeGeneration: {
    staticAnalysis: "Automated vulnerability scanning",
    dependencyCheck: "Known vulnerability database",
    bestPractices: "Secure coding pattern enforcement"
  },
  deployment: {
    accessControl: "Role-based deployment permissions",
    environmentIsolation: "Isolated deployment environments",
    auditLogging: "Complete deployment audit trail"
  },
  runtime: {
    threatDetection: "Real-time threat monitoring",
    anomalyDetection: "Behavioral anomaly detection",
    incidentResponse: "Automated incident response"
  }
};

Compliance Support

// Regulatory compliance features
const complianceSupport = {
  frameworks: ["SOX", "GDPR", "HIPAA", "PCI-DSS"],
  features: {
    dataGovernance: "Data classification and handling",
    auditTrails: "Complete operation audit logs",
    accessControls: "Fine-grained permission management",
    reporting: "Automated compliance reporting"
  }
};

Roadmap

Current Version (1.0)

  • ✅ Basic asset generation for Oracle, Treasury, Data Spigot types
  • ✅ Automated testing and quality assurance
  • ✅ Multi-chain deployment support
  • ✅ Real-time monitoring and alerting

Next Release (1.1) - Q2 2024

  • 🔄 Advanced Cross-Chain Asset generation
  • 🔄 Widget Asset framework
  • 🔄 Enhanced security scanning
  • 🔄 Performance optimization agents

Future Releases (1.2+)

  • 📋 Atomic Networked Services framework
  • 📋 Composeable Micropayment Networks
  • 📋 Crowd Funded Collective Action systems
  • 📋 Enterprise-grade governance tools

Contributing

We welcome contributions to the Smart Assets Agentic Build Framework:

  1. Fork the repository: Create your own fork of the project
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes: Implement your feature or bug fix
  4. Add tests: Ensure your changes are thoroughly tested
  5. Submit a pull request: Open a PR with a clear description

Development Setup

# Clone your fork
git clone https://gitlab.com/yourusername/SA_build_agentics.git

# Install dependencies
uv sync

# Set up development environment
uv run sa-build setup-dev

# Run tests
uv run pytest

# Start development server
uv run sa-build dev

License

License: Custom

Agentic Development Mode

📖 Complete Documentation: IDE Integration Guide | CLI Tools Guide | Documentation Index

🎨 Visual Guides: See workflow diagrams and hook architecture diagrams for visual explanations

What is Agentic Development?

Agentic Development Mode enables fully autonomous AI-driven development using git worktrees. This mode allows AI agents to work independently on isolated branches, automatically selecting and implementing tasks from your project's todo list, making commits, running tests, and iterating rapidly without affecting your main working directory.

Key Benefits:

  • 🚀 Rapid Prototyping: AI can experiment freely without manual approval for each git operation
  • 🔒 Isolated Experiments: Uses git worktrees to keep experiments separate from main codebase
  • 🔄 Parallel Development: Run multiple AI experiments simultaneously in different worktrees
  • 🛡️ Safe Exploration: Easy to discard failed experiments or merge successful ones
  • 📊 Progress Tracking: Automatic checkpointing and session management

Use Cases

  1. Autonomous Task Implementation: AI selects tasks from docs/ToDos.md and implements them autonomously
  2. Rapid Feature Development: Let AI implement complete features from specifications
  3. Architectural Exploration: Test multiple architectural approaches in parallel
  4. Refactoring: Aggressive code refactoring with automatic rollback capability
  5. Bug Fixing: Parallel exploration of different bug fix strategies
  6. Batch Processing: Work through multiple todo items in sequence

How Git Worktrees Work

Git worktrees allow you to have multiple working directories attached to the same repository:

# Main repository
/Users/you/project/                    # main branch

# Worktrees for parallel development
/Users/you/project-worktrees/
  ├── feature-oracle-v2/              # feature/oracle-v2 branch
  ├── refactor-agent-system/          # refactor/agent-system branch
  └── experiment-hybrid-model/        # experiment/hybrid-model branch

Each worktree:

  • Has its own working directory and branch
  • Shares the same git history and objects
  • Can be developed independently
  • Easy to merge back or discard

Agentic Development Commands

Starting Agentic Build

# Start agentic build - AI selects tasks from docs/ToDos.md
uv run sa-build agentic-build

# Start with specific task/feature
uv run sa-build agentic-build --task "Add Gemini provider support"

# Start with specific AI model
uv run sa-build agentic-build --model claude-3.5-sonnet

# Start with custom worktree location
uv run sa-build agentic-build --worktree-dir ~/experiments

# Work through multiple tasks in sequence
uv run sa-build agentic-build --batch --max-tasks 5

What happens:

  1. Reads docs/ToDos.md and analyzes pending tasks
  2. Selects an appropriate task or uses specified task
  3. Creates a new git worktree in .sa-worktrees/<task-name>/
  4. Creates and checks out new branch agentic/<task-name>
  5. Copies .sa-build.toml configuration to worktree
  6. Disables git safety hooks in the worktree
  7. AI works autonomously, making commits and running tests

Managing Agentic Sessions

# Show all active agentic worktrees
uv run sa-build agentic-show

# Check status of current agentic session
uv run sa-build agentic-status

# View changes made in agentic session
uv run sa-build agentic-status --diff

# View commit log for agentic session
uv run sa-build agentic-status --log

# View tasks from docs/ToDos.md
uv run sa-build agentic-show --tasks

Committing Agentic Work

# Review and merge agentic changes to main branch
uv run sa-build agentic-commit --merge

# Create a pull request from agentic branch
uv run sa-build agentic-commit --pr

# Commit changes but keep agentic session active
uv run sa-build agentic-commit --continue

# Interactive review of changes before merge
uv run sa-build agentic-commit --interactive

Cleaning Up Agentic Sessions

# Abort and discard all changes
uv run sa-build agentic-abort

# Abort but save changes as a stash
uv run sa-build agentic-abort --stash

# Archive successful experiment for later reference
uv run sa-build agentic-archive

# Clean up all completed agentic sessions
uv run sa-build agentic-cleanup

Agentic Mode Configuration

Configure agentic mode behavior in .sa-build.toml:

[agentic]
# Enable/disable agentic mode
enabled = true

# Default location for worktrees
worktree_base = ".sa-worktrees"

# Automatic commit message prefix
commit_prefix = "[Agentic]"

# Maximum number of concurrent agentic sessions
max_sessions = 5

# Auto-cleanup completed sessions after (days)
auto_cleanup_days = 7

# Path to todo list file for task selection
todos_file = "docs/ToDos.md"

# Task selection strategy
task_selection = "auto"  # "auto", "manual", or "sequential"

[agentic.git]
# Allow AI to make commits automatically
auto_commit = true

# Allow AI to push to remote
auto_push = false  # Keep false for safety

# Auto-rebase on main before merge
auto_rebase = true

# Required checks before merge
require_tests = true
require_lint = true

[agentic.safety]
# Create backup branch before starting
backup_enabled = true

# Automatic checkpoints every N minutes
checkpoint_interval_minutes = 15

# Maximum uncommitted changes before forcing commit
max_uncommitted_changes = 50

# Block operations outside worktree
enforce_worktree_boundary = true

[agentic.ai]
# Default model for YOLO mode
default_model = "local_mlx"  # or "claude-3.5-sonnet"

# Allow model to make breaking changes
allow_breaking_changes = false

# Require approval for dependency changes
approve_dependency_changes = true

Agentic Prompt Templates

Overview

Agentic prompts should be stored under revision control in templates/agents/ for reusability, sharing, and version management. This allows you to build a library of proven prompts that can be reused across tasks and shared with your team.

Directory Structure

templates/
└── agents/
    ├── code-generation/
    │   ├── smart-contract.md
    │   ├── api-endpoint.md
    │   └── typescript-component.md
    ├── testing/
    │   ├── unit-tests.md
    │   ├── integration-tests.md
    │   └── e2e-tests.md
    ├── refactoring/
    │   ├── extract-method.md
    │   ├── optimize-performance.md
    │   └── improve-types.md
    └── documentation/
        ├── api-docs.md
        ├── architecture-docs.md
        └── inline-comments.md

Template Format

Each template should be a markdown file with clear sections:

# Template Name

## Purpose
Brief description of what this template accomplishes.

## When to Use
- Use case 1
- Use case 2
- Use case 3

## Context Required
- Required information (e.g., file paths, function names)
- Optional context that improves results
- Environment setup needed

## Prompt Template

[Your reusable prompt goes here with placeholders for variables]

Example:

Implement a TypeScript {{component_type}} for {{feature_name}} that:

  • Follows the existing architecture in {{reference_file}}
  • Includes comprehensive error handling
  • Has 90%+ test coverage
  • Uses type-safe patterns throughout

## Expected Outcomes
- List of deliverables
- Quality criteria
- Success metrics

## Post-Task Checklist
- [ ] Tests pass
- [ ] Linting passes
- [ ] Documentation updated
- [ ] Code reviewed

Using Templates in Agentic Mode

Option 1: Reference from Command Line

# Use a specific template
uv run sa-build agentic-build --template templates/agents/code-generation/smart-contract.md

# Use template with variable substitution
uv run sa-build agentic-build \
  --template templates/agents/code-generation/api-endpoint.md \
  --vars '{"feature_name": "user authentication", "framework": "FastAPI"}'

Option 2: Reference in docs/ToDos.md

## ToDo: Implement User Authentication API

**Template**: `templates/agents/code-generation/api-endpoint.md`
**Variables**:
- feature_name: "user authentication"
- framework: "FastAPI"
- auth_method: "JWT"

**Context**:
- Reference existing patterns in `src/api/auth/`
- Use existing database models from `src/models/user.py`

Option 3: Direct AI Invocation

When working with Claude Code or other AI tools directly:

# In your agentic session, reference the template
claude-code "Follow the template in templates/agents/testing/unit-tests.md
to create tests for the new UserService class"

Best Practices

1. Template Versioning

  • Keep templates under git version control
  • Tag stable template versions for reproducibility
  • Document breaking changes in template CHANGELOG

2. Template Organization

  • Group by task type (code-generation, testing, refactoring)
  • Use clear, descriptive filenames
  • Include examples in template comments

3. Variable Placeholders

  • Use consistent placeholder syntax: {{variable_name}}
  • Document all required and optional variables
  • Provide default values where appropriate

4. Template Reusability

  • Write templates to be project-agnostic where possible
  • Include adaptation instructions for different contexts
  • Provide both minimal and comprehensive variants

5. Quality Assurance

  • Test templates on real tasks before committing
  • Collect metrics on template success rates
  • Iteratively improve based on outcomes

6. Sharing and Collaboration

  • Share successful templates across Smart Assets repositories
  • Contribute general-purpose templates to community
  • Document domain-specific adaptations

Example Templates

Smart Contract Generation Template (templates/agents/code-generation/smart-contract.md):

# Smart Contract Generation

## Purpose
Generate production-ready Solidity smart contracts with comprehensive testing.

## Prompt Template
Generate a Solidity smart contract for {{contract_purpose}} that:

1. **Contract Structure**:
   - Implements {{interface_name}} interface
   - Inherits from {{base_contracts}}
   - Uses {{solidity_version}} syntax

2. **Functionality**:
   {{#each functions}}
   - {{this.name}}: {{this.description}}
   {{/each}}

3. **Security Requirements**:
   - Include ReentrancyGuard for state-changing functions
   - Implement access control with {{access_pattern}}
   - Add input validation for all public functions
   - Include pause mechanism for emergencies

4. **Testing**:
   - Unit tests with Hardhat
   - Cover all function paths
   - Include edge cases and failure scenarios
   - Gas optimization tests

5. **Documentation**:
   - NatSpec comments for all functions
   - README with deployment instructions
   - Architecture diagram

## Expected Outcomes
- Fully documented Solidity contract
- Comprehensive test suite (>95% coverage)
- Deployment scripts for multiple networks
- Gas usage report

Testing Template (templates/agents/testing/unit-tests.md):

# Unit Test Generation

## Purpose
Generate comprehensive unit tests for existing code.

## Prompt Template
Generate unit tests for {{module_path}} that:

1. **Test Coverage**:
   - Test all public methods/functions
   - Cover edge cases and error conditions
   - Include boundary value testing
   - Target >90% code coverage

2. **Test Structure**:
   - Use {{test_framework}} (pytest/jest/vitest)
   - Follow AAA pattern (Arrange, Act, Assert)
   - Mock external dependencies
   - Use descriptive test names

3. **Test Quality**:
   - Each test should test one thing
   - Tests should be independent
   - Use fixtures for common setup
   - Include negative test cases

4. **Documentation**:
   - Docstrings explaining test purpose
   - Comments for complex assertions
   - Test data explanation

## Expected Outcomes
- Test file mirroring source structure
- All tests passing
- Coverage report showing >90%
- Documentation of test approach

Maintaining Template Library

Regular Review Process:

# Quarterly template review
uv run sa-build template-review --metrics

# Shows:
# - Template usage frequency
# - Success rate by template
# - Average time savings
# - User feedback scores

# Update templates based on learnings
uv run sa-build template-update --based-on recent-successes

Template Metrics (future feature):

# .sa-build.toml
[templates]
# Track template usage and outcomes
collect_metrics = true
feedback_enabled = true

# Suggest templates based on task analysis
auto_suggest = true

Agentic Mode Safety Features

1. Automatic Checkpointing

Agentic mode automatically creates checkpoints:

# Checkpoints are created every 15 minutes (configurable)
agentic/task-name
├── checkpoint-001  # Initial state
├── checkpoint-002  # After 15 minutes
├── checkpoint-003  # After 30 minutes
└── main           # Current state

# Restore from checkpoint
uv run sa-build agentic-restore --checkpoint 002

2. Worktree Isolation

All agentic work happens in isolated worktrees:

# Main repository remains unchanged
/project/                     # Your normal work continues here

# Agentic experiments are isolated
/project/.sa-worktrees/
  ├── feature-a/             # Experiment A
  └── feature-b/             # Experiment B

3. Pre-Merge Validation

Before merging agentic work:

# Automatic validation runs:
1. All tests must pass (pytest)
2. Linting must pass (ruff)
3. Type checking must pass (mypy)
4. No conflicts with main branch
5. Code review checklist

# Manual review option
uv run sa-build agentic-commit --review

4. Rollback Capabilities

Multiple rollback options:

# Rollback to previous checkpoint
uv run sa-build agentic-rollback --checkpoint 002

# Rollback specific file
uv run sa-build agentic-rollback --file src/agents/code_generator.py

# Complete rollback to start
uv run sa-build agentic-rollback --hard

Workflow Examples

Example 1: Autonomous Task Implementation

# Start agentic build - AI reads docs/ToDos.md and picks a task
uv run sa-build agentic-build

# AI autonomously:
# 1. Analyzes pending tasks in docs/ToDos.md
# 2. Selects "Add Gemini provider support" task
# 3. Creates provider implementation
# 4. Writes comprehensive tests
# 5. Updates documentation
# 6. Makes multiple commits with detailed messages
# 7. Marks task as completed in docs/ToDos.md

# Review progress
uv run sa-build agentic-status
# Output:
# ✓ Task: Add Gemini provider support
# ✓ 12 commits made
# ✓ 847 lines added
# ✓ All tests passing
# ✓ Code quality: 9.2/10

# Merge to main
uv run sa-build agentic-commit --merge

Example 2: Batch Task Processing

# Work through multiple tasks sequentially
uv run sa-build agentic-build --batch --max-tasks 3

# AI autonomously:
# 1. Implements "Add Anthropic Claude integration" (45 minutes)
# 2. Implements "Add OpenAI integration" (40 minutes)
# 3. Implements "Intelligent model routing system" (60 minutes)
# Each task results in passing tests and proper commits

# Review all completed work
uv run sa-build agentic-status

# Merge all changes
uv run sa-build agentic-commit --merge

Example 3: Parallel Architectural Exploration

# Terminal 1: Try approach A
uv run sa-build agentic-build --task "refactor agent system with observer pattern"

# Terminal 2: Try approach B
uv run sa-build agentic-build --task "refactor agent system with event-driven architecture"

# Terminal 3: Try approach C
uv run sa-build agentic-build --task "refactor agent system with actor model"

# Compare results from main repo
uv run sa-build agentic-show
# Lists all three approaches with metrics

# Choose best approach and merge
cd .sa-worktrees/refactor-agent-system-event-driven/
uv run sa-build agentic-commit --merge

# Discard others
uv run sa-build agentic-abort --session refactor-observer
uv run sa-build agentic-abort --session refactor-actor

Integration with CI/CD

Agentic branches can integrate with CI/CD:

# .gitlab-ci.yml
agentic-validation:
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^agentic\//'
  script:
    - uv run pytest
    - uv run mypy src/
    - uv run ruff check
    - uv run sa-build agentic-status --validate
  allow_failure: true  # Don't block on experimental branches

Agentic Mode vs. Normal Mode

FeatureNormal ModeAgentic Mode
Task SelectionManualAuto from docs/ToDos.md
Git CommitsManual approval requiredAutomatic
Git PushBlockedConfigurable
File AccessRepository onlyWorktree only
Hook RestrictionsStrictRelaxed
RollbackManualAutomatic checkpoints
Risk LevelLowMedium (isolated)
SpeedSlower (approvals)Fast (autonomous)
Best ForProduction workTask implementation

Best Practices for Agentic Mode

  1. Maintain docs/ToDos.md: Keep your todo list updated for AI to select tasks
  2. Review Before Merge: Always review agentic-generated code before merging to main
  3. Use Batch Mode for Related Tasks: Process multiple related tasks in sequence
  4. Regular Checkpoints: Don't disable automatic checkpointing
  5. Test Everything: Ensure all tests pass before merging agentic work
  6. Clean Up: Regularly clean up completed or abandoned agentic sessions
  7. Backup Important Work: Archive successful experiments for future reference
  8. Task Granularity: Break large tasks into smaller, manageable items in docs/ToDos.md

Setting Up Hooks for Agentic Build

For agentic development to work properly, the hooks must be installed correctly. Here's the complete setup:

Quick Setup (5 minutes)

# 1. Create hooks directory
mkdir -p ~/.claude/hooks

# 2. Link hooks from parent repository (recommended)
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/agentic-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/git-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/project-boundary-hook.sh ~/.claude/hooks/

# 3. Install jq if not already installed
brew install jq

# 4. Configure Claude Code
# Add to ~/.claude/config.json:
cat > ~/.claude/config.json &#x3C;&#x3C; 'EOF'
{
  "hooks": {
    "pre_tool_use": [
      {
        "name": "agentic-mode-detection",
        "path": "~/.claude/hooks/agentic-hook.sh",
        "tools": ["*"]
      },
      {
        "name": "git-safety",
        "path": "~/.claude/hooks/git-hook.sh",
        "tools": ["Bash"]
      },
      {
        "name": "project-boundary",
        "path": "~/.claude/hooks/project-boundary-hook.sh",
        "tools": ["Read", "Edit", "Write", "MultiEdit", "Glob", "Grep"]
      }
    ]
  }
}
EOF

# 5. Verify setup
ls -la ~/.claude/hooks/
cat ~/.claude/config.json | jq '.hooks'
which jq

Verify Agentic Mode Works

# Create a test worktree
cd ~/src/SA/SA_build_agentics
git worktree add .sa-worktrees/test-setup agentic/test-setup

# Navigate to worktree
cd .sa-worktrees/test-setup

# In Claude Code, verify agentic mode:
# 1. Try: git commit --allow-empty -m "test"
#    Should: Succeed without prompts
# 2. Try: echo "test" > test.txt
#    Should: Succeed without boundary checks
# 3. Check: git status
#    Should: Show the new commit

# Clean up test
cd ../../
git worktree remove .sa-worktrees/test-setup
git branch -D agentic/test-setup

What Happens When Agentic Build Runs

# When you run: uv run sa-build agentic-build

# 1. Creates worktree at: .sa-worktrees/&#x3C;task-name>/
# 2. The .git file in worktree points to: ../.git/worktrees/&#x3C;task-name>
# 3. agentic-hook.sh detects this and sets yolo_mode: true
# 4. git-hook.sh sees yolo_mode and allows all git operations
# 5. project-boundary-hook.sh sees yolo_mode and skips boundary checks
# 6. Claude Code can now commit, push, and access files freely

Common Issues

Issue: Hooks not detected

# Check hook paths are correct
ls -la ~/.claude/hooks/
# Should show all three hooks with proper permissions

# Check Claude Code config
cat ~/.claude/config.json | jq '.hooks.pre_tool_use'
# Should show all three hooks configured

Issue: jq not found

# Install jq
brew install jq

# Verify installation
which jq
jq --version

Issue: Agentic mode not activating

# Verify you're in a worktree
cd .sa-worktrees/&#x3C;your-task>/
git rev-parse --git-dir
# Should show: ../.git/worktrees/&#x3C;your-task>

# Check .git file
file .git
# Should show: .git: ASCII text (not a directory)

cat .git
# Should show: gitdir: ../.git/worktrees/&#x3C;your-task>

Issue: Permission denied on hooks

# Make hooks executable
chmod +x ~/.claude/hooks/*.sh

# Verify permissions
ls -la ~/.claude/hooks/
# Should show: -rwxr-xr-x (executable)

Troubleshooting Agentic Mode

Agentic Session Won't Start

# Check for existing sessions
uv run sa-build agentic-show

# Verify docs/ToDos.md exists and has tasks
cat docs/ToDos.md

# Clean up stale sessions
uv run sa-build agentic-cleanup --force

# Check git worktree status
git worktree list

No Tasks Available

# Verify todos file location
uv run sa-build agentic-show --tasks

# Check configuration
cat .sa-build.toml | grep todos_file

# Manually specify task
uv run sa-build agentic-build --task "implement feature X"

Merge Conflicts

# Update agentic branch with latest main
uv run sa-build agentic-sync

# Interactive conflict resolution
uv run sa-build agentic-resolve-conflicts

# Abort and restart if needed
uv run sa-build agentic-abort
uv run sa-build agentic-build --task same-task

Performance Issues

# Check worktree disk usage
uv run sa-build agentic-disk-usage

# Prune old checkpoints
uv run sa-build agentic-prune-checkpoints --older-than 7d

# Optimize git repository
uv run sa-build agentic-optimize

Cross-Repository Agentic Mode

This framework is designed for use across all Smart Assets repositories. Enable agentic mode in any Smart Asset project:

# In any Smart Asset repository
cd ~/src/smart-asset-oracle
uv run sa-build agentic-build  # Reads oracle repo's docs/ToDos.md

# In another repository simultaneously
cd ~/src/smart-asset-treasury
uv run sa-build agentic-build  # Reads treasury repo's docs/ToDos.md

# Manage all agentic sessions from anywhere
uv run sa-build agentic-show --all-repos

📚 Learn More:


Claude Code Integration

📖 Complete Hook Documentation: CLI Tools & Hooks Guide

🎨 Visual Architecture: See hook system diagrams showing how hooks automatically detect and manage agentic mode

Overview

This project includes custom hooks for Claude Code that enhance the development experience by enforcing project boundaries and git workflow safety. These hooks are based on the Smart Assets GitLab profile tools available at gitlab.com/smart-assets.io/gitlab-profile.

Note: Hooks are automatically disabled in agentic mode to allow autonomous development. See Agentic Development Mode for details.

Available Hooks

1. Agentic Development Hook (agentic-hook.sh)

NEW: This hook automatically detects git worktrees and enables agentic development mode, allowing Claude Code to work autonomously in isolated environments.

Purpose: Automatically enable permissive mode when working in git worktrees for agentic development while maintaining strict safety in the main repository.

How It Works:

  • Detects if Claude Code is running in a git worktree (checks for .git file or worktrees/ in git-dir path)
  • If in a worktree: Sets yolo_mode: true metadata and approves permissive operations
  • If in main repository: Defers to normal safety hooks

When Activated:

  • Automatically when running in .sa-worktrees/ directories
  • When git rev-parse --git-dir contains worktrees/
  • When .git is a file (worktree marker) instead of a directory

Benefits:

  • No manual configuration needed for agentic development
  • Automatic safety enforcement - strict in main repo, permissive in worktrees
  • Seamless transition between normal and agentic modes

Implementation:

#!/usr/bin/env bash
# Detects git worktrees and enables permissive mode

input=$(cat)
cwd=$(echo "$input" | jq -r '.cwd // "'"$(pwd)"'"')
cd "$cwd" 2>/dev/null || exit 0

# Check if this is a worktree
git_dir=$(git rev-parse --git-dir 2>/dev/null)
if [ -f "$cwd/.git" ] || [[ "$git_dir" == *"/worktrees/"* ]]; then
    # Enable agentic mode
    echo "{\"decision\": \"approve\", \"metadata\": {\"yolo_mode\": true}}"
    exit 0
fi
exit 0

2. Git Command Safety Hook (git-hook.sh)

This hook provides safe git command execution by controlling which git operations Claude Code can perform automatically. It automatically detects worktrees and becomes permissive in agentic mode.

Purpose: Prevent accidental or unsafe git operations while allowing safe git commands to execute normally (in main repo).

Agentic Mode Behavior:

  • In Worktrees: All git operations allowed automatically (commits, push, rebase, reset)
  • In Main Repo: Strict safety enforcement as described below

Normal Mode Behavior (main repository):

  • Blocked Commands (requires manual execution):

    • git commit - Commits should be reviewed before execution
    • git rebase - Rebase operations require careful consideration
    • git reset - Reset operations can lose data
    • git push - Push operations should be intentional
  • Permission-Required Commands (asks for user approval):

    • git add - Requires confirmation before staging files
    • git mv - Requires confirmation before moving/renaming files
  • Allowed Commands (execute automatically):

    • git status - Safe read-only operation
    • git diff - Safe read-only operation
    • git log - Safe read-only operation
    • All non-git commands - Pass through normally

Implementation:

#!/usr/bin/env bash

input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command // empty')

# Check for worktree - if true, allow all operations
cwd=$(echo "$input" | jq -r '.cwd // "'"$(pwd)"'"')
cd "$cwd" 2>/dev/null || exit 0

is_worktree=false
if git rev-parse --is-inside-work-tree &#x26;>/dev/null; then
    git_dir=$(git rev-parse --git-dir 2>/dev/null)
    if [ -f "$cwd/.git" ] || [[ "$git_dir" == *"/worktrees/"* ]]; then
        is_worktree=true
    fi
fi

# Agentic mode: allow all git operations in worktrees
if [ "$is_worktree" = true ]; then
    exit 0
fi

# Normal mode restrictions
case "$cmd" in
    "git commit"*|"git rebase"*|"git reset"*|"git push"*)
        echo "{\"decision\": \"block\", \"reason\": \"...\"}"
        exit 0
        ;;
    # ... rest of logic
esac

3. Project Boundary Enforcement Hook (project-boundary-hook.sh)

This hook ensures that Claude Code only accesses files within the project's git repository boundary. It automatically detects worktrees and skips boundary checks in agentic mode.

Purpose: Maintain project isolation and prevent unintended file access outside the git repository (in main repo).

Agentic Mode Behavior:

  • In Worktrees: All file access restrictions lifted (full access within worktree)
  • In Main Repo: Strict boundary enforcement as described below

Normal Mode Behavior (main repository):

Behavior:

  • Within Git Repository: All file operations allowed within the git root
  • Outside Git Repository:
    • Blocks access by default
    • Special case: Allows ~/.claude/ directory with user permission
    • Respects CLAUDESAFEPATH environment variable for approved directories

File Operations Monitored:

  • Read - Reading file contents
  • Edit - Editing files
  • Write - Writing new files
  • MultiEdit - Batch editing operations
  • Glob - File pattern matching
  • Grep - Content searching

Environment Variable: CLAUDESAFEPATH

You can define additional safe paths outside your git repository using the CLAUDESAFEPATH environment variable (colon-separated paths):

# Allow access to specific directories
export CLAUDESAFEPATH="/path/to/shared/lib:/path/to/common/config"

# Add to your shell profile for persistence
echo 'export CLAUDESAFEPATH="/path/to/shared/lib:/path/to/common/config"' >> ~/.zshrc

Implementation Details:

#!/usr/bin/env bash

input=$(cat)
cwd=$(echo "$input" | jq -r '.cwd // "'"$(pwd)"'"')
cd "$cwd" 2>/dev/null || cd "$(pwd)"

# Check for worktree - if true, skip all boundary checks
is_worktree=false
if git rev-parse --is-inside-work-tree &#x26;>/dev/null; then
    git_dir=$(git rev-parse --git-dir 2>/dev/null)
    if [ -f "$cwd/.git" ] || [[ "$git_dir" == *"/worktrees/"* ]]; then
        is_worktree=true
    fi
fi

# Agentic mode: skip all boundary checks in worktrees
if [ "$is_worktree" = true ]; then
    exit 0
fi

# Normal mode: enforce boundaries
git_root=$(git rev-parse --show-toplevel 2>/dev/null)

if [[ "$abs_file" != "$abs_git_root"* ]]; then
    # Special cases: ~/.claude/ or CLAUDESAFEPATH
    # ... boundary enforcement logic
fi

Installing Hooks

Since this repository is within the Smart Assets parent structure, you can link directly to the hooks:

# Create hooks directory in your Claude Code config
mkdir -p ~/.claude/hooks

# Link hooks from parent repository
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/agentic-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/git-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/project-boundary-hook.sh ~/.claude/hooks/

# Verify links
ls -la ~/.claude/hooks/

Benefits of Linking:

  • Hooks auto-update when parent repository is updated
  • Single source of truth for all Smart Assets repositories
  • No need to manually sync changes

Option 2: Manual Installation from GitLab

# Create hooks directory
mkdir -p ~/.claude/hooks

# Download all three hooks
curl -o ~/.claude/hooks/agentic-hook.sh \
  https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/raw/master/AItools/hooks/agentic-hook.sh

curl -o ~/.claude/hooks/git-hook.sh \
  https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/raw/master/AItools/hooks/git-hook.sh

curl -o ~/.claude/hooks/project-boundary-hook.sh \
  https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/raw/master/AItools/hooks/project-boundary-hook.sh

# Make executable
chmod +x ~/.claude/hooks/*.sh

Configure Claude Code to Use Hooks

Edit your Claude Code configuration file (~/.claude/config.json or via Claude Code settings):

{
  "hooks": {
    "pre_tool_use": [
      {
        "name": "agentic-mode-detection",
        "path": "~/.claude/hooks/agentic-hook.sh",
        "tools": ["*"]
      },
      {
        "name": "git-safety",
        "path": "~/.claude/hooks/git-hook.sh",
        "tools": ["Bash"]
      },
      {
        "name": "project-boundary",
        "path": "~/.claude/hooks/project-boundary-hook.sh",
        "tools": ["Read", "Edit", "Write", "MultiEdit", "Glob", "Grep"]
      }
    ]
  }
}

Hook Order Matters:

  1. agentic-hook.sh runs first to detect worktrees and set metadata
  2. git-hook.sh checks for worktree mode and adjusts git restrictions
  3. project-boundary-hook.sh checks for worktree mode and adjusts file access

Note: The agentic hook applies to ALL tools ("*") to ensure worktree detection happens for every operation.

Option 3: Automated Installation with sa-build

Future version of this framework will include:

# Automated hook installation
uv run sa-build install-hooks

# Install hooks with linking from parent repository
uv run sa-build install-hooks --link

# Configure CLAUDESAFEPATH automatically
uv run sa-build configure-safe-paths --add /path/to/directory

# Verify hook installation and test worktree detection
uv run sa-build test-hooks --agentic

Hook Benefits

  1. Automatic Agentic Mode: Hooks detect worktrees and automatically enable permissive mode for agentic development
  2. Safety in Main Repo: Strict safety enforcement when working in the main repository
  3. Security: Blocks potentially dangerous operations (in main repo only)
  4. Seamless Workflow: No manual configuration needed to switch between normal and agentic modes
  5. Consistency: Same hooks work across all Smart Assets repositories
  6. Transparency: Clear feedback about mode (agentic vs. normal) and why operations are allowed/blocked

Customizing Hooks

You can customize the hooks to fit your workflow:

Example: Allow git add without permission

Edit ~/.claude/hooks/git-hook.sh and move "git add"* to the allowed section:

case "$cmd" in
    # Completely blocked commands
    "git commit"*|"git rebase"*|"git reset"*|"git push"*)
        echo "{\"decision\": \"block\", \"reason\": \"The command '$cmd' is not allowed for safety reasons. Please run this command manually if needed.\"}"
        exit 0
        ;;

    # All other commands (including git add) are allowed
    *)
        exit 0
        ;;
esac

Example: Add additional safe paths dynamically

Add to your project's .envrc:

# Allow Claude Code to access shared libraries
export CLAUDESAFEPATH="$HOME/shared-libs:$HOME/common-config"

Testing Hooks

After installation, test the hooks in both modes:

Test Normal Mode (Main Repository)

# In main repository
cd ~/src/SA/SA_build_agentics

# Test git command blocking in Claude Code
# Try: git commit -m "test"
# Expected: Blocked with safety message

# Test file boundary enforcement
# Try to read: cat ../some-other-project/file.txt
# Expected: Blocked with project boundary message

# Test CLAUDESAFEPATH
export CLAUDESAFEPATH="/tmp/test-path"
mkdir -p /tmp/test-path
echo "test content" > /tmp/test-path/test.txt
# Try to read: /tmp/test-path/test.txt
# Expected: Requests permission, then allows access

Test Agentic Mode (Worktree)

# Create a test worktree
git worktree add .sa-worktrees/test-agentic agentic/test-agentic
cd .sa-worktrees/test-agentic

# Test automatic agentic mode detection
# Try: git commit -m "test in worktree"
# Expected: Allowed automatically (no blocking)

# Test file access in agentic mode
# Try to read any file in worktree
# Expected: Allowed automatically (no boundary checks)

# Verify agentic mode is active
# Claude Code should indicate "agentic mode enabled" in responses

Verify Hook Configuration

# Check that all hooks are installed
ls -la ~/.claude/hooks/
# Should show: agentic-hook.sh, git-hook.sh, project-boundary-hook.sh

# Check Claude Code configuration
cat ~/.claude/config.json | jq '.hooks'
# Should show all three hooks configured

# Test jq availability (required for hooks)
which jq
# Should show jq path (install with: brew install jq)

Troubleshooting Hooks

Hook Not Executing

# Verify hook files exist and are executable
ls -la ~/.claude/hooks/
# Should show -rwxr-xr-x permissions

# Make executable if needed
chmod +x ~/.claude/hooks/*.sh

# Check Claude Code configuration
cat ~/.claude/config.json | jq '.hooks'

Hook Blocking Expected Operations

# Check hook output for debugging
# Add debug logging to hooks (temporary)
# Add this line after #!/usr/bin/env bash:
# exec 2>> ~/.claude/hooks/debug.log

# View debug log
tail -f ~/.claude/hooks/debug.log

Permission Prompts Not Appearing

# Ensure jq is installed (required for JSON parsing)
brew install jq

# Verify jq is in PATH
which jq

# Test hook manually
echo '{"tool_input":{"command":"git add ."}}' | ~/.claude/hooks/git-hook.sh

Troubleshooting

Common Installation Issues

direnv Not Loading Environment

# Check if direnv is properly installed and hooked
direnv version

# Check if .envrc is allowed
direnv status

# If not allowed, run:
direnv allow

# Reload shell configuration
source ~/.zshrc  # or ~/.bashrc

MLX Installation Fails

# Ensure you're using ARM64 Python 3.12
uv venv --python /opt/homebrew/bin/python3.12
source .venv/bin/activate

# Install build dependencies first
arch -arm64 brew install pkg-config protobuf cmake

# Then install MLX
uv pip install mlx-lm

Environment Not Activating Automatically

# Check if direnv hook is in your shell config
grep -r "direnv hook" ~/.zshrc ~/.bashrc ~/.config/fish/config.fish

# If missing, add the appropriate hook:
echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc    # for zsh
echo 'eval "$(direnv hook bash)"' >> ~/.bashrc  # for bash

# Restart your shell or source the config
source ~/.zshrc  # or source ~/.bashrc

Python Version Compatibility

# Check Python version and architecture
python -c "import platform; print(f'Python {platform.python_version()} on {platform.machine()}')"

# Should output: Python 3.12.x on arm64

Performance Issues

# Verify MLX is using GPU acceleration
python -c "import mlx.core as mx; print(f'MLX device: {mx.default_device()}')"

# Should output: MLX device: gpu

Hardware Requirements

  • Minimum: MacBook Air M1 with 8GB RAM
  • Recommended: MacBook Pro M2/M3 with 16GB+ RAM
  • Optimal: Mac Studio M2 Ultra with 64GB+ RAM

Support & Documentation

📚 Documentation Resources

🤝 Community & Support


Smart Assets Agentic Build Framework - Autonomous development for the future of digital assets.

For more information about Smart Assets, visit smart-assets.io.

Prompt Playground

15 Variables

Fill Variables

Preview

# Smart Assets Agentic Build Framework

**Status:** Pre‑alpha | **Architecture:** Agenctic Build Server Leveraging Open & Proprietary LLMs
[![License: Custom](https://img.shields.io/badge/license-SovereignLicense-blue.svg)](https://gitlab.com/smart-assets.io/SovereignLicense)

An autonomous development framework for building, testing, and deploying Smart Assets using **hybrid AI models** - intelligent digital entities that can execute complex operations, manage resources, and interact with various blockchain networks and external services.

**🏠 Privacy-First**: Local MLX models on Apple Silicon for fast, private development
**☁️ Cloud-Powered**: Optional access to Claude-3.5-Sonnet, GPT-4o, and Gemini for complex tasks
**🔄 Intelligent Selection**: Automatic model routing based on task complexity and your preferences

## 🛠️ Works with Your Favorite Tools

This framework is designed to work seamlessly with modern development tools:

### 💻 IDE Integration
- **[Cursor](docs/Cursor_Windsurf__agentic_build.md)** - AI-first code editor with native Claude integration
- **[Windsurf](docs/Cursor_Windsurf__agentic_build.md)** - Collaborative AI development environment
- **[VS Code](docs/Cursor_Windsurf__agentic_build.md)** with GitHub Copilot - Industry-standard editor with AI pair programming
- **[VS Code](docs/Cursor_Windsurf__agentic_build.md)** with Continue - Open-source AI coding assistant

### ⌨️ CLI Tools
- **[Claude Code](docs/Hooks_agentic_build.md)** - Anthropic's official CLI for Claude with git hooks
- **[Aider](docs/Hooks_agentic_build.md)** - AI pair programming in your terminal
- **[GitHub Copilot CLI](docs/Hooks_agentic_build.md)** - Command-line interface for Copilot
- **[Continue CLI](docs/Hooks_agentic_build.md)** - Terminal-based AI assistant

### 🔗 Smart Assets Hooks
For CLI tools, this framework includes **[Smart Assets hooks](https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/tree/master/AItools/hooks)** that provide:
- ✅ **Automatic agentic mode detection** in git worktrees
- 🔒 **Safety enforcement** in main repository
- 🚀 **Autonomous development** in isolated worktrees
- 📊 **Intelligent git workflow management**

---

### 📖 **Complete Documentation Hub**

**[📚 VIEW ALL DOCUMENTATION →](docs/index.md)**

Our comprehensive documentation includes:
- 🎨 **Visual Workflow Diagrams** - Mermaid diagrams showing architecture and workflows
- 💻 **[IDE Integration Guide](docs/Cursor_Windsurf__agentic_build.md)** - Complete setup for Cursor, Windsurf, VS Code, JetBrains
- ⌨️ **[CLI Tools Guide](docs/Hooks_agentic_build.md)** - Setup for Claude Code, Aider with Smart Assets hooks
- 🗺️ **[Documentation Index](docs/index.md)** - Quick navigation to any topic
- ✅ **[Development Roadmap](docs/ToDos.md)** - Current tasks and future features

**Quick Links**:
| I want to... | Go to... |
|--------------|----------|
| **Use Cursor or Windsurf** | [IDE Integration Guide](docs/Cursor_Windsurf__agentic_build.md) |
| **Use Claude Code or Aider** | [CLI Tools & Hooks Guide](docs/Hooks_agentic_build.md) |
| **Find any documentation** | [Documentation Index](docs/index.md) |
| **See visual workflows** | [IDE Guide - Diagrams](docs/Cursor_Windsurf__agentic_build.md#overview) \| [CLI Guide - Diagrams](docs/Hooks_agentic_build.md#smart-assets-hooks-system) |
| **Track development progress** | [ToDos.md](docs/ToDos.md) |

---

## Framework Overview

This agentic build system provides an autonomous development environment that can:

- **Hybrid AI Generation**: Choose between local MLX models and cloud AI for optimal results
- **Autonomous Code Generation**: Generate Smart Asset implementations from high-level specifications
- **Intelligent Testing**: Create comprehensive test suites with quality assessment
- **Cost-Optimized Workflows**: Balance privacy, speed, quality, and cost across model providers
- **Dynamic Optimization**: Continuously improve performance and security
- **Multi-Chain Deployment**: Deploy across multiple blockchain networks
- **Adaptive Configuration**: Self-configure based on deployment environment

## Quick Start

### Prerequisites
- **macOS with Apple Silicon (ARM64)** - Required for local LLM support
- **Python 3.11+** - Python 3.12+ recommended, 3.13+ supported when available
- **uv** - Modern Python package manager (required)
- **direnv** - Automatic environment loading (recommended)
- **Git** - Version control
- **Homebrew** - Package manager for macOS

### System Requirements

This repository is specifically designed to run on **Mac hardware with Apple Silicon** for optimal performance with local LLMs, while also supporting cloud AI models for enhanced capabilities:

#### Local Development (Required)
- **MLX framework** for efficient local LLM inference on Apple Silicon
- **ARM64 native Python packages** for best performance
- **Local AI models** for privacy-first development and unlimited usage

#### Cloud Models (Optional)
- **API keys** for Anthropic Claude, OpenAI GPT, or Google Gemini
- **Internet connection** for cloud model access
- **Cost budgeting** for usage-based pricing (typically $0.10-$0.50 per Smart Asset)

### Installation

#### Step 1: Install Prerequisites

```bash
# Install Homebrew (if not already installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Python (try latest first, fallback to known working versions)
arch -arm64 brew install [email protected]  # Latest version (preferred)
# OR if 3.13 has issues with MLX:
# arch -arm64 brew install [email protected]  # Known working version

# Install uv (modern Python package manager)
brew install uv

# Install direnv for automatic environment loading
brew install direnv

# Add direnv hook to your shell (choose your shell)
echo 'eval "$(direnv hook bash)"' >> ~/.bashrc    # For bash
echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc      # For zsh
echo 'direnv hook fish | source' >> ~/.config/fish/config.fish  # For fish

# Install build dependencies
arch -arm64 brew install pkg-config protobuf cmake
```

#### Step 2: Clone and Setup Project

```bash
# Clone the agentic framework
git clone https://gitlab.com/smart-assets.io/SA_build_agentics.git
cd SA_build_agentics

# Allow direnv to automatically setup the environment
direnv allow

# The .envrc file will automatically:
# - Find the best compatible Python version (3.11+, prefers 3.13+ > 3.12)
# - Create a virtual environment with the selected Python
# - Install MLX and dependencies
# - Activate the environment
# - Verify compatibility and setup
```

#### Alternative: Manual Setup

If you prefer manual setup or direnv isn't available:

```bash
# Create virtual environment with compatible Python (try latest available)
uv venv --python /opt/homebrew/bin/python3.13  # or python3.12

# Activate environment
source .venv/bin/activate

# Install dependencies
uv pip install mlx-lm

# Install project dependencies (if requirements.txt exists)
if [ -f requirements.txt ]; then uv pip install -r requirements.txt; fi

# Initialize the framework
uv run sa-build init
```

### Verification

```bash
# Check that direnv loaded the environment (you should see activation messages)
# If using direnv, the environment should already be active

# Verify Python version and architecture
python -c "import platform; print(f'Python {platform.python_version()} on {platform.machine()}')"
# Expected: Python 3.11+ on arm64 (3.12+ recommended)

# Verify MLX installation and GPU acceleration
python -c "import mlx.core as mx; print(f'MLX {mx.__version__} on {mx.default_device()}')"
# Expected: MLX x.x.x on gpu

# Test local LLM setup
uv run sa-build test-llm

# Verify framework installation
uv run sa-build --version
```

### Daily Usage with direnv

Once set up, direnv will automatically manage your environment:

```bash
# Simply navigate to the project directory
cd path/to/SA_build_agentics
# → direnv will automatically activate the virtual environment

# When you leave the directory
cd ..
# → direnv will automatically deactivate the environment

# To manually reload the environment
direnv reload

# To check environment status
direnv status
```

### Basic Usage

#### Using Local MLX Models (Default)
```bash
# Generate a new Smart Asset with local models
uv run sa-build generate-asset --type oracle --name "ETH Price Oracle"

# List and download MLX models
uv run sa-build models list
uv run sa-build models download --name CodeLlama-7b-Instruct

# Build and test automatically
uv run sa-build agentic-build

# Deploy to target networks
uv run sa-build agentic-deploy --networks ethereum,polygon
```

#### Using Cloud Models (Optional)
```bash
# Configure cloud providers (one-time setup)
export ANTHROPIC_API_KEY="your-key-here"
export OPENAI_API_KEY="your-key-here"
sa-build providers configure

# Generate with specific cloud models
uv run sa-build generate-asset --type oracle --name "ETH Price Oracle" --model claude-3.5-sonnet
uv run sa-build generate-asset --type treasury --name "Multi-Sig Treasury" --model gpt-4o

# List available providers and models
uv run sa-build providers list
uv run sa-build models test --provider anthropic

# Estimate costs before generation
uv run sa-build cost-estimate --type oracle --model claude-3.5-sonnet
```

## Hybrid Model Architecture

This framework supports both **local MLX models** and **cloud-based AI models**, giving you the flexibility to choose the best approach for your needs:

### 🏠 Local Models (MLX Framework)
- **Privacy-First**: Code and data never leave your machine
- **Cost-Effective**: No per-token charges, unlimited usage
- **Fast Iteration**: No network latency, instant feedback
- **Offline Capable**: Works without internet connection
- **Apple Silicon Optimized**: Leverages GPU acceleration and unified memory

### ☁️ Cloud Models (API-Based)
- **State-of-the-Art Quality**: Access to Claude-3.5-Sonnet, GPT-4o, Gemini-1.5-Pro
- **Large Context Windows**: Handle complex Smart Assets with extensive codebases
- **Specialized Capabilities**: Structured outputs, function calling, advanced reasoning
- **No Local Storage**: No need to download large model files

### 🔄 Intelligent Model Selection

The framework automatically chooses the best model for each task:

```bash
# Automatic selection based on task complexity and your preferences
uv run sa-build generate-asset --type oracle --name "Simple Oracle"
# → Uses local MLX model for fast, private generation

uv run sa-build generate-asset --type cross-chain --name "Complex Multi-Chain Bridge" 
# → May suggest cloud model for better quality on complex tasks
```

### Configuration Options

```toml
# .sa-build.toml
[model_selection]
strategy = "local_first"      # "local_first", "cloud_first", or "cost_optimized"
fallback_enabled = true       # Fallback to cloud if local fails
cost_budget_per_asset = 0.50  # Max cost for cloud models (USD)

[providers.anthropic]
api_key_env = "ANTHROPIC_API_KEY"
default_model = "claude-3-5-sonnet-20241022"

[providers.openai] 
api_key_env = "OPENAI_API_KEY"
default_model = "gpt-4o"

[providers.google]
api_key_env = "GOOGLE_API_KEY"
default_model = "gemini-1.5-pro"
```

### Supported Providers

| Provider | Models | Strengths | Best For |
|----------|---------|-----------|----------|
| **Local MLX** | CodeLlama-7B, Qwen2.5-Coder-7B | Privacy, Speed, Cost | Daily development, iteration |
| **Anthropic Claude** | Claude-3.5-Sonnet, Claude-3-Haiku | Code quality, reasoning | Complex Smart Assets |
| **OpenAI GPT** | GPT-4o, GPT-4o-mini | Structured outputs, reliability | Production-ready code |
| **Google Gemini** | Gemini-1.5-Pro, Gemini-1.5-Flash | Large context, multimodal | Complex integrations |

## Rational and ML Development Approach
### Hardware-Optimized Development Strategy

### Why We Chose a Multi-Platform Strategy

Our framework supports both local Apple Silicon development and cloud-based training to maximize efficiency, cost-effectiveness, and accessibility across different project scales and requirements.

#### The Hardware Landscape

Modern ML development spans multiple hardware ecosystems, each optimized for different use cases:

- **Apple Silicon (M3/M4)**: Excellent for development, prototyping, and small-scale training with unified memory architecture and energy efficiency
- **Google Cloud TPUs**: Cost-effective for large-scale training (8 TPU v5e chips at ~$11/hour vs order-of-magnitude higher costs for equivalent GPU compute)
- **AWS Trainium**: Up to 54% lower cost per token compared to traditional GPU clusters
- **NVIDIA GPUs**: Industry standard with broad framework support, though expensive for continuous use

#### Model Format Strategy

Different deployment targets require different optimizations:

- **GGUF**: CPU-optimized format for consumer hardware deployment and inference
- **MLX**: Apple Silicon-specific format leveraging Neural Engine and unified memory (up to 10x faster, 14x less memory for optimized models)
- **Standard PyTorch/TensorFlow**: Cross-platform compatibility for cloud training and production deployment
- **TensorRT/Specialized**: Hardware-specific optimization for production inference

#### Development Workflow Rationale

**Local Development (Apple Silicon)**
- Rapid prototyping and experimentation
- Fine-tuning pre-trained models (<10B parameters)
- Data preprocessing and exploration
- Development environment consistency
- Privacy-sensitive data processing

**Cloud Training (TPU/Trainium)**
- Large-scale model training (>10B parameters)
- Distributed training across multiple accelerators
- Time-critical training deadlines
- Experimentation with cutting-edge architectures

**Cost Optimization**
- Local development eliminates cloud costs during exploration phases
- Cloud training provides access to capabilities impossible on single machines
- Hybrid approach typically breaks even around $10,000 annual cloud spend threshold

#### Framework Benefits  

This multi-platform approach enables:

1. **Seamless Development**: Start locally, scale to cloud when needed
2. **Cost Efficiency**: Pay for cloud compute only when required scale demands it
3. **Hardware Agnostic**: Deploy models across consumer devices (GGUF), Apple ecosystem (MLX), or cloud infrastructure
4. **Future Proofing**: Support for emerging hardware platforms and optimization techniques

The framework abstracts away platform-specific complexities while maintaining the ability to leverage each platform's unique strengths, providing a practical path from research to production deployment.

### Local LLM Architecture

This framework is optimized for **Apple Silicon Macs** and uses local LLMs for privacy, cost-effectiveness, and performance:

### MLX Integration

The framework leverages Apple's **MLX framework** for efficient local AI inference:

```python
# Local LLM configuration
llm_config = {
    "framework": "mlx",
    "models": {
        "code_generation": "mlx-community/CodeLlama-7b-Instruct-hf-4bit-mlx",
        "optimization": "mlx-community/Llama-3.2-3B-Instruct-4bit",
        "testing": "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit"
    },
    "hardware_acceleration": "apple_silicon",
    "memory_optimization": "4bit_quantization"
}
```

### Benefits of Local LLMs

- **🔒 Privacy**: Code and data never leave your machine
- **💰 Cost-effective**: No API usage costs
- **⚡ Performance**: Optimized for Apple Silicon hardware
- **🌐 Offline capable**: Works without internet connection
- **🔄 Consistent**: Reproducible results and behavior

### Supported Models

The framework comes pre-configured with MLX-optimized models:

```bash
# List available local models
uv run sa-build models list

# Download specific model
uv run sa-build models download --name CodeLlama-7b-Instruct

# Switch active model
uv run sa-build models use --name Qwen2.5-Coder-7B
```

## Agentic Architecture

The framework consists of several autonomous agents that work together:

### 1. Code Generation Agent
Automatically generates Smart Asset implementations from specifications:

```python
# Specification Input
oracle_spec = {
    "name": "Multi-Source Price Oracle",
    "data_sources": ["coinbase", "binance", "kraken"],
    "aggregation_method": "weighted",
    "update_interval": 60000,
    "quality_threshold": 0.8
}

# Generated Implementation
generated_asset = await code_agent.generate_asset(oracle_spec)
```

### 2. Testing Agent
Creates comprehensive test suites with automated quality assessment:

```python
# Automatically generates tests for:
# - Unit functionality validation
# - Integration testing across components
# - Performance benchmarking
# - Security vulnerability scanning
# - Quality assurance metrics
```

### 3. Optimization Agent
Continuously improves code quality and performance:

```python
# Optimization targets:
# - Gas efficiency optimization
# - Response time improvements
# - Memory usage optimization
# - Security hardening
# - Code maintainability
```

### 4. Deployment Agent
Manages multi-chain deployment and configuration:

```python
# Handles:
# - Network-specific configuration
# - Contract deployment
# - Service registration
# - Health monitoring
# - Rollback procedures
```

## Smart Asset Types Supported

### Oracle Assets
Autonomous data aggregation systems with multi-source validation:

**Features:**
- Real-time data collection from multiple APIs
- Quality scoring and confidence metrics
- Automatic retry and error handling
- Configurable aggregation methods (average, median, weighted)

**Generated Components:**
- Data source connectors
- Quality assessment algorithms
- Aggregation logic
- Monitoring dashboards

### Treasury Assets
Multi-signature treasury management with automated operations:

**Features:**
- Multi-sig approval workflows
- Automated investment strategies
- Risk assessment and compliance
- Daily withdrawal limits

**Generated Components:**
- Governance contracts
- Investment strategies
- Risk management rules
- Audit trails

### Data Spigot Assets
Decentralized data marketplaces for AI training:

**Features:**
- Quality assessment algorithms
- Contributor compensation systems
- Training job management
- Spam detection and uniqueness verification

**Generated Components:**
- Data quality evaluators
- Payment distribution systems
- Job matching algorithms
- Fraud detection mechanisms

### Cross-Chain Assets
Multi-chain asset management and optimization:

**Features:**
- Cross-chain balance tracking
- Automated arbitrage detection
- Liquidity pool optimization
- Portfolio rebalancing

**Generated Components:**
- Bridge integrations
- Arbitrage engines
- Portfolio managers
- Risk calculators

### Web Widget Assets
Embeddable interactive components:

**Features:**
- Real-time data visualization
- User interaction tracking
- Responsive design
- Customizable themes

**Generated Components:**
- Widget renderers
- Data feed connectors
- Analytics collectors
- Embed code generators

## Agentic Workflows

### 1. Asset Specification to Implementation

```python
# High-level specification
specification = {
    "asset_type": "oracle",
    "name": "Weather Data Oracle",
    "data_sources": [
        {"name": "openweather", "weight": 0.4},
        {"name": "weatherapi", "weight": 0.3},
        {"name": "accuweather", "weight": 0.3}
    ],
    "update_frequency": "5m",
    "quality_threshold": 0.85,
    "geographic_scope": "global"
}

# Autonomous generation process
build_pipeline = await agentic_framework.create_pipeline(specification)
await build_pipeline.execute()
```

### 2. Quality Assurance Pipeline

```python
# Automated quality pipeline
qa_pipeline = {
    "code_quality": {
        "linting": "ruff",
        "type_checking": "mypy-strict",
        "complexity": "max-10",
        "coverage": "min-95%"
    },
    "security": {
        "vulnerability_scanning": "bandit",
        "dependency_audit": "safety",
        "smart_contract_audit": "slither"
    },
    "performance": {
        "gas_optimization": "auto",
        "response_time": "max-500ms",
        "throughput": "min-1000-tps"
    }
}
```

### 3. Multi-Environment Deployment

```python
# Deployment configuration
deployment_config = {
    "environments": {
        "testnet": {
            "networks": ["sepolia", "mumbai"],
            "monitoring": "basic",
            "budget": "unlimited"
        },
        "mainnet": {
            "networks": ["ethereum", "polygon", "arbitrum"],
            "monitoring": "comprehensive",
            "budget": "conservative"
        }
    },
    "rollout_strategy": "blue-green",
    "health_checks": "continuous"
}
```

## Agent Communication

Agents communicate through a distributed event system:

```typescript
// Event-driven agent coordination
interface AgentEvent {
  source: AgentType;
  target: AgentType;
  type: EventType;
  payload: any;
  timestamp: Date;
}

// Example: Code generation complete
const codeCompleteEvent = {
  source: "code-generator",
  target: "test-generator",
  type: "CODE_GENERATED",
  payload: { 
    assetId: "oracle-123",
    files: ["OracleAsset.ts", "config.ts"],
    metadata: { complexity: "medium", dependencies: ["axios", "web3"] }
  }
};
```

## Configuration Management

### Framework Configuration

```typescript
// Framework settings
interface AgenticConfig {
  agents: {
    codeGenerator: {
      model: "codellama-7b" | "qwen2.5-coder-7b" | "llama-3.2-3b";
      framework: "mlx";
      temperature: 0.1;
      maxTokens: 8000;
      quantization: "4bit";
    };
    testGenerator: {
      model: "qwen2.5-coder-7b";
      coverage: "comprehensive" | "standard" | "minimal";
      frameworks: ["vitest", "jest", "hardhat"];
    };
    optimizer: {
      model: "llama-3.2-3b";
      targets: ["gas", "speed", "security"];
      aggressiveness: "conservative" | "moderate" | "aggressive";
    };
  };
  deployment: {
    networks: NetworkConfig[];
    monitoring: MonitoringConfig;
    rollback: RollbackConfig;
  };
  hardware: {
    platform: "apple_silicon";
    memory_optimization: true;
    gpu_acceleration: true;
  };
}
```

### Asset Configuration

```typescript
// Per-asset configuration
interface AssetConfig {
  metadata: {
    name: string;
    description: string;
    version: string;
    tags: string[];
  };
  runtime: {
    updateFrequency: number;
    errorHandling: "strict" | "graceful";
    logging: "minimal" | "detailed";
  };
  integration: {
    apis: APIConfig[];
    blockchains: ChainConfig[];
    services: ServiceConfig[];
  };
}
```

## Monitoring and Observability

### Real-time Monitoring

```typescript
// Comprehensive monitoring system
const monitoringSystem = {
  performance: {
    responseTime: "Real-time latency monitoring",
    throughput: "Transaction per second tracking",
    errorRate: "Error frequency and categorization",
    resourceUsage: "CPU, memory, and network utilization"
  },
  business: {
    dataQuality: "Data accuracy and freshness metrics",
    userEngagement: "User interaction and satisfaction",
    revenue: "Transaction volume and fee collection",
    compliance: "Regulatory and policy adherence"
  },
  technical: {
    uptime: "Service availability tracking",
    security: "Threat detection and prevention",
    scalability: "Load capacity and auto-scaling",
    integration: "Third-party service health"
  }
};
```

### Alerting and Response

```typescript
// Automated incident response
const alertingConfig = {
  triggers: {
    highLatency: "Response time > 1000ms",
    lowDataQuality: "Quality score < 0.7",
    securityThreat: "Unusual access patterns",
    deploymentFailure: "Deployment pipeline errors"
  },
  responses: {
    autoHealing: "Automatic service restart",
    scaling: "Dynamic resource allocation",
    rollback: "Automatic version rollback",
    notification: "Team alert and escalation"
  }
};
```

## Advanced Features

### 1. Continuous Learning

The framework learns from deployment performance and user feedback:

```typescript
// Learning system
const learningSystem = {
  codeOptimization: "Learn from production performance",
  userPreferences: "Adapt to user interaction patterns",
  marketConditions: "Respond to changing market dynamics",
  securityThreats: "Evolve defenses based on attack patterns"
};
```

### 2. Multi-Model Integration

Support for various local AI models optimized for Apple Silicon:

```typescript
// Local model configuration
const modelConfig = {
  codeGeneration: [
    "mlx-community/CodeLlama-7b-Instruct-hf-4bit-mlx",
    "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
    "mlx-community/deepseek-coder-6.7b-instruct-4bit"
  ],
  testGeneration: [
    "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
    "mlx-community/CodeLlama-7b-Instruct-hf-4bit-mlx"
  ],
  optimization: [
    "mlx-community/Llama-3.2-3B-Instruct-4bit",
    "mlx-community/Qwen2.5-3B-Instruct-4bit"
  ],
  monitoring: [
    "mlx-community/Llama-3.2-1B-Instruct-4bit"
  ],
  framework: "mlx",
  hardware: "apple_silicon",
  quantization: "4bit"
};
```

### 3. Ecosystem Integration

Native integration with development and deployment tools:

```typescript
// Ecosystem integrations
const integrations = {
  ide: ["vscode", "jetbrains", "vim"],
  cicd: ["github-actions", "gitlab-ci", "jenkins"],
  cloud: ["aws", "gcp", "azure", "digitalocean"],
  monitoring: ["datadog", "newrelic", "prometheus"],
  security: ["snyk", "veracode", "checkmarx"]
};
```

## Development Workflow

### 1. Specification-Driven Development

```bash
# Create asset specification
uv run sa-build create-spec --interactive

# Generate implementation
uv run sa-build generate --spec specs/my-oracle.yaml

# Review and approve generated code
uv run sa-build review --asset my-oracle

# Deploy to testnet
uv run sa-build deploy --env testnet --asset my-oracle
```

### 2. Iterative Improvement

```bash
# Analyze production performance
uv run sa-build analyze --asset my-oracle --timeframe 7d

# Generate optimization recommendations
uv run sa-build optimize --asset my-oracle --target gas-efficiency

# Apply optimizations
uv run sa-build apply-optimizations --asset my-oracle

# A/B test new version
uv run sa-build test-deployment --strategy ab-test
```

### 3. Multi-Asset Orchestration

```bash
# Create asset ecosystem
uv run sa-build create-ecosystem --name defi-protocol

# Add assets to ecosystem
uv run sa-build add-asset --ecosystem defi-protocol --asset oracle
uv run sa-build add-asset --ecosystem defi-protocol --asset treasury
uv run sa-build add-asset --ecosystem defi-protocol --asset cross-chain

# Deploy entire ecosystem
uv run sa-build deploy-ecosystem --name defi-protocol --env mainnet
```

## Examples and Use Cases

### 1. DeFi Protocol Development

```typescript
// Autonomous DeFi protocol generation
const defiProtocol = {
  components: [
    {
      type: "oracle",
      purpose: "price-feeds",
      assets: ["ETH", "BTC", "USDC"],
      updateFrequency: "30s"
    },
    {
      type: "treasury", 
      purpose: "protocol-treasury",
      governance: "dao",
      strategies: ["yield-farming", "liquidity-provision"]
    },
    {
      type: "cross-chain",
      purpose: "multi-chain-liquidity",
      networks: ["ethereum", "polygon", "arbitrum"],
      bridgeProtocols: ["layerzero", "wormhole"]
    }
  ],
  integration: "automatic",
  governance: "decentralized"
};

await agenticFramework.generateProtocol(defiProtocol);
```

### 2. AI Data Marketplace

```typescript
// Automated AI training data platform
const dataMarketplace = {
  spigots: [
    {
      dataType: "text",
      domains: ["finance", "healthcare", "legal"],
      qualityThreshold: 0.9
    },
    {
      dataType: "image", 
      categories: ["medical", "autonomous-driving", "satellite"],
      qualityThreshold: 0.95
    }
  ],
  compensation: "dynamic-pricing",
  qualityAssurance: "multi-layer",
  privacy: "differential-privacy"
};

await agenticFramework.generateMarketplace(dataMarketplace);
```

### 3. Enterprise Integration

```typescript
// Enterprise-grade Smart Asset deployment
const enterpriseDeployment = {
  compliance: ["SOX", "GDPR", "HIPAA"],
  security: "enterprise-grade",
  scalability: "auto-scaling",
  monitoring: "comprehensive",
  support: "24/7",
  integration: {
    erp: ["sap", "oracle", "microsoft"],
    crm: ["salesforce", "hubspot"],
    databases: ["postgresql", "mongodb", "snowflake"]
  }
};

await agenticFramework.generateEnterprise(enterpriseDeployment);
```

## Testing Framework

### Installing Test Dependencies

Before running tests, install the development and testing dependencies using the optional dependency groups defined in `pyproject.toml`:

```bash
# Install the package with dev and testing dependencies (recommended)
uv pip install -e ".[dev,testing]"

# This installs:
# - pytest, pytest-cov for testing
# - pytest-asyncio, pytest-mock, hypothesis for advanced testing
# - mypy for type checking
# - ruff for linting
# - pre-commit for git hooks
```

**Alternative**: If you prefer separate requirements files, you can also use:

```bash
# Just install individual packages
uv pip install pytest pytest-cov pytest-asyncio pytest-mock hypothesis mypy ruff
```

### Running Tests

```bash
# Run all tests (skip coverage for speed during development)
uv run pytest --no-cov

# Run all tests with coverage report
uv run pytest

# Run tests with verbose output
uv run pytest -v

# Run specific test file
uv run pytest tests/test_agentic_merge.py -v

# Run specific test function
uv run pytest tests/test_agentic_merge.py::test_database_not_included_in_merge -v

# Run tests matching a pattern
uv run pytest -k "agentic" -v

# Run tests with output (shows print statements)
uv run pytest -s -v

# Run tests in parallel (faster)
uv run pytest -n auto

# Run only fast tests (skip slow ones)
uv run pytest -m "not slow"

# Run with coverage and generate HTML report
uv run pytest --cov=sa_build --cov-report=html
# Then open: htmlcov/index.html
```

### Test Organization

Tests are organized to mirror the source code structure:

```
tests/
├── __init__.py
├── test_agentic_merge.py        # Agentic mode merge validation tests
├── test_todo_parser.py           # ToDos.md parsing tests
├── test_worktree_manager.py      # Git worktree management tests
├── test_session_manager.py       # Session database tests
├── test_cli.py                   # CLI command tests
└── integration/                  # Integration tests
    ├── test_agentic_workflow.py
    └── test_full_pipeline.py
```

### Writing Tests

Follow these patterns when writing tests:

```python
import pytest
from pathlib import Path

# Use fixtures for common setup
@pytest.fixture
def temp_repo(tmp_path):
    """Create a temporary git repository."""
    repo = tmp_path / "test_repo"
    repo.mkdir()
    # ... setup code
    return repo

# Test function naming: test_<what>_<expected_behavior>
def test_database_not_included_in_merge(temp_repo):
    """Test that database files are never committed during merge."""
    # Arrange: Set up test conditions
    db_file = temp_repo / ".sa-build" / "agentic-sessions.db"
    db_file.parent.mkdir()
    db_file.write_bytes(b"FAKE_DB")

    # Act: Perform the operation
    result = perform_merge(temp_repo)

    # Assert: Verify expected outcomes
    assert db_file.exists(), "Database should exist on disk"
    assert not is_tracked_by_git(db_file), "Database should not be in git"
```

### Test Markers

Use pytest markers to categorize tests:

```bash
# Run only unit tests
uv run pytest -m "not integration"

# Run only integration tests
uv run pytest -m integration

# Skip slow tests during development
uv run pytest -m "not slow"

# Run only GPU tests (requires GPU)
uv run pytest -m gpu
```

### Continuous Integration

Tests run automatically in CI/CD:

```bash
# Pre-commit checks (run before committing)
uv run pytest --no-cov           # Fast test run
uv run mypy src/                 # Type checking
uv run ruff check                # Linting

# Full CI pipeline (what runs on GitLab)
uv run pytest                    # Full test suite with coverage
uv run mypy src/ --strict        # Strict type checking
uv run ruff check --select ALL   # All linting rules
```

### Automated Test Generation

The framework automatically generates comprehensive test suites:

```bash
# Generate unit tests
uv run sa-build test-gen --type unit --asset my-oracle

# Generate integration tests
uv run sa-build test-gen --type integration --ecosystem defi-protocol

# Generate performance tests
uv run sa-build test-gen --type performance --load-profile high

# Generate security tests
uv run sa-build test-gen --type security --threat-model comprehensive
```

### Quality Metrics

```typescript
// Automated quality assessment
const qualityMetrics = {
  codeQuality: {
    complexity: "Cyclomatic complexity analysis",
    maintainability: "Code maintainability index",
    readability: "Code readability score",
    documentation: "Documentation coverage"
  },
  functionality: {
    correctness: "Functional requirement compliance",
    performance: "Response time and throughput",
    reliability: "Error handling and recovery",
    scalability: "Load handling capacity"
  },
  security: {
    vulnerabilities: "Known vulnerability detection",
    accessControl: "Permission and authentication",
    dataProtection: "Encryption and privacy",
    auditTrail: "Logging and monitoring"
  }
};
```

## Community and Ecosystem

### Open Source Components

```bash
# Contribute to the framework
git clone https://gitlab.com/smart-assets.io/SA_build_agentics.git
cd SA_build_agentics

# Install development dependencies
uv sync --dev

# Run framework tests
uv run pytest

# Submit improvements
git commit -m "Add new agent capability"
git push origin feature/new-capability
```

### Plugin Development

```typescript
// Create custom agents
interface CustomAgent extends Agent {
  name: string;
  capabilities: Capability[];
  execute(context: AgentContext): Promise<AgentResult>;
}

// Register with framework
await agenticFramework.registerAgent(new CustomOptimizationAgent());
```

### Marketplace Integration

The framework integrates with the Smart Assets marketplace at [smart-assets.io](https://www.smart-assets.io/):

- **Asset Templates**: Pre-built Smart Asset templates
- **Agent Marketplace**: Custom agents and capabilities
- **Deployment Services**: Managed deployment and hosting
- **Monitoring Dashboards**: Real-time performance monitoring

## Performance Benchmarks

### Code Generation Performance

```
Asset Type          | Generation Time | Code Quality | Test Coverage
--------------------|-----------------|--------------|---------------
Oracle Asset       | 2.3 minutes     | 9.2/10      | 96%
Treasury Asset      | 4.1 minutes     | 9.0/10      | 94%
Cross-Chain Asset   | 6.8 minutes     | 8.9/10      | 92%
Data Spigot Asset   | 3.7 minutes     | 9.1/10      | 95%
Widget Asset        | 1.9 minutes     | 9.3/10      | 97%
```

### Deployment Performance

```
Network             | Deployment Time | Success Rate | Gas Efficiency
--------------------|-----------------|--------------|----------------
Ethereum Mainnet    | 8.2 minutes     | 99.7%       | 95%
Polygon             | 3.1 minutes     | 99.9%       | 98%
Arbitrum            | 4.6 minutes     | 99.8%       | 97%
Optimism            | 4.2 minutes     | 99.8%       | 96%
```

## Security and Compliance

### Security Framework

```typescript
// Multi-layer security approach
const securityFramework = {
  codeGeneration: {
    staticAnalysis: "Automated vulnerability scanning",
    dependencyCheck: "Known vulnerability database",
    bestPractices: "Secure coding pattern enforcement"
  },
  deployment: {
    accessControl: "Role-based deployment permissions",
    environmentIsolation: "Isolated deployment environments",
    auditLogging: "Complete deployment audit trail"
  },
  runtime: {
    threatDetection: "Real-time threat monitoring",
    anomalyDetection: "Behavioral anomaly detection",
    incidentResponse: "Automated incident response"
  }
};
```

### Compliance Support

```typescript
// Regulatory compliance features
const complianceSupport = {
  frameworks: ["SOX", "GDPR", "HIPAA", "PCI-DSS"],
  features: {
    dataGovernance: "Data classification and handling",
    auditTrails: "Complete operation audit logs",
    accessControls: "Fine-grained permission management",
    reporting: "Automated compliance reporting"
  }
};
```

## Roadmap

### Current Version (1.0)
- ✅ Basic asset generation for Oracle, Treasury, Data Spigot types
- ✅ Automated testing and quality assurance
- ✅ Multi-chain deployment support
- ✅ Real-time monitoring and alerting

### Next Release (1.1) - Q2 2024
- 🔄 Advanced Cross-Chain Asset generation
- 🔄 Widget Asset framework
- 🔄 Enhanced security scanning
- 🔄 Performance optimization agents

### Future Releases (1.2+)
- 📋 Atomic Networked Services framework
- 📋 Composeable Micropayment Networks
- 📋 Crowd Funded Collective Action systems
- 📋 Enterprise-grade governance tools

## Contributing

We welcome contributions to the Smart Assets Agentic Build Framework:

1. **Fork the repository**: Create your own fork of the project
2. **Create a feature branch**: `git checkout -b feature/amazing-feature`
3. **Make your changes**: Implement your feature or bug fix
4. **Add tests**: Ensure your changes are thoroughly tested
5. **Submit a pull request**: Open a PR with a clear description

### Development Setup

```bash
# Clone your fork
git clone https://gitlab.com/yourusername/SA_build_agentics.git

# Install dependencies
uv sync

# Set up development environment
uv run sa-build setup-dev

# Run tests
uv run pytest

# Start development server
uv run sa-build dev
```

## License
[![License: Custom](https://img.shields.io/badge/license-SovereignLicense-blue.svg)](https://gitlab.com/smart-assets.io/SovereignLicense)

## Agentic Development Mode

> **📖 Complete Documentation**: [IDE Integration Guide](docs/Cursor_Windsurf__agentic_build.md) | [CLI Tools Guide](docs/Hooks_agentic_build.md) | [Documentation Index](docs/index.md)
>
> **🎨 Visual Guides**: See [workflow diagrams](docs/Cursor_Windsurf__agentic_build.md#overview) and [hook architecture diagrams](docs/Hooks_agentic_build.md#smart-assets-hooks-system) for visual explanations

### What is Agentic Development?

**Agentic Development Mode** enables fully autonomous AI-driven development using git worktrees. This mode allows AI agents to work independently on isolated branches, automatically selecting and implementing tasks from your project's todo list, making commits, running tests, and iterating rapidly without affecting your main working directory.

**Key Benefits**:
- 🚀 **Rapid Prototyping**: AI can experiment freely without manual approval for each git operation
- 🔒 **Isolated Experiments**: Uses git worktrees to keep experiments separate from main codebase
- 🔄 **Parallel Development**: Run multiple AI experiments simultaneously in different worktrees
- 🛡️ **Safe Exploration**: Easy to discard failed experiments or merge successful ones
- 📊 **Progress Tracking**: Automatic checkpointing and session management

### Use Cases

1. **Autonomous Task Implementation**: AI selects tasks from `docs/ToDos.md` and implements them autonomously
2. **Rapid Feature Development**: Let AI implement complete features from specifications
3. **Architectural Exploration**: Test multiple architectural approaches in parallel
4. **Refactoring**: Aggressive code refactoring with automatic rollback capability
5. **Bug Fixing**: Parallel exploration of different bug fix strategies
6. **Batch Processing**: Work through multiple todo items in sequence

### How Git Worktrees Work

Git worktrees allow you to have multiple working directories attached to the same repository:

```bash
# Main repository
/Users/you/project/                    # main branch

# Worktrees for parallel development
/Users/you/project-worktrees/
  ├── feature-oracle-v2/              # feature/oracle-v2 branch
  ├── refactor-agent-system/          # refactor/agent-system branch
  └── experiment-hybrid-model/        # experiment/hybrid-model branch
```

Each worktree:
- Has its own working directory and branch
- Shares the same git history and objects
- Can be developed independently
- Easy to merge back or discard

### Agentic Development Commands

#### Starting Agentic Build

```bash
# Start agentic build - AI selects tasks from docs/ToDos.md
uv run sa-build agentic-build

# Start with specific task/feature
uv run sa-build agentic-build --task "Add Gemini provider support"

# Start with specific AI model
uv run sa-build agentic-build --model claude-3.5-sonnet

# Start with custom worktree location
uv run sa-build agentic-build --worktree-dir ~/experiments

# Work through multiple tasks in sequence
uv run sa-build agentic-build --batch --max-tasks 5
```

What happens:
1. Reads `docs/ToDos.md` and analyzes pending tasks
2. Selects an appropriate task or uses specified task
3. Creates a new git worktree in `.sa-worktrees/<task-name>/`
4. Creates and checks out new branch `agentic/<task-name>`
5. Copies `.sa-build.toml` configuration to worktree
6. Disables git safety hooks in the worktree
7. AI works autonomously, making commits and running tests

#### Managing Agentic Sessions

```bash
# Show all active agentic worktrees
uv run sa-build agentic-show

# Check status of current agentic session
uv run sa-build agentic-status

# View changes made in agentic session
uv run sa-build agentic-status --diff

# View commit log for agentic session
uv run sa-build agentic-status --log

# View tasks from docs/ToDos.md
uv run sa-build agentic-show --tasks
```

#### Committing Agentic Work

```bash
# Review and merge agentic changes to main branch
uv run sa-build agentic-commit --merge

# Create a pull request from agentic branch
uv run sa-build agentic-commit --pr

# Commit changes but keep agentic session active
uv run sa-build agentic-commit --continue

# Interactive review of changes before merge
uv run sa-build agentic-commit --interactive
```

#### Cleaning Up Agentic Sessions

```bash
# Abort and discard all changes
uv run sa-build agentic-abort

# Abort but save changes as a stash
uv run sa-build agentic-abort --stash

# Archive successful experiment for later reference
uv run sa-build agentic-archive

# Clean up all completed agentic sessions
uv run sa-build agentic-cleanup
```

### Agentic Mode Configuration

Configure agentic mode behavior in `.sa-build.toml`:

```toml
[agentic]
# Enable/disable agentic mode
enabled = true

# Default location for worktrees
worktree_base = ".sa-worktrees"

# Automatic commit message prefix
commit_prefix = "[Agentic]"

# Maximum number of concurrent agentic sessions
max_sessions = 5

# Auto-cleanup completed sessions after (days)
auto_cleanup_days = 7

# Path to todo list file for task selection
todos_file = "docs/ToDos.md"

# Task selection strategy
task_selection = "auto"  # "auto", "manual", or "sequential"

[agentic.git]
# Allow AI to make commits automatically
auto_commit = true

# Allow AI to push to remote
auto_push = false  # Keep false for safety

# Auto-rebase on main before merge
auto_rebase = true

# Required checks before merge
require_tests = true
require_lint = true

[agentic.safety]
# Create backup branch before starting
backup_enabled = true

# Automatic checkpoints every N minutes
checkpoint_interval_minutes = 15

# Maximum uncommitted changes before forcing commit
max_uncommitted_changes = 50

# Block operations outside worktree
enforce_worktree_boundary = true

[agentic.ai]
# Default model for YOLO mode
default_model = "local_mlx"  # or "claude-3.5-sonnet"

# Allow model to make breaking changes
allow_breaking_changes = false

# Require approval for dependency changes
approve_dependency_changes = true
```

### Agentic Prompt Templates

#### Overview

Agentic prompts should be stored under revision control in `templates/agents/` for reusability, sharing, and version management. This allows you to build a library of proven prompts that can be reused across tasks and shared with your team.

#### Directory Structure

```
templates/
└── agents/
    ├── code-generation/
    │   ├── smart-contract.md
    │   ├── api-endpoint.md
    │   └── typescript-component.md
    ├── testing/
    │   ├── unit-tests.md
    │   ├── integration-tests.md
    │   └── e2e-tests.md
    ├── refactoring/
    │   ├── extract-method.md
    │   ├── optimize-performance.md
    │   └── improve-types.md
    └── documentation/
        ├── api-docs.md
        ├── architecture-docs.md
        └── inline-comments.md
```

#### Template Format

Each template should be a markdown file with clear sections:

```markdown
# Template Name

## Purpose
Brief description of what this template accomplishes.

## When to Use
- Use case 1
- Use case 2
- Use case 3

## Context Required
- Required information (e.g., file paths, function names)
- Optional context that improves results
- Environment setup needed

## Prompt Template

[Your reusable prompt goes here with placeholders for variables]

Example:
```
Implement a TypeScript {{component_type}} for {{feature_name}} that:
- Follows the existing architecture in {{reference_file}}
- Includes comprehensive error handling
- Has 90%+ test coverage
- Uses type-safe patterns throughout
```

## Expected Outcomes
- List of deliverables
- Quality criteria
- Success metrics

## Post-Task Checklist
- [ ] Tests pass
- [ ] Linting passes
- [ ] Documentation updated
- [ ] Code reviewed
```

#### Using Templates in Agentic Mode

**Option 1: Reference from Command Line**

```bash
# Use a specific template
uv run sa-build agentic-build --template templates/agents/code-generation/smart-contract.md

# Use template with variable substitution
uv run sa-build agentic-build \
  --template templates/agents/code-generation/api-endpoint.md \
  --vars '{"feature_name": "user authentication", "framework": "FastAPI"}'
```

**Option 2: Reference in docs/ToDos.md**

```markdown
## ToDo: Implement User Authentication API

**Template**: `templates/agents/code-generation/api-endpoint.md`
**Variables**:
- feature_name: "user authentication"
- framework: "FastAPI"
- auth_method: "JWT"

**Context**:
- Reference existing patterns in `src/api/auth/`
- Use existing database models from `src/models/user.py`
```

**Option 3: Direct AI Invocation**

When working with Claude Code or other AI tools directly:

```bash
# In your agentic session, reference the template
claude-code "Follow the template in templates/agents/testing/unit-tests.md
to create tests for the new UserService class"
```

#### Best Practices

**1. Template Versioning**
- Keep templates under git version control
- Tag stable template versions for reproducibility
- Document breaking changes in template CHANGELOG

**2. Template Organization**
- Group by task type (code-generation, testing, refactoring)
- Use clear, descriptive filenames
- Include examples in template comments

**3. Variable Placeholders**
- Use consistent placeholder syntax: `{{variable_name}}`
- Document all required and optional variables
- Provide default values where appropriate

**4. Template Reusability**
- Write templates to be project-agnostic where possible
- Include adaptation instructions for different contexts
- Provide both minimal and comprehensive variants

**5. Quality Assurance**
- Test templates on real tasks before committing
- Collect metrics on template success rates
- Iteratively improve based on outcomes

**6. Sharing and Collaboration**
- Share successful templates across Smart Assets repositories
- Contribute general-purpose templates to community
- Document domain-specific adaptations

#### Example Templates

**Smart Contract Generation Template** (`templates/agents/code-generation/smart-contract.md`):

```markdown
# Smart Contract Generation

## Purpose
Generate production-ready Solidity smart contracts with comprehensive testing.

## Prompt Template
Generate a Solidity smart contract for {{contract_purpose}} that:

1. **Contract Structure**:
   - Implements {{interface_name}} interface
   - Inherits from {{base_contracts}}
   - Uses {{solidity_version}} syntax

2. **Functionality**:
   {{#each functions}}
   - {{this.name}}: {{this.description}}
   {{/each}}

3. **Security Requirements**:
   - Include ReentrancyGuard for state-changing functions
   - Implement access control with {{access_pattern}}
   - Add input validation for all public functions
   - Include pause mechanism for emergencies

4. **Testing**:
   - Unit tests with Hardhat
   - Cover all function paths
   - Include edge cases and failure scenarios
   - Gas optimization tests

5. **Documentation**:
   - NatSpec comments for all functions
   - README with deployment instructions
   - Architecture diagram

## Expected Outcomes
- Fully documented Solidity contract
- Comprehensive test suite (>95% coverage)
- Deployment scripts for multiple networks
- Gas usage report
```

**Testing Template** (`templates/agents/testing/unit-tests.md`):

```markdown
# Unit Test Generation

## Purpose
Generate comprehensive unit tests for existing code.

## Prompt Template
Generate unit tests for {{module_path}} that:

1. **Test Coverage**:
   - Test all public methods/functions
   - Cover edge cases and error conditions
   - Include boundary value testing
   - Target >90% code coverage

2. **Test Structure**:
   - Use {{test_framework}} (pytest/jest/vitest)
   - Follow AAA pattern (Arrange, Act, Assert)
   - Mock external dependencies
   - Use descriptive test names

3. **Test Quality**:
   - Each test should test one thing
   - Tests should be independent
   - Use fixtures for common setup
   - Include negative test cases

4. **Documentation**:
   - Docstrings explaining test purpose
   - Comments for complex assertions
   - Test data explanation

## Expected Outcomes
- Test file mirroring source structure
- All tests passing
- Coverage report showing >90%
- Documentation of test approach
```

#### Maintaining Template Library

**Regular Review Process**:

```bash
# Quarterly template review
uv run sa-build template-review --metrics

# Shows:
# - Template usage frequency
# - Success rate by template
# - Average time savings
# - User feedback scores

# Update templates based on learnings
uv run sa-build template-update --based-on recent-successes
```

**Template Metrics** (future feature):

```toml
# .sa-build.toml
[templates]
# Track template usage and outcomes
collect_metrics = true
feedback_enabled = true

# Suggest templates based on task analysis
auto_suggest = true
```

### Agentic Mode Safety Features

#### 1. Automatic Checkpointing

Agentic mode automatically creates checkpoints:

```bash
# Checkpoints are created every 15 minutes (configurable)
agentic/task-name
├── checkpoint-001  # Initial state
├── checkpoint-002  # After 15 minutes
├── checkpoint-003  # After 30 minutes
└── main           # Current state

# Restore from checkpoint
uv run sa-build agentic-restore --checkpoint 002
```

#### 2. Worktree Isolation

All agentic work happens in isolated worktrees:

```bash
# Main repository remains unchanged
/project/                     # Your normal work continues here

# Agentic experiments are isolated
/project/.sa-worktrees/
  ├── feature-a/             # Experiment A
  └── feature-b/             # Experiment B
```

#### 3. Pre-Merge Validation

Before merging agentic work:

```bash
# Automatic validation runs:
1. All tests must pass (pytest)
2. Linting must pass (ruff)
3. Type checking must pass (mypy)
4. No conflicts with main branch
5. Code review checklist

# Manual review option
uv run sa-build agentic-commit --review
```

#### 4. Rollback Capabilities

Multiple rollback options:

```bash
# Rollback to previous checkpoint
uv run sa-build agentic-rollback --checkpoint 002

# Rollback specific file
uv run sa-build agentic-rollback --file src/agents/code_generator.py

# Complete rollback to start
uv run sa-build agentic-rollback --hard
```

### Workflow Examples

#### Example 1: Autonomous Task Implementation

```bash
# Start agentic build - AI reads docs/ToDos.md and picks a task
uv run sa-build agentic-build

# AI autonomously:
# 1. Analyzes pending tasks in docs/ToDos.md
# 2. Selects "Add Gemini provider support" task
# 3. Creates provider implementation
# 4. Writes comprehensive tests
# 5. Updates documentation
# 6. Makes multiple commits with detailed messages
# 7. Marks task as completed in docs/ToDos.md

# Review progress
uv run sa-build agentic-status
# Output:
# ✓ Task: Add Gemini provider support
# ✓ 12 commits made
# ✓ 847 lines added
# ✓ All tests passing
# ✓ Code quality: 9.2/10

# Merge to main
uv run sa-build agentic-commit --merge
```

#### Example 2: Batch Task Processing

```bash
# Work through multiple tasks sequentially
uv run sa-build agentic-build --batch --max-tasks 3

# AI autonomously:
# 1. Implements "Add Anthropic Claude integration" (45 minutes)
# 2. Implements "Add OpenAI integration" (40 minutes)
# 3. Implements "Intelligent model routing system" (60 minutes)
# Each task results in passing tests and proper commits

# Review all completed work
uv run sa-build agentic-status

# Merge all changes
uv run sa-build agentic-commit --merge
```

#### Example 3: Parallel Architectural Exploration

```bash
# Terminal 1: Try approach A
uv run sa-build agentic-build --task "refactor agent system with observer pattern"

# Terminal 2: Try approach B
uv run sa-build agentic-build --task "refactor agent system with event-driven architecture"

# Terminal 3: Try approach C
uv run sa-build agentic-build --task "refactor agent system with actor model"

# Compare results from main repo
uv run sa-build agentic-show
# Lists all three approaches with metrics

# Choose best approach and merge
cd .sa-worktrees/refactor-agent-system-event-driven/
uv run sa-build agentic-commit --merge

# Discard others
uv run sa-build agentic-abort --session refactor-observer
uv run sa-build agentic-abort --session refactor-actor
```

### Integration with CI/CD

Agentic branches can integrate with CI/CD:

```yaml
# .gitlab-ci.yml
agentic-validation:
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^agentic\//'
  script:
    - uv run pytest
    - uv run mypy src/
    - uv run ruff check
    - uv run sa-build agentic-status --validate
  allow_failure: true  # Don't block on experimental branches
```

### Agentic Mode vs. Normal Mode

| Feature | Normal Mode | Agentic Mode |
|---------|------------|-----------|
| Task Selection | Manual | Auto from docs/ToDos.md |
| Git Commits | Manual approval required | Automatic |
| Git Push | Blocked | Configurable |
| File Access | Repository only | Worktree only |
| Hook Restrictions | Strict | Relaxed |
| Rollback | Manual | Automatic checkpoints |
| Risk Level | Low | Medium (isolated) |
| Speed | Slower (approvals) | Fast (autonomous) |
| Best For | Production work | Task implementation |

### Best Practices for Agentic Mode

1. **Maintain docs/ToDos.md**: Keep your todo list updated for AI to select tasks
2. **Review Before Merge**: Always review agentic-generated code before merging to main
3. **Use Batch Mode for Related Tasks**: Process multiple related tasks in sequence
4. **Regular Checkpoints**: Don't disable automatic checkpointing
5. **Test Everything**: Ensure all tests pass before merging agentic work
6. **Clean Up**: Regularly clean up completed or abandoned agentic sessions
7. **Backup Important Work**: Archive successful experiments for future reference
8. **Task Granularity**: Break large tasks into smaller, manageable items in docs/ToDos.md

### Setting Up Hooks for Agentic Build

For agentic development to work properly, the hooks must be installed correctly. Here's the complete setup:

#### Quick Setup (5 minutes)

```bash
# 1. Create hooks directory
mkdir -p ~/.claude/hooks

# 2. Link hooks from parent repository (recommended)
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/agentic-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/git-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/project-boundary-hook.sh ~/.claude/hooks/

# 3. Install jq if not already installed
brew install jq

# 4. Configure Claude Code
# Add to ~/.claude/config.json:
cat > ~/.claude/config.json << 'EOF'
{
  "hooks": {
    "pre_tool_use": [
      {
        "name": "agentic-mode-detection",
        "path": "~/.claude/hooks/agentic-hook.sh",
        "tools": ["*"]
      },
      {
        "name": "git-safety",
        "path": "~/.claude/hooks/git-hook.sh",
        "tools": ["Bash"]
      },
      {
        "name": "project-boundary",
        "path": "~/.claude/hooks/project-boundary-hook.sh",
        "tools": ["Read", "Edit", "Write", "MultiEdit", "Glob", "Grep"]
      }
    ]
  }
}
EOF

# 5. Verify setup
ls -la ~/.claude/hooks/
cat ~/.claude/config.json | jq '.hooks'
which jq
```

#### Verify Agentic Mode Works

```bash
# Create a test worktree
cd ~/src/SA/SA_build_agentics
git worktree add .sa-worktrees/test-setup agentic/test-setup

# Navigate to worktree
cd .sa-worktrees/test-setup

# In Claude Code, verify agentic mode:
# 1. Try: git commit --allow-empty -m "test"
#    Should: Succeed without prompts
# 2. Try: echo "test" > test.txt
#    Should: Succeed without boundary checks
# 3. Check: git status
#    Should: Show the new commit

# Clean up test
cd ../../
git worktree remove .sa-worktrees/test-setup
git branch -D agentic/test-setup
```

#### What Happens When Agentic Build Runs

```bash
# When you run: uv run sa-build agentic-build

# 1. Creates worktree at: .sa-worktrees/<task-name>/
# 2. The .git file in worktree points to: ../.git/worktrees/<task-name>
# 3. agentic-hook.sh detects this and sets yolo_mode: true
# 4. git-hook.sh sees yolo_mode and allows all git operations
# 5. project-boundary-hook.sh sees yolo_mode and skips boundary checks
# 6. Claude Code can now commit, push, and access files freely
```

#### Common Issues

**Issue: Hooks not detected**
```bash
# Check hook paths are correct
ls -la ~/.claude/hooks/
# Should show all three hooks with proper permissions

# Check Claude Code config
cat ~/.claude/config.json | jq '.hooks.pre_tool_use'
# Should show all three hooks configured
```

**Issue: jq not found**
```bash
# Install jq
brew install jq

# Verify installation
which jq
jq --version
```

**Issue: Agentic mode not activating**
```bash
# Verify you're in a worktree
cd .sa-worktrees/<your-task>/
git rev-parse --git-dir
# Should show: ../.git/worktrees/<your-task>

# Check .git file
file .git
# Should show: .git: ASCII text (not a directory)

cat .git
# Should show: gitdir: ../.git/worktrees/<your-task>
```

**Issue: Permission denied on hooks**
```bash
# Make hooks executable
chmod +x ~/.claude/hooks/*.sh

# Verify permissions
ls -la ~/.claude/hooks/
# Should show: -rwxr-xr-x (executable)
```

### Troubleshooting Agentic Mode

#### Agentic Session Won't Start

```bash
# Check for existing sessions
uv run sa-build agentic-show

# Verify docs/ToDos.md exists and has tasks
cat docs/ToDos.md

# Clean up stale sessions
uv run sa-build agentic-cleanup --force

# Check git worktree status
git worktree list
```

#### No Tasks Available

```bash
# Verify todos file location
uv run sa-build agentic-show --tasks

# Check configuration
cat .sa-build.toml | grep todos_file

# Manually specify task
uv run sa-build agentic-build --task "implement feature X"
```

#### Merge Conflicts

```bash
# Update agentic branch with latest main
uv run sa-build agentic-sync

# Interactive conflict resolution
uv run sa-build agentic-resolve-conflicts

# Abort and restart if needed
uv run sa-build agentic-abort
uv run sa-build agentic-build --task same-task
```

#### Performance Issues

```bash
# Check worktree disk usage
uv run sa-build agentic-disk-usage

# Prune old checkpoints
uv run sa-build agentic-prune-checkpoints --older-than 7d

# Optimize git repository
uv run sa-build agentic-optimize
```

### Cross-Repository Agentic Mode

This framework is designed for use across all Smart Assets repositories. Enable agentic mode in any Smart Asset project:

```bash
# In any Smart Asset repository
cd ~/src/smart-asset-oracle
uv run sa-build agentic-build  # Reads oracle repo's docs/ToDos.md

# In another repository simultaneously
cd ~/src/smart-asset-treasury
uv run sa-build agentic-build  # Reads treasury repo's docs/ToDos.md

# Manage all agentic sessions from anywhere
uv run sa-build agentic-show --all-repos
```

> **📚 Learn More**:
> - **Using IDEs**: [Complete IDE workflow patterns and examples](docs/Cursor_Windsurf__agentic_build.md#general-ide-workflow-patterns)
> - **Using CLI**: [Complete CLI workflow patterns and examples](docs/Hooks_agentic_build.md#advanced-cli-workflows)
> - **Visual Diagrams**: [Task-driven development flowchart](docs/Cursor_Windsurf__agentic_build.md#pattern-1-task-driven-development) | [Hook architecture diagram](docs/Hooks_agentic_build.md#hook-architecture)
> - **Find Anything**: [Documentation Index](docs/index.md) - Quick navigation to any topic

---

## Claude Code Integration

> **📖 Complete Hook Documentation**: [CLI Tools & Hooks Guide](docs/Hooks_agentic_build.md)
>
> **🎨 Visual Architecture**: See [hook system diagrams](docs/Hooks_agentic_build.md#smart-assets-hooks-system) showing how hooks automatically detect and manage agentic mode

### Overview

This project includes custom hooks for Claude Code that enhance the development experience by enforcing project boundaries and git workflow safety. These hooks are based on the Smart Assets GitLab profile tools available at [gitlab.com/smart-assets.io/gitlab-profile](https://gitlab.com/smart-assets.io/gitlab-profile/-/tree/master/AItools/hooks).

**Note**: Hooks are automatically disabled in agentic mode to allow autonomous development. See [Agentic Development Mode](#agentic-development-mode) for details.

### Available Hooks

#### 1. Agentic Development Hook (`agentic-hook.sh`)

**NEW**: This hook automatically detects git worktrees and enables agentic development mode, allowing Claude Code to work autonomously in isolated environments.

**Purpose**: Automatically enable permissive mode when working in git worktrees for agentic development while maintaining strict safety in the main repository.

**How It Works**:
- Detects if Claude Code is running in a git worktree (checks for `.git` file or `worktrees/` in git-dir path)
- If in a worktree: Sets `yolo_mode: true` metadata and approves permissive operations
- If in main repository: Defers to normal safety hooks

**When Activated**:
- Automatically when running in `.sa-worktrees/` directories
- When `git rev-parse --git-dir` contains `worktrees/`
- When `.git` is a file (worktree marker) instead of a directory

**Benefits**:
- No manual configuration needed for agentic development
- Automatic safety enforcement - strict in main repo, permissive in worktrees
- Seamless transition between normal and agentic modes

**Implementation**:
```bash
#!/usr/bin/env bash
# Detects git worktrees and enables permissive mode

input=$(cat)
cwd=$(echo "$input" | jq -r '.cwd // "'"$(pwd)"'"')
cd "$cwd" 2>/dev/null || exit 0

# Check if this is a worktree
git_dir=$(git rev-parse --git-dir 2>/dev/null)
if [ -f "$cwd/.git" ] || [[ "$git_dir" == *"/worktrees/"* ]]; then
    # Enable agentic mode
    echo "{\"decision\": \"approve\", \"metadata\": {\"yolo_mode\": true}}"
    exit 0
fi
exit 0
```

#### 2. Git Command Safety Hook (`git-hook.sh`)

This hook provides safe git command execution by controlling which git operations Claude Code can perform automatically. **It automatically detects worktrees and becomes permissive in agentic mode.**

**Purpose**: Prevent accidental or unsafe git operations while allowing safe git commands to execute normally (in main repo).

**Agentic Mode Behavior**:
- **In Worktrees**: All git operations allowed automatically (commits, push, rebase, reset)
- **In Main Repo**: Strict safety enforcement as described below

**Normal Mode Behavior** (main repository):
- **Blocked Commands** (requires manual execution):
  - `git commit` - Commits should be reviewed before execution
  - `git rebase` - Rebase operations require careful consideration
  - `git reset` - Reset operations can lose data
  - `git push` - Push operations should be intentional

- **Permission-Required Commands** (asks for user approval):
  - `git add` - Requires confirmation before staging files
  - `git mv` - Requires confirmation before moving/renaming files

- **Allowed Commands** (execute automatically):
  - `git status` - Safe read-only operation
  - `git diff` - Safe read-only operation
  - `git log` - Safe read-only operation
  - All non-git commands - Pass through normally

**Implementation**:
```bash
#!/usr/bin/env bash

input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command // empty')

# Check for worktree - if true, allow all operations
cwd=$(echo "$input" | jq -r '.cwd // "'"$(pwd)"'"')
cd "$cwd" 2>/dev/null || exit 0

is_worktree=false
if git rev-parse --is-inside-work-tree &>/dev/null; then
    git_dir=$(git rev-parse --git-dir 2>/dev/null)
    if [ -f "$cwd/.git" ] || [[ "$git_dir" == *"/worktrees/"* ]]; then
        is_worktree=true
    fi
fi

# Agentic mode: allow all git operations in worktrees
if [ "$is_worktree" = true ]; then
    exit 0
fi

# Normal mode restrictions
case "$cmd" in
    "git commit"*|"git rebase"*|"git reset"*|"git push"*)
        echo "{\"decision\": \"block\", \"reason\": \"...\"}"
        exit 0
        ;;
    # ... rest of logic
esac
```

#### 3. Project Boundary Enforcement Hook (`project-boundary-hook.sh`)

This hook ensures that Claude Code only accesses files within the project's git repository boundary. **It automatically detects worktrees and skips boundary checks in agentic mode.**

**Purpose**: Maintain project isolation and prevent unintended file access outside the git repository (in main repo).

**Agentic Mode Behavior**:
- **In Worktrees**: All file access restrictions lifted (full access within worktree)
- **In Main Repo**: Strict boundary enforcement as described below

**Normal Mode Behavior** (main repository):

**Behavior**:
- **Within Git Repository**: All file operations allowed within the git root
- **Outside Git Repository**:
  - Blocks access by default
  - Special case: Allows `~/.claude/` directory with user permission
  - Respects `CLAUDESAFEPATH` environment variable for approved directories

**File Operations Monitored**:
- `Read` - Reading file contents
- `Edit` - Editing files
- `Write` - Writing new files
- `MultiEdit` - Batch editing operations
- `Glob` - File pattern matching
- `Grep` - Content searching

**Environment Variable: CLAUDESAFEPATH**

You can define additional safe paths outside your git repository using the `CLAUDESAFEPATH` environment variable (colon-separated paths):

```bash
# Allow access to specific directories
export CLAUDESAFEPATH="/path/to/shared/lib:/path/to/common/config"

# Add to your shell profile for persistence
echo 'export CLAUDESAFEPATH="/path/to/shared/lib:/path/to/common/config"' >> ~/.zshrc
```

**Implementation Details**:
```bash
#!/usr/bin/env bash

input=$(cat)
cwd=$(echo "$input" | jq -r '.cwd // "'"$(pwd)"'"')
cd "$cwd" 2>/dev/null || cd "$(pwd)"

# Check for worktree - if true, skip all boundary checks
is_worktree=false
if git rev-parse --is-inside-work-tree &>/dev/null; then
    git_dir=$(git rev-parse --git-dir 2>/dev/null)
    if [ -f "$cwd/.git" ] || [[ "$git_dir" == *"/worktrees/"* ]]; then
        is_worktree=true
    fi
fi

# Agentic mode: skip all boundary checks in worktrees
if [ "$is_worktree" = true ]; then
    exit 0
fi

# Normal mode: enforce boundaries
git_root=$(git rev-parse --show-toplevel 2>/dev/null)

if [[ "$abs_file" != "$abs_git_root"* ]]; then
    # Special cases: ~/.claude/ or CLAUDESAFEPATH
    # ... boundary enforcement logic
fi
```

### Installing Hooks

#### Option 1: Install from Parent Repository (Recommended)

Since this repository is within the Smart Assets parent structure, you can link directly to the hooks:

```bash
# Create hooks directory in your Claude Code config
mkdir -p ~/.claude/hooks

# Link hooks from parent repository
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/agentic-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/git-hook.sh ~/.claude/hooks/
ln -sf ~/src/SA/top-level-gitlab-profile/AItools/hooks/project-boundary-hook.sh ~/.claude/hooks/

# Verify links
ls -la ~/.claude/hooks/
```

**Benefits of Linking**:
- Hooks auto-update when parent repository is updated
- Single source of truth for all Smart Assets repositories
- No need to manually sync changes

#### Option 2: Manual Installation from GitLab

```bash
# Create hooks directory
mkdir -p ~/.claude/hooks

# Download all three hooks
curl -o ~/.claude/hooks/agentic-hook.sh \
  https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/raw/master/AItools/hooks/agentic-hook.sh

curl -o ~/.claude/hooks/git-hook.sh \
  https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/raw/master/AItools/hooks/git-hook.sh

curl -o ~/.claude/hooks/project-boundary-hook.sh \
  https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/raw/master/AItools/hooks/project-boundary-hook.sh

# Make executable
chmod +x ~/.claude/hooks/*.sh
```

#### Configure Claude Code to Use Hooks

Edit your Claude Code configuration file (`~/.claude/config.json` or via Claude Code settings):

```json
{
  "hooks": {
    "pre_tool_use": [
      {
        "name": "agentic-mode-detection",
        "path": "~/.claude/hooks/agentic-hook.sh",
        "tools": ["*"]
      },
      {
        "name": "git-safety",
        "path": "~/.claude/hooks/git-hook.sh",
        "tools": ["Bash"]
      },
      {
        "name": "project-boundary",
        "path": "~/.claude/hooks/project-boundary-hook.sh",
        "tools": ["Read", "Edit", "Write", "MultiEdit", "Glob", "Grep"]
      }
    ]
  }
}
```

**Hook Order Matters**:
1. `agentic-hook.sh` runs first to detect worktrees and set metadata
2. `git-hook.sh` checks for worktree mode and adjusts git restrictions
3. `project-boundary-hook.sh` checks for worktree mode and adjusts file access

**Note**: The agentic hook applies to ALL tools (`"*"`) to ensure worktree detection happens for every operation.

#### Option 3: Automated Installation with sa-build

Future version of this framework will include:

```bash
# Automated hook installation
uv run sa-build install-hooks

# Install hooks with linking from parent repository
uv run sa-build install-hooks --link

# Configure CLAUDESAFEPATH automatically
uv run sa-build configure-safe-paths --add /path/to/directory

# Verify hook installation and test worktree detection
uv run sa-build test-hooks --agentic
```

### Hook Benefits

1. **Automatic Agentic Mode**: Hooks detect worktrees and automatically enable permissive mode for agentic development
2. **Safety in Main Repo**: Strict safety enforcement when working in the main repository
3. **Security**: Blocks potentially dangerous operations (in main repo only)
4. **Seamless Workflow**: No manual configuration needed to switch between normal and agentic modes
5. **Consistency**: Same hooks work across all Smart Assets repositories
6. **Transparency**: Clear feedback about mode (agentic vs. normal) and why operations are allowed/blocked

### Customizing Hooks

You can customize the hooks to fit your workflow:

**Example: Allow `git add` without permission**

Edit `~/.claude/hooks/git-hook.sh` and move `"git add"*` to the allowed section:

```bash
case "$cmd" in
    # Completely blocked commands
    "git commit"*|"git rebase"*|"git reset"*|"git push"*)
        echo "{\"decision\": \"block\", \"reason\": \"The command '$cmd' is not allowed for safety reasons. Please run this command manually if needed.\"}"
        exit 0
        ;;

    # All other commands (including git add) are allowed
    *)
        exit 0
        ;;
esac
```

**Example: Add additional safe paths dynamically**

Add to your project's `.envrc`:

```bash
# Allow Claude Code to access shared libraries
export CLAUDESAFEPATH="$HOME/shared-libs:$HOME/common-config"
```

### Testing Hooks

After installation, test the hooks in both modes:

#### Test Normal Mode (Main Repository)

```bash
# In main repository
cd ~/src/SA/SA_build_agentics

# Test git command blocking in Claude Code
# Try: git commit -m "test"
# Expected: Blocked with safety message

# Test file boundary enforcement
# Try to read: cat ../some-other-project/file.txt
# Expected: Blocked with project boundary message

# Test CLAUDESAFEPATH
export CLAUDESAFEPATH="/tmp/test-path"
mkdir -p /tmp/test-path
echo "test content" > /tmp/test-path/test.txt
# Try to read: /tmp/test-path/test.txt
# Expected: Requests permission, then allows access
```

#### Test Agentic Mode (Worktree)

```bash
# Create a test worktree
git worktree add .sa-worktrees/test-agentic agentic/test-agentic
cd .sa-worktrees/test-agentic

# Test automatic agentic mode detection
# Try: git commit -m "test in worktree"
# Expected: Allowed automatically (no blocking)

# Test file access in agentic mode
# Try to read any file in worktree
# Expected: Allowed automatically (no boundary checks)

# Verify agentic mode is active
# Claude Code should indicate "agentic mode enabled" in responses
```

#### Verify Hook Configuration

```bash
# Check that all hooks are installed
ls -la ~/.claude/hooks/
# Should show: agentic-hook.sh, git-hook.sh, project-boundary-hook.sh

# Check Claude Code configuration
cat ~/.claude/config.json | jq '.hooks'
# Should show all three hooks configured

# Test jq availability (required for hooks)
which jq
# Should show jq path (install with: brew install jq)
```

### Troubleshooting Hooks

#### Hook Not Executing

```bash
# Verify hook files exist and are executable
ls -la ~/.claude/hooks/
# Should show -rwxr-xr-x permissions

# Make executable if needed
chmod +x ~/.claude/hooks/*.sh

# Check Claude Code configuration
cat ~/.claude/config.json | jq '.hooks'
```

#### Hook Blocking Expected Operations

```bash
# Check hook output for debugging
# Add debug logging to hooks (temporary)
# Add this line after #!/usr/bin/env bash:
# exec 2>> ~/.claude/hooks/debug.log

# View debug log
tail -f ~/.claude/hooks/debug.log
```

#### Permission Prompts Not Appearing

```bash
# Ensure jq is installed (required for JSON parsing)
brew install jq

# Verify jq is in PATH
which jq

# Test hook manually
echo '{"tool_input":{"command":"git add ."}}' | ~/.claude/hooks/git-hook.sh
```

## Troubleshooting

### Common Installation Issues

#### direnv Not Loading Environment
```bash
# Check if direnv is properly installed and hooked
direnv version

# Check if .envrc is allowed
direnv status

# If not allowed, run:
direnv allow

# Reload shell configuration
source ~/.zshrc  # or ~/.bashrc
```

#### MLX Installation Fails
```bash
# Ensure you're using ARM64 Python 3.12
uv venv --python /opt/homebrew/bin/python3.12
source .venv/bin/activate

# Install build dependencies first
arch -arm64 brew install pkg-config protobuf cmake

# Then install MLX
uv pip install mlx-lm
```

#### Environment Not Activating Automatically
```bash
# Check if direnv hook is in your shell config
grep -r "direnv hook" ~/.zshrc ~/.bashrc ~/.config/fish/config.fish

# If missing, add the appropriate hook:
echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc    # for zsh
echo 'eval "$(direnv hook bash)"' >> ~/.bashrc  # for bash

# Restart your shell or source the config
source ~/.zshrc  # or source ~/.bashrc
```

#### Python Version Compatibility
```bash
# Check Python version and architecture
python -c "import platform; print(f'Python {platform.python_version()} on {platform.machine()}')"

# Should output: Python 3.12.x on arm64
```

#### Performance Issues
```bash
# Verify MLX is using GPU acceleration
python -c "import mlx.core as mx; print(f'MLX device: {mx.default_device()}')"

# Should output: MLX device: gpu
```

### Hardware Requirements

- **Minimum**: MacBook Air M1 with 8GB RAM
- **Recommended**: MacBook Pro M2/M3 with 16GB+ RAM
- **Optimal**: Mac Studio M2 Ultra with 64GB+ RAM

## Support & Documentation

### 📚 Documentation Resources

- **[📖 Documentation Index](docs/index.md)** - Central hub for all documentation with quick navigation
- **[💻 IDE Integration Guide](docs/Cursor_Windsurf__agentic_build.md)** - Complete guide for Cursor, Windsurf, VS Code, JetBrains
- **[⌨️ CLI Tools Guide](docs/Hooks_agentic_build.md)** - Setup and usage with Claude Code, Aider
- **[✅ Development Roadmap](docs/ToDos.md)** - Current tasks and future features
- **[🎨 Visual Workflows](docs/Cursor_Windsurf__agentic_build.md#overview)** - Mermaid diagrams showing system architecture

### 🤝 Community & Support

- **Documentation**: [docs.smart-assets.io](https://docs.smart-assets.io)
- **Community**: [Discord](https://discord.gg/smart-assets)
- **Issues**: [GitLab Issues](https://gitlab.com/smart-assets.io/SA_build_agentics/-/issues)
- **Hooks Repository**: [Smart Assets Hooks](https://gitlab.com/smart-assets.io/top-level-gitlab-profile/-/tree/master/AItools/hooks)

---

**Smart Assets Agentic Build Framework** - Autonomous development for the future of digital assets.

For more information about Smart Assets, visit [smart-assets.io](https://www.smart-assets.io/).
Share: