# Low-Level Design: Chanakya v2 Multi-Agent Architecture

## 1. Overview
Chanakya v2 is the next-generation decision-intelligence platform for Enterprise Brain. It moves from a monolithic RAG setup to a **Multi-Agent Orchestration** model using the **Agent-to-Agent (A2A)** protocol.

## 2. Architectural Components

### 2.1 Hub Agent (Chanakya)
- **Role**: Central orchestrator and executive interface.
- **Framework**: `pydantic-ai` for reasoning, `pylogue` for streaming UI.
- **Responsibilities**:
    - Intent classification: Determining which sub-agents to query.
    - Context Management: Propagating user identity and session state via `RequestContext`.
    - Synthesis: Aggregating responses from multiple sub-agents into a single executive summary.

### 2.2 Sub-Agents (Gmail & Jira)
- **Role**: Domain-specific data experts.
- **Framework**: Compliant with the A2A JSON-RPC specification.
- **Responsibilities**:
    - Data Extraction: Searching through enterprise-specific silos (Gmail threads, Jira tickets).
    - Tool Calling: Using domain-specific tools (e.g., `search_emails`, `get_ticket_details`).

## 3. Communication Protocol (A2A)
The system uses the standard A2A protocol for inter-agent communication:
1. **Send Message**: Hub sends a JSON-RPC request to the sub-agent's endpoint (`POST /`).
2. **Task Creation**: Sub-agent returns a `task_id` for long-running lookups.
3. **Polling**: Hub polls `get_task` until a terminal state (`completed`, `failed`) is reached.
4. **Metadata Propagation**: User details (email, tenant) are passed in the `metadata` field of the A2A message to ensure RBAC and auditability at the source.

## 4. Context & Dependency Injection
To ensure tools have access to request-level metadata without global state:
- **`RequestContext`**: A typed dataclass containing `user_email`, `tenant`, and `role`.
- **`MetadataAwareWorker`**: A custom worker that extracts A2A metadata and stores it in an `asyncio`-safe `ContextVar`.
- **`EnterpriseAgent`**: A base class that automatically injects these dependencies into `pydantic-ai` tool calls.

## 5. Deployment Model
- **Containerization**: Each agent runs in a dedicated Docker container.
- **Registry**: `backend/chanakya/config.py` acts as the service discovery layer, mapping agent names to internal URLs.

## 6. Package Structure

```
backend/chanakya/
  a2a_context.py        # Shared: RequestContext, MetadataAwareWorker, make_metadata_aware_app
  base.py               # Shared: EnterpriseAgent base class
  config.py             # Shared: AGENT_REGISTRY (service discovery)
  rt_agent/             # Hub routing agent (was chanakya.py)
    __init__.py         #   exports: app, chanakya
    agent.py            #   chanakya agent definition + tools (ask_gmail, ask_jira)
    server.py           #   FastAPI app, chat UI mount, admin UI
    a2a.py              #   A2A polling helpers (ask_agent, _extract_text, etc.)
  gmail/                # Gmail sub-agent
  jira/                 # Jira sub-agent
  user_aware/           # User-aware sub-agent
```

**Entry point**: `backend.chanakya.rt_agent:app` (uvicorn / docker-compose).

## 7. Implementation Status (as of 2026-03-26)
- [x] A2A Hub & Server implementation.
- [x] Gmail & Jira basic agent logic.
- [x] Metadata propagation via `ContextVar`.
- [x] Hub refactored into `rt_agent/` package (`agent.py`, `server.py`, `a2a.py`).
- [x] Dead code removed (`model.py`).
- [ ] Context Propagation Lifecycle ([DEB-322](../../reports/jira/20260315#deb-322-context-propagation-lifecycle)) - **In Progress**.
- [ ] Pydantic Agent standardization ([DEB-327](../../reports/jira/20260315#deb-327-adhoc-question-and-answer-lifecycle---i)) - **In Progress**.
