# Synqed Developer Onboarding Guide

Welcome to the Synqed development team! This guide will take you from zero to productive contributor.

**Prerequisites:** Python 3.10+, Git, Basic async/await knowledge  
**Repository Access:** Required (proprietary software)

---

## Table of Contents

1. [Quick Start](#quick-start)
2. [Running Examples - Hands-On Tutorial](#running-examples---hands-on-tutorial)
3. [Project Structure](#project-structure)
4. [Development Environment Setup](#development-environment-setup)
5. [Architecture Overview](#architecture-overview)
6. [Core Components Deep Dive](#core-components-deep-dive)
7. [Development Workflow](#development-workflow)
8. [Testing Strategy](#testing-strategy)
9. [Code Standards](#code-standards)
10. [Contributing Guidelines](#contributing-guidelines)
11. [Common Development Tasks](#common-development-tasks)
12. [Debugging Guide](#debugging-guide)
13. [Release Process](#release-process)

---

## Quick Start

### Get the Code

```bash
# Clone the repository
git clone <repository-url>
cd Synq

# Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode with all dependencies
pip install -e ".[dev,all]"

# Verify installation
python -c "import synqed; print(synqed.__version__)"
```

### Run Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=src/synqed --cov-report=html

# View coverage report
open htmlcov/index.html
```

### Your First Code Change

```bash
# Create a feature branch
git checkout -b your-name/your-feature-name

# Make your changes
# ...

# Run tests
pytest

# Format code
ruff format src/ tests/

# Check linting
ruff check src/ tests/

# Commit your changes
git add .
git commit -m "feat: your feature description"

# Push and create PR
git push origin your-name/your-feature-name
```

---

## Running Examples - Hands-On Tutorial

The best way to understand Synqed is to run the example scripts and observe their terminal output. This section walks you through each example.

### Prerequisites

Before running examples, you'll need:

```bash
# Install additional dependencies
pip install openai anthropic google-generativeai python-dotenv

# Create a .env file in the Synq root directory
cat > .env << EOF
OPENAI_API_KEY=sk-your-key-here
# Optional: Add other providers
# ANTHROPIC_API_KEY=sk-ant-your-key-here
# GOOGLE_API_KEY=your-key-here
EOF
```

### Example 1: Basic Agent and Client (intro/)

This example demonstrates the fundamental agent-client pattern.

#### Step 1: Start the Agent Server

```bash
# Navigate to examples directory
cd examples/intro

# Terminal 1: Start the agent
python agent.py
```

**Expected Output:**
```
Agent running at http://localhost:8000
Ready to receive messages! Run client.py to test it.
```

**What's happening:**
- Creates an agent with name, description, and skills
- Agent uses GPT-4o-mini to process messages
- Starts FastAPI server on port 8000
- Server exposes `/agent-card` and task endpoints

#### Step 2: Connect with a Client

```bash
# Terminal 2: In a separate terminal, run the client
python client.py
```

**Expected Output:**
```
Complete response:
Here are 3 best practices for customer support:

1. Active Listening: Pay full attention to customers...
2. Timely Response: Respond to inquiries quickly...
3. Empathy and Understanding: Show genuine care...

Streaming response:
Once upon a time, in a busy tech company, there lived a helpful robot named Bolt...
[Text appears word by word, creating a typing effect]
```

**What's happening:**
- Client connects to agent at `http://localhost:8000`
- Demonstrates two communication modes:
  - `ask()`: Waits for complete response
  - `stream()`: Receives response in real-time chunks
- Client automatically closes connection when done

#### Step 3: View Agent Card

```bash
# Terminal 2: View agent metadata
python agent_card.py
```

**Expected Output:**
```json
Agent Card:
============================================================
{
  "name": "Customer Support Assistant",
  "description": "Automated support agent...",
  "skills": [
    {
      "id": "customer_support",
      "name": "customer_support",
      ...
    }
  ],
  "capabilities": {
    "streaming": true,
    "push_notifications": false
  }
}
============================================================
Agent Name: Customer Support Assistant
Skills: ['customer_support', 'ticket_routing', 'inquiry_handling']
Streaming: True
```

**What's happening:**
- Fetches agent card from `/.well-known/agent-card.json` endpoint
- Shows agent metadata, skills, and capabilities
- This is the A2A protocol's standard discovery mechanism

**Key Takeaway:** The basic pattern is: Create Agent → Start Server → Connect Client → Communicate

---

### Example 2: Orchestrator Quick Start (intro/)

This example shows intelligent agent routing using an LLM.

```bash
# In Terminal 1 (after stopping agent.py with Ctrl+C)
python orchestrator_quickstart.py
```

**Expected Output:**
```
======================================================================
  ORCHESTRATOR QUICK START
======================================================================

✓ Registered 3 agents

User Task: I want to cook pasta tonight but I need to know what ingredients to buy

🤖 Orchestrator analyzing...

======================================================================
ORCHESTRATION RESULT
======================================================================

📌 Selected Agent(s):

  🎯 RecipeAgent
     Confidence: 75%
     Recommended Skills: recipe_search
     Reasoning: The user is asking about cooking pasta, which requires 
     finding a recipe. The RecipeAgent is specialized in recipe search.

  🎯 ShoppingAgent
     Confidence: 85%
     Recommended Skills: shopping_list
     Reasoning: The user explicitly mentions needing to know what 
     ingredients to buy, which is the core capability of ShoppingAgent.

📋 Execution Plan:
   First, use RecipeAgent to find a pasta recipe, then use ShoppingAgent 
   to generate a shopping list based on the recipe ingredients.

💡 Alternative Options:
   (none for this task)

======================================================================

Trying another task...

User Task: What's the weather like tomorrow?

✓ Selected: WeatherAgent
  Confidence: 95%
  Reasoning: This is a straightforward weather forecast query...

✓ Done!
```

**What's happening:**
- Orchestrator uses GPT-4o to analyze tasks
- Registers 3 agents (RecipeAgent, ShoppingAgent, WeatherAgent)
- Analyzes task text and agent capabilities
- Returns:
  - Selected agent(s) with confidence scores
  - Reasoning for selection
  - Execution plan
  - Alternative options
- Demonstrates multi-agent selection for complex tasks
- Shows single-agent selection for simple tasks

**Key Takeaway:** The Orchestrator uses LLM intelligence to route tasks to appropriate agents without hardcoded rules.

---

### Example 3: Multi-Agent Orchestration (multi-agentic/)

This example shows a complete multi-agent system with the orchestrator.

```bash
# Navigate to multi-agentic directory
cd ../multi-agentic

# Run the orchestrator example
python orchestrator.py
```

**Expected Output:**
```
======================================================================
  INTELLIGENT AGENT ORCHESTRATION WITH LLMs
======================================================================

======================================================================
EXAMPLE 1: Standalone Orchestrator
======================================================================

✓ Registered 4 agents

──────────────────────────────────────────────────────────────────────
Task 1: I want to make pasta carbonara for dinner tonight
──────────────────────────────────────────────────────────────────────

🎯 Selected Agent(s):

  Agent: RecipeAgent
  Confidence: 90.0%
  Skills: recipe_search
  Reasoning: The task involves finding a recipe for a specific dish...

📋 Execution Plan:
  Use RecipeAgent to search for pasta carbonara recipes, providing 
  the user with detailed instructions...

──────────────────────────────────────────────────────────────────────
Task 2: Create a shopping list for a week of healthy meals
──────────────────────────────────────────────────────────────────────

🎯 Selected Agent(s):

  Agent: MealPlannerAgent
  Confidence: 70.0%
  Skills: weekly_meal_plan
  Reasoning: Creating a shopping list for a week requires meal planning...

  Agent: ShoppingAgent
  Confidence: 85.0%
  Skills: create_shopping_list
  Reasoning: Once meals are planned, ShoppingAgent will create the list...

📋 Execution Plan:
  1. Use MealPlannerAgent to create a weekly meal plan
  2. Use ShoppingAgent to generate comprehensive shopping list

[... continues with more tasks ...]

======================================================================
EXAMPLE 2: Orchestrator + TaskDelegator Integration
======================================================================

✓ Started 2 agent servers

Task: Find me a recipe for pasta and create a shopping list for it

🤖 Orchestrator is analyzing and routing the task...

✓ Task completed!

Response:
🍳 Recipe Search Results for: pasta

Recipe: Quick Pasta Carbonara
Ingredients:
- 400g spaghetti
- 200g pancetta or bacon
...

======================================================================
EXAMPLE 3: Multiple LLM Providers
======================================================================

Task: I need a quick dinner recipe

──────────────────────────────────────────────────────────────────────
Testing: OpenAI GPT-4o
──────────────────────────────────────────────────────────────────────
✓ Selected: RecipeAgent
  Confidence: 88.0%
  Reasoning: The user needs a recipe, which is RecipeAgent's specialty...

[If you have other API keys configured, you'll see similar output 
 for Anthropic Claude and Google Gemini]

======================================================================

✓ All examples completed!

Key Takeaways:
1. The Orchestrator uses LLMs to intelligently route tasks
2. You must specify the LLM provider and API key
3. The orchestrator provides confidence scores and reasoning
4. It integrates seamlessly with TaskDelegator
5. Multiple LLM providers are supported (OpenAI, Anthropic, Google)
```

**What's happening:**

**Example 1 - Standalone Orchestrator:**
- Creates 4 specialized agents (Recipe, Shopping, Nutrition, MealPlanner)
- Orchestrator analyzes 4 different tasks
- Shows confidence scores and reasoning for each selection
- Demonstrates multi-agent selection for complex tasks

**Example 2 - With TaskDelegator:**
- Starts agent servers in background on ports 8001-8002
- Creates TaskDelegator with orchestrator integration
- Submits task → Orchestrator selects agent → Delegator executes
- Shows actual agent response (not just routing decision)
- Demonstrates seamless integration

**Example 3 - Multiple Providers:**
- Tests different LLM providers (OpenAI, Anthropic, Google)
- Shows that routing logic works across providers
- Compares confidence and reasoning across models

**Key Takeaway:** This shows production-ready multi-agent systems with intelligent routing, parallel execution, and actual task completion.

---

### Example 4: Enterprise RFP System (multi-agentic/)

This is the most advanced example, showing a real-world enterprise use case.

```bash
# Run the RFP delegation system
python delegator_rfp_system.py
```

**Expected Output:**
```
================================================================================
ENTERPRISE RFP RESPONSE AUTOMATION SYSTEM
Multi-Agent Delegation with Synq Orchestrator + TaskDelegator
================================================================================

✓ API key found

📋 Step 1: Creating specialized agents...

✓ Requirements Analyst created
✓ Technical Architect created
✓ Pricing Analyst created
✓ Compliance Agent created

🚀 Step 2: Starting agent servers...

✓ Requirements Analyst running at http://localhost:8001
✓ Technical Architect running at http://localhost:8002
✓ Pricing Analyst running at http://localhost:8003
✓ Compliance Agent running at http://localhost:8004

🧠 Step 3: Setting up Orchestrator for intelligent routing...

✓ Orchestrator created with GPT-4o
  The orchestrator will analyze each task and select the best agent

🎯 Step 4: Setting up TaskDelegator with Orchestrator...

✓ Registered 4 agents:
  - Requirements Analyst: requirements_analysis, document_parsing, ...
  - Technical Architect: solution_design, cloud_architecture, ...
  - Pricing Analyst: cost_estimation, pricing_strategy, ...
  - Compliance Agent: legal_review, compliance_check, ...

================================================================================
PROCESSING RFP: GlobalCorp Industries Cloud Migration
================================================================================

🔍 Phase 1: Requirements Analysis
--------------------------------------------------------------------------------
🤖 Orchestrator analyzing task and selecting agent...

## Technical Requirements
- Migrate 500+ virtual machines (Windows Server 2016-2022, RHEL 7-8)
- 100TB structured data (SQL Server, Oracle)
- 50TB unstructured data (file shares)
- 24/7 uptime with max 2-hour maintenance window
- Geographic distribution: US (60%), EU (30%), APAC (10%)
- Peak: 50,000 concurrent users
- SAP ERP integration required

## Business Requirements
- 12-month completion timeline
- Phased approach to minimize risk
- Cost optimization vs current $2M annual spend
- Training for 15 engineers
- 24/7 support during and 6 months post-migration

## Compliance Requirements
- SOC 2 Type II certification
- GDPR compliance for EU operations
- ISO 27001 security controls
- Data residency (EU data stays in EU)

## Key Success Criteria
- Minimal downtime during migration
- Cost savings vs current infrastructure
- Regulatory compliance maintained
- Successful team knowledge transfer

## Risk Factors & Considerations
- 24/7 uptime requirement extremely challenging
- SAP integration complexity
- Multi-region data residency requirements
- Tight 12-month timeline with 500+ VMs

⚡ Phase 2: Parallel Processing (Technical Design + Compliance Review)
--------------------------------------------------------------------------------
🤖 Orchestrator routing tasks to appropriate agents in parallel...

TECHNICAL SOLUTION:
--------------------------------------------------------------------------------
## Proposed Architecture
Multi-region cloud architecture using:
- Compute: Auto-scaling VM instances with reserved capacity
- Storage: Tiered storage (hot/cool/archive) for cost optimization
- Databases: Managed database services with automatic failover
- Networking: Global load balancing with geo-routing

Key Services:
- VM Migration Service for lift-and-shift
- Database Migration Service for zero-downtime migration
- Virtual Private Cloud for network isolation
- Cloud CDN for global content delivery

## Migration Strategy
Phase 1 (Months 1-3): Foundation & Non-critical
- Set up cloud networking and security
- Migrate development/test environments
- Establish monitoring and management tools

Phase 2 (Months 4-8): Production Applications
- Migrate production VMs in waves
- Database replication and cutover
- SAP integration testing

Phase 3 (Months 9-12): Optimization & Handoff
- Performance tuning
- Cost optimization
- Team training
- Documentation

## High Availability & DR
- 99.99% uptime SLA through multi-zone deployment
- Active-passive failover for critical systems
- RPO: 15 minutes, RTO: 1 hour
- Automated backups with 30-day retention

[... detailed technical sections ...]

COMPLIANCE ANALYSIS:
--------------------------------------------------------------------------------
## Compliance Requirements Summary
- SOC 2 Type II: Annual audits required
- GDPR: Privacy by design, data subject rights
- ISO 27001: Information security management
- Data Residency: EU data must remain in EU regions

## Compliance Approach

### SOC 2 Type II
- Use cloud provider's SOC 2 certified services
- Implement access controls and audit logging
- Regular security assessments

### GDPR
- Deploy EU resources in EU-only regions
- Implement data encryption at rest and in transit
- Data processing agreements with cloud provider
- Privacy impact assessments

### ISO 27001
- Align security controls with ISO framework
- Implement security monitoring and incident response
- Regular vulnerability assessments

[... detailed compliance sections ...]

💰 Phase 3: Pricing Analysis
--------------------------------------------------------------------------------
🤖 Orchestrator selecting agent for pricing analysis...

## Infrastructure Costs (Annual)
- Compute: $850,000
- Storage: $180,000
- Networking: $120,000
- Databases: $250,000
- Security & Compliance: $150,000
**Subtotal**: $1,550,000/year

## Migration Services (One-Time)
- Planning & Architecture: $300,000
- Migration Execution: $800,000
- Testing & Validation: $250,000
- Training: $100,000
**Subtotal**: $1,450,000

## Support & Maintenance
- 24/7 Support during migration: $200,000
- 6-month post-migration support: $150,000

## Total Investment
- Year 1: $3,350,000 (migration + infrastructure)
- Year 2-3: $1,700,000/year (infrastructure + support)

## ROI Analysis
- Current annual spend: $2,000,000
- Projected annual spend: $1,550,000
- Annual savings: $450,000
- Payback period: 36 months
- 3-year TCO: $6,800,000 vs $8,000,000 (on-premises)

## Cost Optimization Opportunities
- Reserved instances: Save up to 30% on compute
- Auto-scaling: Reduce costs during off-peak hours
- Storage tiering: Archive old data at 70% lower cost

================================================================================
FINAL PROPOSAL SUMMARY
================================================================================

All sections completed successfully!

Proposal Sections Generated:
  1. ✓ Requirements Analysis (orchestrator selected Requirements Analyst)
  2. ✓ Technical Solution & Architecture (orchestrator selected Technical Architect)
  3. ✓ Compliance & Legal Review (orchestrator selected Compliance Agent)
  4. ✓ Pricing & Financial Analysis (orchestrator selected Pricing Analyst)

🧠 Orchestrator Intelligence:
  The orchestrator analyzed each task description and agent capabilities
  to intelligently route tasks to the most appropriate agent without
  requiring manual agent selection. This enables truly autonomous
  multi-agent workflows.

📋 Next Steps:
  - Review all sections for accuracy
  - Add executive summary
  - Include team credentials and past projects
  - Format as professional proposal document
  - Submit before December 1, 2024 deadline

⏱ Time Saved: Traditional process takes 3-5 days, this took ~2 minutes!
🎯 Automation Level: Fully autonomous with intelligent routing

🧹 Cleaning up...
✓ All agents stopped

================================================================================
✨ RFP Response Automation Complete!
================================================================================
```

**What's happening:**

**Phase 1 - Sequential Processing:**
- Submits RFP document for requirements analysis
- Orchestrator selects Requirements Analyst
- Agent uses GPT-4o-mini to extract and structure requirements

**Phase 2 - Parallel Processing:**
- Creates technical and compliance tasks with requirements context
- Both tasks submitted simultaneously with `asyncio.gather()`
- Orchestrator independently selects appropriate agent for each
- Technical Architect designs solution
- Compliance Agent reviews regulations
- Both complete in parallel for efficiency

**Phase 3 - Sequential with Dependencies:**
- Pricing task depends on technical solution output
- Orchestrator selects Pricing Analyst
- Agent calculates costs based on technical architecture

**Cleanup:**
- All 4 servers stop gracefully
- Clients close connections
- Resources cleaned up properly

**Key Takeaway:** This demonstrates a real-world enterprise workflow with:
- 4 specialized agents working together
- Intelligent orchestration without hardcoded routing
- Parallel execution where possible
- Context passing between phases
- Professional output quality

---

### What You Learned

By running these examples, you've seen:

1. **Basic Patterns** (`intro/`):
   - Creating agents with skills and executors
   - Starting servers and connecting clients
   - Streaming vs non-streaming responses
   - Agent card discovery

2. **Intelligent Routing** (`orchestrator_quickstart.py`):
   - LLM-based agent selection
   - Confidence scoring and reasoning
   - Multi-agent task handling

3. **Production Systems** (`multi-agentic/`):
   - Multiple agents working together
   - Integration of Orchestrator + TaskDelegator
   - Background server management
   - Real agent execution with actual responses

4. **Enterprise Workflows** (`delegator_rfp_system.py`):
   - Complex multi-phase workflows
   - Parallel and sequential task execution
   - Context passing between agents
   - Fully autonomous operation

### Next Steps

Now that you've run the examples:

1. **Modify examples**: Try changing agent descriptions or skills and observe how the orchestrator's routing changes
2. **Create your own agent**: Start with a simple agent for a different use case
3. **Read the code**: Examine example source code to understand implementation details
4. **Explore the tests**: See `tests/` for comprehensive test coverage
5. **Deep dive**: Continue to the [Core Components Deep Dive](#core-components-deep-dive) section

---

## 📁 Project Structure

```
Synq/
├── src/synqed/              # Main package source code
│   ├── __init__.py          # Package exports and version
│   ├── agent.py             # Agent wrapper implementation
│   ├── agent_card.py        # AgentCard builder
│   ├── client.py            # Client for connecting to agents
│   ├── server.py            # Server for hosting agents
│   ├── orchestrator.py      # LLM-based intelligent routing
│   └── delegator.py         # Multi-agent coordination
│
├── tests/                   # Test suite
│   ├── conftest.py          # Pytest fixtures and config
│   ├── test_agent.py        # Agent unit tests
│   ├── test_agent_card.py   # AgentCard builder tests
│   ├── test_client.py       # Client tests
│   ├── test_server.py       # Server tests
│   ├── test_orchestrator.py # Orchestrator tests
│   ├── test_delegator.py    # Delegator tests
│   ├── test_integration.py  # Integration tests
│   └── test_e2e.py         # End-to-end tests
│
├── examples/                # Example applications
│   ├── intro/              # Beginner examples
│   │   ├── agent.py
│   │   ├── client.py
│   │   ├── agent_card.py
│   │   └── orchestrator_quickstart.py
│   └── multi-agentic/      # Advanced examples
│       ├── orchestrator.py
│       └── delegator_rfp_system.py
│
├── scripts/                 # Build and utility scripts
│   ├── build_package.sh    # Package build script
│   └── publish.sh          # Publishing script
│
├── dist/                    # Built distribution packages
├── htmlcov/                # Coverage reports
│
├── pyproject.toml          # Project configuration and dependencies
├── pytest.ini              # Pytest configuration
├── MANIFEST.in             # Package manifest for distribution
├── LICENSE                 # Proprietary license
├── README.md               # User-facing documentation
├── DEVELOPER_ONBOARDING.md # This file
└── MASTERY_PATH.md        # Learning curriculum for users
```

### File Responsibilities

| File | Purpose | When to Modify |
|------|---------|----------------|
| `agent.py` | Agent creation and execution | Adding agent features, executor improvements |
| `agent_card.py` | AgentCard building utilities | New card fields, validation logic |
| `client.py` | Client for agent communication | Client features, connection handling |
| `server.py` | Server for hosting agents | Server features, lifecycle management |
| `orchestrator.py` | LLM-based intelligent routing | New LLM providers, routing logic |
| `delegator.py` | Multi-agent task delegation | Delegation strategies, coordination logic |
| `pyproject.toml` | Dependencies, build config | Adding dependencies, version bumps |

---

## Development Environment Setup

### Cloning the Repositories

Synqed builds on top of the A2A protocol. For complete development setup, you should clone the relevant A2A repositories:

```bash
# Create a workspace directory for all A2A projects
mkdir -p ~/workspace/a2a-projects
cd ~/workspace/a2a-projects

# 1. Clone the main A2A protocol repository (specifications, docs)
git clone https://github.com/a2aproject/A2A.git
cd A2A
# Explore: specification/, docs/, types/

# 2. Clone the A2A Python SDK (what Synqed uses)
cd ~/workspace/a2a-projects
git clone https://github.com/a2aproject/a2a-python.git
cd a2a-python
# Install in development mode if you need to modify it
pip install -e .

# 3. Clone the A2A samples repository (examples and demos)
cd ~/workspace/a2a-projects
git clone https://github.com/a2aproject/a2a-samples.git
cd a2a-samples
# Explore: samples/python/, demo/, extensions/

# 4. Clone Synqed (this repository)
cd ~/workspace/a2a-projects
git clone <synqed-repository-url>
cd Synq
pip install -e ".[dev,all]"
```

**Repository Overview:**

| Repository | Purpose | When You Need It |
|-----------|---------|------------------|
| [A2A](https://github.com/a2aproject/A2A) | Protocol specification, types, documentation | Understanding protocol, contributing to spec |
| [a2a-python](https://github.com/a2aproject/a2a-python) | Python SDK implementation | Debugging SDK issues, adding SDK features |
| [a2a-samples](https://github.com/a2aproject/a2a-samples) | Reference implementations and examples | Learning A2A patterns, testing interoperability |
| [a2a-go](https://github.com/a2aproject/a2a-go) | Go SDK (optional) | Testing cross-language agent communication |
| [a2a-js](https://github.com/a2aproject/a2a-js) | JavaScript SDK (optional) | Building web-based agents |
| [a2a-java](https://github.com/a2aproject/a2a-java) | Java SDK (optional) | Enterprise Java agent integration |
| [a2a-dotnet](https://github.com/a2aproject/a2a-dotnet) | .NET SDK (optional) | .NET/C# agent development |

**Quick Start (Minimal Setup):**

If you only want to develop on Synqed without modifying the A2A SDK:

```bash
# Clone only Synqed
git clone <synqed-repository-url>
cd Synq

# Install with all dependencies (includes a2a-sdk from PyPI)
pip install -e ".[dev,all]"
```

### Required Tools

```bash
# Python 3.10 or higher
python --version  # Should be 3.10+

# pip and virtualenv
pip install --upgrade pip setuptools wheel

# Development tools
pip install ruff mypy pytest pytest-asyncio pytest-cov
```

### Optional Tools

```bash
# For better development experience
pip install ipython ipdb  # Better REPL and debugging
pip install pytest-watch  # Continuous testing
pip install pre-commit    # Git hooks
```

### IDE Setup

#### VS Code (Recommended)

`.vscode/settings.json`:
```json
{
    "python.linting.enabled": true,
    "python.linting.ruffEnabled": true,
    "python.formatting.provider": "none",
    "editor.formatOnSave": true,
    "python.testing.pytestEnabled": true,
    "python.testing.unittestEnabled": false,
    "[python]": {
        "editor.defaultFormatter": "charliermarsh.ruff",
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    }
}
```

#### PyCharm

1. Open Project Settings → Python Interpreter
2. Add your virtual environment
3. Enable pytest as test runner
4. Configure Ruff as external tool

### Environment Variables

Create a `.env` file for development (DO NOT COMMIT):

```bash
# .env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_API_KEY=...

# Development settings
LOG_LEVEL=DEBUG
PYTEST_TIMEOUT=30
```

---

## Architecture Overview

### Three-Layer Design

```
┌─────────────────────────────────────────┐
│        User Application Layer           │
│  (Customer code using Synqed)           │
└─────────────────┬───────────────────────┘
                  │
┌─────────────────▼───────────────────────┐
│          Synqed Layer (This!)           │
│  ┌─────────────────────────────────┐   │
│  │ Agent, Client, Server,          │   │
│  │ Orchestrator, Delegator         │   │
│  └─────────────────────────────────┘   │
└─────────────────┬───────────────────────┘
                  │
┌─────────────────▼───────────────────────┐
│           A2A Protocol Layer            │
│  (Agent-to-Agent communication)         │
│  - a2a-sdk package                      │
└─────────────────────────────────────────┘
```

### Core Design Principles

1. **Simplicity First**: Hide A2A complexity behind intuitive APIs
2. **Async by Default**: All I/O operations are async
3. **Type Safety**: Full type hints for better DX
4. **Resource Management**: Automatic cleanup via context managers
5. **Extensibility**: Easy to add new features without breaking existing code

### Component Interactions

```
┌──────────┐                          ┌──────────┐
│  Client  │ ◄──── HTTP/JSON ──────► │  Server  │
└────┬─────┘                          └────┬─────┘
     │                                     │
     │ uses                            hosts
     │                                     │
     ▼                                     ▼
┌──────────────────┐               ┌──────────┐
│  Orchestrator    │ ◄── queries ──│  Agent   │
│  (LLM Routing)   │                └──────────┘
└────┬─────────────┘
     │ uses
     ▼
┌──────────────────┐
│  TaskDelegator   │
│  (Coordination)  │
└──────────────────┘
```

---

## 🔍 Core Components Deep Dive

### 1. Agent (`agent.py`)

**Purpose:** Wraps A2A agent functionality into a simple interface.

**Key Responsibilities:**
- Agent metadata management (name, description, skills)
- Agent card generation
- Executor function management
- Integration with A2A AgentExecutor

**Architecture:**
```python
Agent
├── _card_builder: AgentCardBuilder   # Builds AgentCard
├── _executor_func: Callable          # User's logic
├── _agent_executor: AgentExecutor    # A2A executor
└── card: AgentCard                   # Published card
```

**Critical Methods:**
- `__init__()`: Initialize agent with metadata
- `_create_executor()`: Wrap user function for A2A
- `card` property: Generate AgentCard on demand
- `executor` property: Get A2A executor instance

**Development Notes:**
- Agent cards are generated lazily
- Skills can be strings or detailed dicts
- Executor functions receive RequestContext
- URL is set by AgentServer on startup

### 2. Client (`client.py`)

**Purpose:** Connect to and communicate with agents.

**Key Responsibilities:**
- HTTP/JSON-RPC communication with agents
- Task submission and management
- Streaming response handling
- Automatic agent card discovery

**Architecture:**
```python
Client
├── _agent_client: AgentClient        # A2A client instance
├── agent_url: str                    # Target agent URL
├── agent_card: AgentCard | None      # Cached card
└── _session: aiohttp.ClientSession   # HTTP session
```

**Critical Methods:**
- `ask()`: Blocking request-response
- `stream()`: Streaming response
- `submit_task()`: Create new task
- `get_task()`: Query task status
- `cancel_task()`: Cancel running task
- `get_agent_card()`: Fetch agent capabilities

**Development Notes:**
- Uses aiohttp for HTTP communication
- Supports both streaming and non-streaming modes
- Implements async context manager for cleanup
- Caches agent cards for performance

### 3. Server (`server.py`)

**Purpose:** Host agents and handle incoming requests.

**Key Responsibilities:**
- HTTP server lifecycle management
- Request routing to agent executor
- Task state management
- CORS and security configuration

**Architecture:**
```python
AgentServer
├── _agent: Agent                     # Agent to serve
├── _host: str                        # Bind address
├── _port: int                        # Bind port
├── _app: A2AFastAPIApplication       # FastAPI app
├── _task_store: TaskStore            # Task persistence
└── _server_task: asyncio.Task        # Running server
```

**Critical Methods:**
- `start()`: Start server (blocking)
- `start_background()`: Start server (non-blocking)
- `stop()`: Gracefully shut down
- `_create_request_handler()`: Set up A2A handlers

**Development Notes:**
- Uses FastAPI under the hood (via A2A)
- Supports background execution for multi-agent systems
- Implements graceful shutdown with cleanup
- CancelledError filtering prevents noisy logs

### 4. Orchestrator (`orchestrator.py`)

**Purpose:** Intelligently route tasks to agents using LLMs.

**Key Responsibilities:**
- LLM integration (OpenAI, Anthropic, Google)
- Agent registry management
- Task analysis and routing
- Confidence scoring and reasoning

**Architecture:**
```python
Orchestrator
├── provider: LLMProvider             # OPENAI, ANTHROPIC, GOOGLE
├── _llm_client: Any                  # Provider-specific client
├── model: str                        # Model name
├── _agents: dict[str, tuple]         # Registered agents
└── _routing_cache: dict              # Optional caching
```

**Critical Methods:**
- `register_agent()`: Add agent to registry
- `orchestrate()`: Analyze task and select agent(s)
- `list_agents()`: Get all registered agents
- `_call_llm()`: Provider-specific LLM calling

**Development Notes:**
- Uses structured prompts for consistent routing
- Returns confidence scores (0.0 to 1.0)
- Supports multiple agent selection
- Provider clients are lazy-loaded
- JSON schema validation for LLM responses

**Prompt Engineering:**
The orchestration prompt is critical. It includes:
- Task description
- Agent capabilities (names, descriptions, skills)
- Instructions for JSON response format
- Examples of routing decisions

### 5. TaskDelegator (`delegator.py`)

**Purpose:** Coordinate multiple agents for complex tasks.

**Key Responsibilities:**
- Agent registration and discovery
- Task submission to appropriate agents
- Optional integration with Orchestrator
- Result aggregation

**Architecture:**
```python
TaskDelegator
├── _agents: dict[str, Agent]         # Local agents
├── _agent_cards: dict                # Agent cards
├── _agent_urls: dict                 # Agent URLs
├── _clients: dict[str, Client]       # Client pool
└── _orchestrator: Orchestrator?      # Optional smart routing
```

**Critical Methods:**
- `register_agent()`: Add agent (local or remote)
- `submit_task()`: Delegate task to agent
- `_select_agent()`: Choose appropriate agent
- `_get_or_create_client()`: Client pooling

**Development Notes:**
- Supports both local and remote agents
- Integrates with Orchestrator for intelligent routing
- Maintains client pool for performance
- Can work without Orchestrator (basic routing)

### 6. AgentCardBuilder (`agent_card.py`)

**Purpose:** Build and validate AgentCard objects.

**Key Responsibilities:**
- Fluent API for card construction
- Skill management
- Capability configuration
- Validation and defaults

**Architecture:**
```python
AgentCardBuilder
├── _name: str                        # Agent name
├── _description: str                 # Agent description
├── _skills: list[AgentSkill]         # Skill list
├── _capabilities: dict               # Agent capabilities
└── ... (other card fields)
```

**Critical Methods:**
- `add_skill()`: Add a skill to the agent
- `set_capabilities()`: Configure capabilities
- `build()`: Generate final AgentCard

**Development Notes:**
- Implements builder pattern
- Provides sensible defaults
- Validates inputs
- Generates unique IDs automatically

---

##  Development Workflow

### Branch Strategy

```
main
├── feature/agent-improvements
├── feature/new-llm-provider
├── fix/client-timeout-bug
└── docs/api-documentation
```

**Branch Naming:**
- `feature/*` - New features
- `fix/*` - Bug fixes
- `docs/*` - Documentation
- `refactor/*` - Code refactoring
- `test/*` - Test improvements

### Commit Messages

Follow [Conventional Commits](https://www.conventionalcommits.org/):

```bash
# Format
<type>(<scope>): <description>

[optional body]

[optional footer]

# Examples
feat(orchestrator): add support for Gemini 2.0 models
fix(client): handle connection timeout gracefully
docs(readme): update quick start guide
test(agent): add tests for error handling
refactor(server): simplify shutdown logic
```

**Types:**
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation only
- `test`: Adding tests
- `refactor`: Code restructuring
- `perf`: Performance improvement
- `chore`: Maintenance tasks

### Code Review Process

1. **Create PR** with clear description
2. **Run tests** - All tests must pass
3. **Check coverage** - Maintain >90% coverage
4. **Review feedback** - Address all comments
5. **Squash commits** - Keep history clean
6. **Merge** - After 1+ approvals

### PR Template

```markdown
## Description
Brief description of changes

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Refactoring

## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] Manual testing performed

## Checklist
- [ ] Code follows style guide
- [ ] Tests pass locally
- [ ] Coverage maintained/improved
- [ ] Documentation updated
- [ ] No breaking changes (or documented)

## Related Issues
Closes #123
```

---

## Testing Strategy

### Test Categories

```
tests/
├── Unit Tests          # Test individual components
│   ├── test_agent.py
│   ├── test_client.py
│   ├── test_server.py
│   └── ...
│
├── Integration Tests   # Test components together
│   └── test_integration.py
│
└── E2E Tests          # Test complete workflows
    └── test_e2e.py
```

### Running Tests

```bash
# All tests
pytest

# Specific file
pytest tests/test_agent.py

# Specific test
pytest tests/test_agent.py::TestAgent::test_agent_creation

# With coverage
pytest --cov=src/synqed --cov-report=html --cov-report=term

# Verbose output
pytest -vv

# Stop on first failure
pytest -x

# Run in parallel (if pytest-xdist installed)
pytest -n auto

# Watch mode (if pytest-watch installed)
ptw
```

### Writing Tests

#### Unit Test Example

```python
# tests/test_agent.py

import pytest
from synqed import Agent

class TestAgent:
    """Unit tests for Agent class."""
    
    def test_agent_creation_with_simple_skills(self):
        """Test creating an agent with simple skill strings."""
        # Arrange & Act
        agent = Agent(
            name="TestAgent",
            description="A test agent",
            skills=["skill1", "skill2"]
        )
        
        # Assert
        assert agent.name == "TestAgent"
        assert agent.description == "A test agent"
        assert len(agent.card.skills) == 2
        assert agent.card.skills[0].skill_id == "skill1"
    
    @pytest.mark.asyncio
    async def test_agent_executor_function(self):
        """Test agent with custom executor function."""
        # Arrange
        async def custom_logic(context):
            return "Test response"
        
        agent = Agent(
            name="TestAgent",
            description="A test agent",
            skills=["test"],
            executor=custom_logic
        )
        
        # Act
        executor = agent.executor
        
        # Assert
        assert executor is not None
        assert callable(executor.execute_task)
```

#### Integration Test Example

```python
# tests/test_integration.py

import pytest
from synqed import Agent, AgentServer, Client

@pytest.mark.asyncio
async def test_agent_client_communication(port_generator):
    """Test full agent-client communication flow."""
    # Arrange
    async def agent_logic(context):
        return f"Echo: {context.get_user_input()}"
    
    agent = Agent(
        name="EchoAgent",
        description="Echoes messages",
        skills=["echo"],
        executor=agent_logic
    )
    
    port = port_generator()
    server = AgentServer(agent, port=port)
    
    # Act
    await server.start_background()
    
    try:
        async with Client(f"http://localhost:{port}") as client:
            response = await client.ask("Hello!")
            
            # Assert
            assert response == "Echo: Hello!"
    
    finally:
        # Cleanup
        await server.stop()
```

#### E2E Test Example

```python
# tests/test_e2e.py

import pytest
from synqed import Agent, AgentServer, Orchestrator, LLMProvider

@pytest.mark.asyncio
@pytest.mark.skipif(not os.getenv("OPENAI_API_KEY"), reason="No API key")
async def test_orchestration_workflow(port_generator):
    """Test complete orchestration workflow with real LLM."""
    # Arrange - Create multiple agents
    agents = []
    servers = []
    
    for name in ["AgentA", "AgentB", "AgentC"]:
        agent = Agent(
            name=name,
            description=f"Handles {name} tasks",
            skills=[f"{name.lower()}_skill"],
            executor=lambda ctx: f"{name} response"
        )
        server = AgentServer(agent, port=port_generator())
        await server.start_background()
        
        agents.append(agent)
        servers.append(server)
    
    # Create orchestrator
    orchestrator = Orchestrator(
        provider=LLMProvider.OPENAI,
        api_key=os.getenv("OPENAI_API_KEY"),
        model="gpt-4o-mini"
    )
    
    # Register agents
    for agent in agents:
        orchestrator.register_agent(agent.card, agent.url)
    
    try:
        # Act
        result = await orchestrator.orchestrate("Test task")
        
        # Assert
        assert len(result.selected_agents) > 0
        assert result.selected_agents[0].confidence > 0.0
        assert result.execution_plan != ""
    
    finally:
        # Cleanup
        for server in servers:
            await server.stop()
```

### Test Fixtures

Common fixtures in `conftest.py`:

```python
@pytest.fixture
def port_generator():
    """Generate unique ports for test servers."""
    port = 8000
    def generate():
        nonlocal port
        port += 1
        return port
    return generate

@pytest.fixture
async def simple_agent():
    """Create a simple test agent."""
    async def logic(context):
        return "Test response"
    
    return Agent(
        name="TestAgent",
        description="A test agent",
        skills=["test"],
        executor=logic
    )

@pytest.fixture
async def running_server(simple_agent, port_generator):
    """Create and start a test server."""
    server = AgentServer(simple_agent, port=port_generator())
    await server.start_background()
    yield server
    await server.stop()
```

### Coverage Requirements

- **Minimum:** 90% overall coverage
- **Unit tests:** 95%+ coverage
- **Integration tests:** Cover all component interactions
- **E2E tests:** Cover main user workflows

Check coverage:

```bash
pytest --cov=src/synqed --cov-report=term-missing
```

---

## Code Standards

### Style Guide

We follow PEP 8 with some modifications:

```python
# Line length: 88 characters (Black default)
# Quotes: Double quotes for strings
# Imports: Organized by stdlib, third-party, local
# Type hints: Required for all public APIs

# Good example
from typing import Any

async def process_task(
    task_id: str,
    context: dict[str, Any],
    timeout: float = 30.0,
) -> str:
    """
    Process a task with given context.
    
    Args:
        task_id: Unique task identifier
        context: Task execution context
        timeout: Maximum execution time in seconds
    
    Returns:
        Task result as string
    
    Raises:
        TimeoutError: If task exceeds timeout
        ValueError: If task_id is invalid
    """
    # Implementation
    ...
```

### Type Hints

**Required for:**
- All public functions and methods
- All function parameters
- All function return types
- Class attributes

**Examples:**

```python
from typing import Any, Callable, Coroutine

# Simple types
def get_name() -> str:
    return "Synqed"

# Complex types
async def create_agent(
    name: str,
    skills: list[str] | list[dict[str, Any]],
    executor: Callable[[RequestContext], Coroutine[Any, Any, str]] | None = None
) -> Agent:
    ...

# Class attributes
class Agent:
    name: str
    description: str
    _executor_func: Callable | None
```

### Docstrings

We use Google-style docstrings:

```python
def register_agent(
    self,
    agent_card: AgentCard,
    agent_url: str,
    agent_id: str | None = None,
) -> None:
    """
    Register an agent with the orchestrator.
    
    This method adds an agent to the orchestrator's registry, making it
    available for task routing decisions.
    
    Args:
        agent_card: The agent's card containing metadata and capabilities
        agent_url: URL where the agent can be reached
        agent_id: Optional custom ID for the agent. If not provided,
                 uses the agent's name from the card.
    
    Raises:
        ValueError: If agent_id is already registered
        TypeError: If agent_card is not a valid AgentCard
    
    Example:
        >>> orchestrator = Orchestrator(...)
        >>> orchestrator.register_agent(
        ...     agent_card=my_agent.card,
        ...     agent_url="http://localhost:8000"
        ... )
    """
    ...
```

### Code Formatting

```bash
# Format code with Ruff
ruff format src/ tests/ examples/

# Check formatting
ruff format --check src/ tests/

# Fix auto-fixable issues
ruff check --fix src/ tests/
```

### Linting

```bash
# Run linter
ruff check src/ tests/

# Check specific rules
ruff check --select E,F,I src/

# Ignore specific rules (add to pyproject.toml)
# [tool.ruff.lint]
# ignore = ["E501"]  # Line too long
```

### Type Checking

```bash
# Run mypy
mypy src/synqed

# Strict mode
mypy --strict src/synqed

# Ignore missing imports
mypy --ignore-missing-imports src/synqed
```

---

## Contributing Guidelines

### Before You Start

1. Check existing issues and PRs
2. Discuss major changes in an issue first
3. Ensure tests pass locally
4. Update documentation

### Making Changes

```bash
# 1. Create feature branch
git checkout -b my-name/my-feature

# 2. Make changes
# ... edit code ...

# 3. Add tests
# ... write tests ...

# 4. Run tests
pytest

# 5. Format code
ruff format src/ tests/

# 6. Check linting
ruff check src/ tests/

# 7. Run type checking
mypy src/synqed

# 8. Update documentation
# ... update docstrings, README, etc. ...

# 9. Commit changes
git add .
git commit -m "feat: add my feature"

# 10. Push and create PR
git push origin my-name/my-feature
```

### Pull Request Checklist

- [ ] Tests added/updated
- [ ] Tests pass locally
- [ ] Code formatted with Ruff
- [ ] No linting errors
- [ ] Type hints added
- [ ] Docstrings updated
- [ ] Coverage maintained (>90%)
- [ ] Documentation updated
- [ ] Examples updated (if applicable)
- [ ] Commit messages follow convention
- [ ] PR description is clear

### Code Review Guidelines

**As Author:**
- Keep PRs focused and small
- Provide clear description and context
- Respond to feedback promptly
- Be open to suggestions

**As Reviewer:**
- Be constructive and specific
- Ask questions if unclear
- Suggest improvements
- Approve when ready

---

## Common Development Tasks

### Adding a New LLM Provider

1. **Update `LLMProvider` enum:**

```python
# src/synqed/orchestrator.py

class LLMProvider(str, Enum):
    OPENAI = "openai"
    ANTHROPIC = "anthropic"
    GOOGLE = "google"
    NEW_PROVIDER = "new_provider"  # Add here
```

2. **Implement provider initialization:**

```python
def _init_llm_client(self) -> Any:
    """Initialize the LLM client based on the provider."""
    # ... existing providers ...
    
    elif self.provider == LLMProvider.NEW_PROVIDER:
        try:
            from new_provider import AsyncClient
            return AsyncClient(api_key=self.api_key)
        except ImportError:
            raise ValueError(
                "NEW_PROVIDER provider requires 'new-provider' package. "
                "Install it with: pip install new-provider"
            )
```

3. **Implement LLM calling logic:**

```python
async def _call_llm(self, prompt: str) -> dict[str, Any]:
    """Call the LLM with the given prompt."""
    # ... existing providers ...
    
    elif self.provider == LLMProvider.NEW_PROVIDER:
        response = await self._llm_client.generate(
            prompt=prompt,
            temperature=self.temperature,
            max_tokens=self.max_tokens,
        )
        return json.loads(response.text)
```

4. **Add tests:**

```python
# tests/test_orchestrator.py

@pytest.mark.asyncio
async def test_new_provider_initialization():
    """Test NEW_PROVIDER provider initialization."""
    orchestrator = Orchestrator(
        provider=LLMProvider.NEW_PROVIDER,
        api_key="test-key",
        model="test-model"
    )
    assert orchestrator._llm_client is not None
```

5. **Update documentation:**
- Add to README.md LLM providers section
- Update examples if needed
- Add to CHANGELOG.md

### Adding New Agent Capabilities

1. **Update capability in agent:**

```python
# src/synqed/agent.py

agent = Agent(
    name="MyAgent",
    description="...",
    skills=["..."],
    executor=logic,
    capabilities={
        "streaming": True,
        "push_notifications": False,
        "new_capability": True,  # Add new capability
    }
)
```

2. **Update AgentCardBuilder:**

```python
# src/synqed/agent_card.py

def set_capabilities(
    self,
    streaming: bool = True,
    push_notifications: bool = False,
    new_capability: bool = False,  # Add parameter
    **kwargs: Any
) -> "AgentCardBuilder":
    """Set agent capabilities."""
    capabilities = {
        "streaming": streaming,
        "push_notifications": push_notifications,
        "new_capability": new_capability,  # Add to dict
        **kwargs
    }
    self._capabilities = capabilities
    return self
```

3. **Add tests and documentation**

### Adding New Client Features

1. **Add method to Client class:**

```python
# src/synqed/client.py

async def new_feature(self, param: str) -> str:
    """
    New client feature description.
    
    Args:
        param: Description of parameter
    
    Returns:
        Result description
    
    Raises:
        ConnectionError: If connection fails
    """
    # Implementation
    ...
```

2. **Add tests:**

```python
# tests/test_client.py

@pytest.mark.asyncio
async def test_client_new_feature(running_server):
    """Test new client feature."""
    async with Client(running_server.url) as client:
        result = await client.new_feature("test")
        assert result == "expected"
```

3. **Update examples and documentation**

### Modifying Orchestration Logic

1. **Update prompt template:**

```python
# src/synqed/orchestrator.py

ORCHESTRATION_PROMPT = """
You are an intelligent task router...

[Update prompt to include new routing logic]
"""
```

2. **Modify orchestration method:**

```python
async def orchestrate(
    self,
    task: str,
    new_param: str | None = None  # Add parameters as needed
) -> OrchestrationResult:
    """Orchestrate task routing."""
    # Update implementation
    ...
```

3. **Add/update tests:**

```python
@pytest.mark.asyncio
async def test_orchestration_with_new_logic():
    """Test orchestration with new parameter."""
    # Test implementation
    ...
```

### Version Bumps

1. **Update version:**

```python
# src/synqed/__init__.py
__version__ = "1.0.0"  # Bump version

# pyproject.toml
[project]
version = "1.0.0"  # Keep in sync
```

2. **Update CHANGELOG.md:**

```markdown
## [1.0.0] - 2025-01-15

### Added
- New feature description

### Fixed
- Bug fix description

### Changed
- Change description
```

3. **Create git tag:**

```bash
git tag v1.0.0
git push origin v1.0.0
```

---

## Build and Publish Scripts

Synqed includes two helper scripts for building and publishing packages. These are located in the `scripts/` directory.

### build_package.sh - Quick Build Script

**Purpose:** Build the Synqed package for local testing or distribution.

**What it does:**
1. Cleans previous builds (`dist/`, `build/`, `*.egg-info`)
2. Builds the package using Python's `build` module
3. Validates the package with `twine check`
4. Shows built files and next steps

**When to use:**
- Before testing local installation
- Before publishing to PyPI
- To verify package builds correctly
- After making changes to `pyproject.toml`

**Usage:**

```bash
# Make sure you're in the Synq directory
cd Synq

# Run the build script
./scripts/build_package.sh
```

**Expected Output:**

```
🧹 Cleaning previous builds...
📦 Building package...
* Creating venv isolated environment...
* Installing packages in isolated environment... (setuptools >= 61.0)
* Getting build dependencies for sdist...
* Building sdist...
* Building wheel from sdist
✅ Checking package...
Checking dist/synqed-5.0.16-py3-none-any.whl: PASSED
Checking dist/synqed-5.0.16.tar.gz: PASSED

✨ Build complete!

Built files:
total 96
-rw-r--r--  1 user  staff    42K Nov 17 10:30 synqed-5.0.16-py3-none-any.whl
-rw-r--r--  1 user  staff    38K Nov 17 10:30 synqed-5.0.16.tar.gz

To publish:
  Test PyPI:  ./scripts/publish.sh --test
  Production: ./scripts/publish.sh --prod
```

**Prerequisites:**

```bash
# Install build tools
pip install build twine
```

**Troubleshooting:**

If build fails, common issues include:
- Missing dependencies in `pyproject.toml`
- Syntax errors in package files
- Invalid version format
- Missing `MANIFEST.in` entries for non-Python files

---

### publish.sh - Publishing Script

**Purpose:** Automated package versioning, building, and publishing to PyPI.

**What it does:**
1. Checks dependencies (`build`, `twine`)
2. **Automatically increments version** (patch version +1)
3. Updates `pyproject.toml` with new version
4. Cleans previous builds
5. Builds the package
6. Validates with `twine check`
7. Uploads to Test PyPI or Production PyPI

**When to use:**
- Publishing a new release to PyPI
- Testing package installation from Test PyPI
- After merging a PR with new features/fixes
- During the release process

**Configuration:**

Create a `.env` file in the Synq directory with your PyPI tokens:

```bash
# .env file (DO NOT COMMIT)
TWINE_USERNAME=__token__
TWINE_PASSWORD=pypi-xxxxx...  # Production PyPI token
TWINE_TEST_PASSWORD=pypi-xxxxx...  # Test PyPI token (optional)
```

**Get PyPI Tokens:**
- Production: https://pypi.org/manage/account/token/
- Test: https://test.pypi.org/manage/account/token/

**Usage:**

```bash
# Test on Test PyPI first (recommended)
./scripts/publish.sh --test

# Publish to Production PyPI
./scripts/publish.sh --prod

# View help
./scripts/publish.sh --help
```

**Expected Output (Test PyPI):**

```
[INFO] Checking dependencies...
[INFO] All dependencies are installed
[INFO] Incrementing version...
[INFO] Current version: 1.0.0
[INFO] Version updated: 1.0.0 → 1.0.1
[INFO] Cleaning previous builds...
[INFO] Clean complete
[INFO] Building package...
[INFO] Build successful
[INFO] Checking package with twine...
[INFO] Package check passed
[INFO] Package version: 1.0.1
[INFO] Uploading to Test PyPI...
Uploading distributions to https://test.pypi.org/legacy/
Uploading synqed-1.0.1-py3-none-any.whl
Uploading synqed-1.0.1.tar.gz

[INFO] Successfully uploaded to Test PyPI
[INFO] View at: https://test.pypi.org/project/synqed/1.0.1/
[INFO] 
[INFO] To test installation:
  pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple synqed
[INFO] Done!
```

**Expected Output (Production PyPI):**

```
[WARNING] You are about to upload to PRODUCTION PyPI
[WARNING] This cannot be undone. Are you sure? (yes/no)
yes
[INFO] Uploading to Production PyPI...
Uploading distributions to https://upload.pypi.org/legacy/
Uploading synqed-1.0.1-py3-none-any.whl
Uploading synqed-1.0.1.tar.gz

[INFO] Successfully uploaded to Production PyPI
[INFO] View at: https://pypi.org/project/synqed/1.0.1/
[INFO] 
[INFO] To install:
  pip install synqed
[INFO] Done!
```

**Important Notes:**

⚠️ **Version Increment:** The script automatically increments the patch version (e.g., 1.0.0 → 1.0.1). If you need a different version bump:
- Manual: Edit `pyproject.toml` before running the script and comment out the `increment_version` call
- For major/minor bumps: Update version manually first

⚠️ **Production Warning:** Publishing to production PyPI is irreversible. Always test on Test PyPI first!

⚠️ **Commit Changes:** After publishing, remember to commit the version bump:

```bash
git add pyproject.toml src/synqed/__init__.py
git commit -m "chore: bump version to 1.0.1"
git push origin main
git tag v1.0.1
git push origin v1.0.1
```

**Testing Installation:**

After publishing to Test PyPI:

```bash
# Create a clean test environment
python -m venv test-env
source test-env/bin/activate

# Install from Test PyPI
pip install --index-url https://test.pypi.org/simple/ \
    --extra-index-url https://pypi.org/simple \
    synqed

# Test the installation
python -c "import synqed; print(synqed.__version__)"
python examples/intro/agent.py  # Run an example

# Clean up
deactivate
rm -rf test-env
```

After publishing to Production PyPI:

```bash
# Create a clean test environment
python -m venv test-env
source test-env/bin/activate

# Install from Production PyPI
pip install synqed

# Test the installation
python -c "import synqed; print(synqed.__version__)"

# Clean up
deactivate
rm -rf test-env
```

**Troubleshooting:**

Common issues:

| Error | Cause | Solution |
|-------|-------|----------|
| `TWINE_PASSWORD not set` | Missing PyPI token | Add token to `.env` file |
| `Version already exists` | Version already published | Increment version manually or use different version |
| `Package check failed` | Invalid package metadata | Check `pyproject.toml` formatting |
| `Upload failed` | Network or authentication issue | Check token validity and internet connection |
| `Module not found` | Missing `build` or `twine` | Run `pip install build twine` |

**Best Practices:**

1. **Always test first:** Use `--test` before `--prod`
2. **Test installation:** Install from Test PyPI and run examples
3. **Update changelog:** Document changes in CHANGELOG.md before publishing
4. **Create release notes:** Add GitHub release with changelog excerpt
5. **Notify team:** Announce new versions in team chat
6. **Monitor issues:** Watch for bug reports after releasing

---

## 🐛 Debugging Guide

### Enable Debug Logging

```python
import logging

# Enable debug logging for Synqed
logging.basicConfig(level=logging.DEBUG)

# Or just for specific modules
logging.getLogger("synqed.orchestrator").setLevel(logging.DEBUG)
logging.getLogger("synqed.client").setLevel(logging.DEBUG)
```

### Common Issues and Solutions

#### 1. Agent Not Starting

**Symptom:** Server doesn't start or crashes immediately

**Debug steps:**

```python
# Add debug logging
import logging
logging.basicConfig(level=logging.DEBUG)

# Check port availability
import socket
sock = socket.socket()
try:
    sock.bind(("0.0.0.0", 8000))
    print("Port 8000 available")
except OSError:
    print("Port 8000 in use")
finally:
    sock.close()

# Verify agent creation
agent = Agent(...)
print(f"Agent created: {agent.name}")
print(f"Agent card: {agent.card}")
```

#### 2. Client Connection Failures

**Symptom:** Client can't connect to agent

**Debug steps:**

```python
# Test agent card endpoint
import httpx
response = httpx.get("http://localhost:8000/agent-card")
print(f"Status: {response.status_code}")
print(f"Card: {response.json()}")

# Enable client debugging
logging.getLogger("synqed.client").setLevel(logging.DEBUG)
logging.getLogger("httpx").setLevel(logging.DEBUG)
```

#### 3. Orchestration Not Working

**Symptom:** Orchestrator makes poor routing decisions

**Debug steps:**

```python
# Print registered agents
print("Registered agents:")
for agent_id, (card, url) in orchestrator._agents.items():
    print(f"  - {agent_id}: {card.name}")
    print(f"    Skills: {[s.name for s in card.skills]}")

# Enable orchestrator debugging
logging.getLogger("synqed.orchestrator").setLevel(logging.DEBUG)

# Check LLM response
result = await orchestrator.orchestrate("test task")
print(f"Selected: {result.selected_agents[0].agent_name}")
print(f"Reasoning: {result.selected_agents[0].reasoning}")
print(f"Confidence: {result.selected_agents[0].confidence}")
```

#### 4. Test Failures

**Symptom:** Tests fail intermittently or unexpectedly

**Debug steps:**

```bash
# Run single test with verbose output
pytest tests/test_agent.py::test_name -vv

# Run with debugging
pytest tests/test_agent.py::test_name -vv --pdb

# Check test isolation
pytest tests/test_agent.py -vv --lf  # Run last failed

# Disable output capture
pytest tests/test_agent.py -s
```

### Using Python Debugger

```python
# Add breakpoint in code
import pdb; pdb.set_trace()  # Or just: breakpoint()

# In pytest
pytest --pdb  # Drop into debugger on failure

# With ipdb (better interface)
import ipdb; ipdb.set_trace()
```

### Profiling Performance

```python
import cProfile
import pstats

# Profile a function
profiler = cProfile.Profile()
profiler.enable()

# Your code here
await orchestrator.orchestrate("test")

profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumtime')
stats.print_stats(10)  # Top 10 functions
```

---

## Release Process

### Pre-release Checklist

- [ ] All tests pass (`pytest`)
- [ ] Coverage >90% (`pytest --cov`)
- [ ] Linting passes (`ruff check`, `ruff format --check`)
- [ ] Type checking passes (`mypy src/synqed`)
- [ ] Documentation updated (README.md, docstrings)
- [ ] CHANGELOG.md updated with release notes
- [ ] Examples tested (run all examples in `examples/`)
- [ ] No TODO/FIXME in code
- [ ] All PRs merged to main

### Release Workflow

Synqed uses automated scripts for building and publishing. Follow this workflow:

#### Step 1: Prepare the Release

```bash
# Ensure you're on main branch with latest changes
git checkout main
git pull origin main

# Run all tests
pytest --cov=src/synqed --cov-report=term

# Run linting
ruff check src/ tests/
ruff format --check src/ tests/

# Test examples manually
cd examples/intro
python agent.py  # Test in one terminal
python client.py  # Test in another terminal
cd ../..
```

#### Step 2: Update CHANGELOG.md

```markdown
## [1.0.0] - 2025-11-17

### Added
- New feature: Orchestrator support for Gemini 2.0
- Added build and publish scripts documentation

### Fixed
- Fixed client timeout handling
- Resolved server shutdown race condition

### Changed
- Improved error messages in TaskDelegator
- Updated dependencies

### Deprecated
- (if any)

### Removed
- (if any)

### Security
- (if any)
```

#### Step 3: Build and Test Locally

```bash
# Build the package
./scripts/build_package.sh

# This will:
# - Clean previous builds
# - Build wheel and tarball
# - Validate with twine check
```

**Expected Output:**

```
🧹 Cleaning previous builds...
📦 Building package...
✅ Checking package...
✨ Build complete!

Built files:
-rw-r--r--  synqed-5.0.16-py3-none-any.whl
-rw-r--r--  synqed-5.0.16.tar.gz
```

#### Step 4: Test on Test PyPI (Recommended)

```bash
# Ensure you have Test PyPI token in .env
# TWINE_TEST_PASSWORD=pypi-xxxxx...

# Publish to Test PyPI (auto-increments version to 1.0.0)
./scripts/publish.sh --test
```

This will:
1. Increment version from 1.0.0 → 1.0.1
2. Update `pyproject.toml` automatically
3. Build the package
4. Upload to Test PyPI

**Test the installation:**

```bash
# Create clean test environment
python -m venv test-env
source test-env/bin/activate

# Install from Test PyPI
pip install --index-url https://test.pypi.org/simple/ \
    --extra-index-url https://pypi.org/simple \
    synqed

# Verify version
python -c "import synqed; print(synqed.__version__)"  # Should print latest version

# Test functionality
cd examples/intro
python agent.py

# Clean up
deactivate
cd ../..
rm -rf test-env
```

#### Step 5: Commit Version Bump

```bash
# The publish script updated pyproject.toml
# Commit these changes
git add pyproject.toml
git commit -m "chore: bump version"
git push origin main
```

#### Step 6: Publish to Production PyPI

```bash
# Ensure you have Production PyPI token in .env
# TWINE_PASSWORD=pypi-xxxxx...

# Publish to Production PyPI
./scripts/publish.sh --prod
```

You'll see a confirmation prompt:

```
[WARNING] You are about to upload to PRODUCTION PyPI
[WARNING] This cannot be undone. Are you sure? (yes/no)
```

Type `yes` to proceed.

#### Step 7: Create Git Tag and GitHub Release

For example:
```bash
# Create and push git tag
git tag v1.0.0
git push origin v1.0.0

# Create GitHub Release
# Go to: https://github.com/<org>/<repo>/releases/new
# - Tag: v1.0.0
# - Title: "Release 1.0.0"
# - Description: Copy from CHANGELOG.md
# - Attach built files from dist/ (optional)
```

#### Step 8: Post-release Verification

```bash
# Test installation from Production PyPI
python -m venv verify-env
source verify-env/bin/activate

pip install synqed
python -c "import synqed; print(synqed.__version__)"

# Run a quick test
cd examples/intro
python orchestrator_quickstart.py  # Quick functional test

# Clean up
deactivate
cd ../..
rm -rf verify-env
```

### Post-release Tasks

- [ ] Verify package on PyPI: https://pypi.org/project/synqed/
- [ ] Update internal wiki/documentation
- [ ] Announce release in team Slack channel
- [ ] Post release notes (if public)
- [ ] Monitor GitHub issues for bug reports
- [ ] Monitor PyPI download stats

### Rollback Procedure

If a critical bug is found after release:

```bash
# You cannot delete a PyPI version, but you can:

# 1. Yank the release (marks as broken, but still installable)
# Visit: https://pypi.org/manage/project/synqed/release/<version>/
# Click "Options" → "Yank release"

# 2. Release a hotfix version immediately
./scripts/publish.sh --prod  # This will create 5.0.18

# 3. Notify users
# - Post notice in release notes
# - Update documentation
# - Send team notification
```

### Release Schedule

**Patch Releases (5.0.x):**
- Bug fixes
- Documentation updates
- Performance improvements
- Release as needed (can be frequent)

**Minor Releases (5.x.0):**
- New features
- New LLM provider support
- Backward-compatible changes
- Every 2-4 weeks

**Major Releases (x.0.0):**
- Breaking changes
- Major architecture changes
- API redesign
- Coordinate with team, announce in advance

### Troubleshooting Releases

| Issue | Solution |
|-------|----------|
| Test PyPI upload fails | Check `TWINE_TEST_PASSWORD` in `.env` |
| Production PyPI upload fails | Check `TWINE_PASSWORD` in `.env` |
| Version already exists | Version was already published; increment manually |
| Package check fails | Review `pyproject.toml` and package structure |
| Tests fail on Test PyPI install | Check dependency versions in `pyproject.toml` |
| Import errors after install | Ensure `__init__.py` exports all public APIs |

---

## Additional Resources

### Internal Documentation

- **Architecture Design Doc:** `docs/architecture.md` (if exists)
- **API Reference:** `docs/api/` (if exists)
- **Meeting Notes:** `docs/meetings/` (if exists)

### External Resources

- **A2A Protocol:** https://github.com/google/a2a
- **A2A SDK Docs:** a2a-sdk documentation
- **Python Async:** https://docs.python.org/3/library/asyncio.html
- **FastAPI:** https://fastapi.tiangolo.com/
- **Pytest:** https://docs.pytest.org/

### Team Communication

- **Slack Channel:** #synqed-dev
- **Weekly Sync:** Wednesdays 2pm
- **Code Review:** GitHub PR comments
- **Questions:** Ask in #synqed-dev or create an issue

---

**Document Version:** 1.0  
**Last Updated:** January 2025  
**Maintainers:** Synq Team

