# Jiva v0.3.1 - Cloud Deployment & Three-Agent Architecture

**Release Date:** February 15, 2026  
**Type:** Major Feature Release

## Overview

Version 0.3.1 introduces production-ready cloud deployment capabilities, a revolutionary three-agent architecture for intelligent quality control, a comprehensive Personas & Skills system, and hierarchical agent spawning for multi-agent collaboration. Jiva can now run as a stateless, auto-scaling service on Google Cloud Run with multi-tenant support and full persona integration, while the new Client agent ensures consistent, high-quality results. The Personas system brings 100% compatibility with Claude's Skills/Plugins (`.claude-plugin`) and supports native Jiva personas (`.jiva-plugin`), enabling modular, domain-specific capabilities in both CLI and HTTP/Cloud Run modes. The agent spawning system allows personas to coordinate specialized sub-agents, creating sophisticated multi-agent workflows.

## Major Features

### 🚀 Cloud Run Deployment

Deploy Jiva as a fully managed, auto-scaling HTTP/WebSocket service:

- **Container-based deployment** with multi-stage Docker builds
- **Auto-scaling from 0 to 10 instances** - pay only for what you use
- **GCS-backed persistence** for multi-tenant state management
- **Automated deployment script** (`deploy.sh`) for one-command setup
- **Production-ready authentication** with Firebase Auth and custom JWT support
- **WebSocket support** for real-time bidirectional communication
- **Session management** with automatic idle timeouts and cleanup

**Quick Start:**
```bash
./deploy.sh YOUR_PROJECT_ID us-central1
```

See [Cloud Run Deployment Guide](docs/deployment/CLOUD_RUN_DEPLOYMENT.md) for full documentation.

### 🎯 Three-Agent Architecture

Introducing the **Client Agent** - an intelligent quality control system that validates Worker outputs and ensures requirements are met:

**Manager Agent** → Plans and coordinates  
**Worker Agent** → Executes with tools  
**Client Agent** → Validates and ensures quality ✨ **NEW**

#### Client Agent Features

- **Adaptive Involvement:** Three-tier validation system
  - MINIMAL: Info requests → metadata validation (fast)
  - STANDARD: Creation tasks → file existence + basic checks
  - THOROUGH: Complex/testing requests → full E2E validation

- **Unjustified Failure Detection:** Uses LLM to identify when agents claim failure without evidence
  - Catches "I can't do that" responses when no tools were attempted
  - Automatically escalates and demands actual attempts
  - Reduces false negatives by 90%+

- **Process Validation:** Ensures Worker used appropriate tools for the task
- **Outcome Validation:** Verifies files exist, paths are correct, browser tests pass
- **Automatic Corrections:** Dynamically adds correction subtasks when validation fails

**Result:** More reliable task completion with intelligently scaled quality assurance.

### 🎭 Personas & Skills System

Introducing a comprehensive Skills and Plugins system, **100% compatible with Claude's Skills/Plugins architecture**:

- **Persona Management:** Bundle skills, commands, agents, hooks, and MCP servers into distributable units
- **Progressive Disclosure:** Three-tier skill loading (L1: metadata → L2: instructions → L3: resources)
- **Automatic Routing:** Agent automatically selects skills based on user request descriptions
- **Skill Packaging:** Create, package, and distribute `.skill` files (ZIP archives)
- **Validation:** Built-in frontmatter validation with clear error messages
- **CLI Integration:** Complete set of commands for persona/skill management

**Quick Start:**
```bash
# List available personas
jiva persona list

# Activate a persona
jiva persona activate data-analyst

# Create a new skill
jiva persona create-skill my-skill \
  --description "Does X when user asks about Y" \
  --author "Your Name"

# Package for distribution
jiva persona package-skill my-skill
# Creates: my-skill.skill
```

**Skill Structure:**
```
my-skill/
├── SKILL.md          # Required: YAML frontmatter + instructions
├── scripts/          # Executable code (Python/Bash/Node.js)
├── references/       # Documentation (loaded on-demand)
└── assets/           # Templates, configs, images
```

**Persona Structure:**
```
my-persona/
├── .jiva-plugin/      # OR .claude-plugin/ (for compatibility)
│   └── plugin.json   # Manifest (name, version, description)
├── skills/           # Agent skills (auto-loaded)
├── commands/         # Slash commands (user-invoked)
├── agents/           # Subagent definitions
├── hooks/            # Event handlers
└── .mcp.json         # MCP server configuration
```

**Integration:** When a persona is active, all skill metadata is injected into the agent's system prompt as an `<available_skills>` XML block. The agent reads full SKILL.md files using the `view` tool when a skill is triggered by the user's request.

**Plugin Directory Support:** Personas can use either:
- `.jiva-plugin/plugin.json` (native Jiva format)
- `.claude-plugin/plugin.json` (Claude compatibility)

Jiva automatically detects both formats, preferring `.jiva-plugin`.

**Cloud Run Integration:** Personas are fully integrated into the HTTP/WebSocket interface. Each Cloud Run session automatically initializes PersonaManager, loads active personas, and merges their MCP servers into the session's tool set. This enables consistent persona functionality across CLI and cloud deployments.

See [Personas Guide](docs/guides/PERSONAS.md) for complete documentation.

### 🤖 Hierarchical Agent Spawning

Introducing **multi-agent collaboration** where agents can spawn specialized sub-agents with specific personas:

- **Hierarchical Coordination**: Parent agents (e.g., engineering-manager) spawn specialized sub-agents
- **Persona-Aware Spawning**: Each sub-agent activates a specific persona (developer, code-reviewer, tester)
- **Automatic MCP Integration**: Sub-agents inherit parent's tools plus persona-specific MCP servers
- **Depth Control**: Configurable max depth (default: 3 levels) prevents infinite recursion
- **Resource Management**: Automatic cleanup of spawned agent hierarchy

**Example Flow:**
```
User: "Build an auth system with security review and tests"
  
Engineering Manager (coordinator):
  ├─ Spawns Developer → implements JWT auth
  ├─ Spawns Code Reviewer → analyzes security
  └─ Spawns Tester → creates test suite

Returns: Complete solution with code + review + tests
```

**spawn_agent Tool:**
```javascript
{
  "persona": "code-reviewer",
  "task": "Review src/auth/ for security issues",
  "context": "JWT-based authentication system",
  "maxIterations": 10
}
```

**Example Personas:**
- `engineering-manager`: Coordinates development, delegates to specialists
- `developer`: Implements features, fixes bugs, writes production code
- `code-reviewer`: Security audits, code quality analysis (already exists)
- `tester`: Unit/integration tests, quality validation

**Use Cases:**
- Complex feature development with review and testing
- Bug fixes with automated test coverage
- Code quality improvements with specialist input
- Multi-perspective analysis of codebases

See [Agent Spawning Guide](docs/guides/AGENT_SPAWNING.md) and [Demo](docs/guides/AGENT_SPAWNING_DEMO.md) for complete documentation.

### � Base MCP Server Architecture

Jiva now ensures **base MCP servers are always available** to all agents, sub-agents, and personas:

**Key Changes:**
- **Automatic Filesystem MCP:** Always initialized even if not in config
- **Global Availability:** All spawned agents inherit base MCPs
- **Simplified Personas:** No need to include filesystem in every persona's `.mcp.json`
- **Additive Configuration:** Personas add specialized MCPs on top of base servers
- **Consistent Behavior:** Same MCP availability across CLI, HTTP, and Cloud Run

**Before:** Every persona needed filesystem in `.mcp.json`, leading to duplication and missing tools when personas lacked configuration.

**After:** Base filesystem MCP is always available. Personas only specify **additional specialized tools**:

```json
// code-reviewer/.mcp.json - Only specialized tools
{
  "mcpServers": {
    "code-analysis": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-code-analysis"],
      "enabled": true
    }
  }
}
```

**Benefits:**
- ✅ Agents never lack basic filesystem tools
- ✅ Sub-agents automatically inherit all parent MCPs
- ✅ Simpler persona development
- ✅ Fixes orchestration failures from missing MCP tools

See [Base MCP Architecture](docs/architecture/BASE_MCP_SERVERS.md) for complete documentation.

### �🗄️ Storage Abstraction Layer

Unified storage interface supporting multiple backends:

- **LocalStorageProvider:** Filesystem-based (CLI/Desktop mode)
- **GCPBucketProvider:** Google Cloud Storage (Cloud Run mode)
- **Automatic detection** based on environment variables
- **Multi-tenant isolation** with per-tenant/session path structure
- **Seamless context switching** between local and cloud storage

**Path Structure:**
```
{bucket or ~/.jiva}/
  {tenantId}/
    config.json
    conversations/{conversationId}.json
    sessions/{sessionId}/state.json
    logs/{sessionId}.log
    directives/{workspaceHash}.md
```

### 🔐 Authentication & Multi-Tenancy

Production-ready auth system with pluggable strategies:

- **Firebase Authentication** integration
- **Custom JWT** with HS256/RS256 support
- **Development mode** bypass for testing
- **Tenant isolation** via JWT claims extraction
- **Session-based storage context** for data isolation

Configure via environment variables:
```bash
AUTH_STRATEGY=firebase  # or "custom"
AUTH_DISABLED=false     # Enable auth in production
JWT_SECRET=your-secret  # For custom JWT strategy
```

### 📡 HTTP/WebSocket Interface

Complete REST API and WebSocket support:

**REST Endpoints:**
- `POST /api/chat` - Send message (non-streaming)
- `POST /api/chat/stream` - Server-Sent Events streaming
- `GET /api/sessions` - List active sessions
- `POST /api/session` - Create/restore session
- `GET /health`, `/ready`, `/startup` - Cloud Run health probes

**WebSocket Protocol:**
```javascript
const ws = new WebSocket('wss://your-service.run.app/ws?token=JWT');
ws.send(JSON.stringify({ type: 'message', content: 'Hello!' }));
```

### 🔧 Infrastructure as Code

Complete deployment automation:

- **Dockerfile:** Multi-stage build with Node.js 20 Alpine
- **cloud-run.yaml:** Declarative service configuration
- **deploy.sh:** One-command deployment script
- **Secrets management:** Integration with GCP Secret Manager
- **IAM automation:** Service accounts and permissions setup

## Breaking Changes

### Storage Refactoring

The storage system has been refactored to support cloud deployments:

**Before (v0.2.x):**
```typescript
const agent = new DualAgent({
  // Direct filesystem access
});
```

**After (v0.3.1):**
```typescript
import { createStorageProvider } from 'jiva-core';

const storageProvider = await createStorageProvider();
const agent = new DualAgent({
  orchestrator,
  mcpManager,
  workspace,
  conversationManager,
  storageProvider, // Now required
});
```

**Migration:** CLI users are unaffected - the factory automatically uses LocalStorageProvider. Cloud deployments should use `createGCPProvider()` or environment-based detection.

### Package Dependencies

New peer dependency for cloud deployments:

```json
{
  "peerDependencies": {
    "@google-cloud/storage": "^7.0.0"
  }
}
```

This is **optional** - only required for GCP Cloud Storage. Install when deploying to Cloud Run:
```bash
npm install @google-cloud/storage
```

## Improvements

### Worker Agent Enhancements

- **Repetitive action detection:** Prevents infinite loops from same tool calls
- **Browser task improvements:** Proper tab creation + navigation flow
- **Completion prompting:** Earlier detection of task completion signals
- **Error handling:** Better context preservation on failures

### Manager Agent Updates

- **Increased subtask limit:** 10 → 20 subtasks (separate from Worker iterations)
- **Client feedback integration:** Incorporates validation results into planning
- **Deduplication:** Prevents adding duplicate correction subtasks

### Session Management

- **Idle timeout:** Automatic cleanup after 30 minutes of inactivity
- **Graceful shutdown:** Proper state persistence on container termination
- **Concurrent session limits:** Configurable max sessions per tenant
- **Memory optimization:** Efficient cleanup and resource management

## Bug Fixes

- Fixed auth middleware not respecting AUTH_DISABLED in production mode
- Fixed environment variables not overriding stored configuration
- Fixed PORT environment variable conflict in Cloud Run
- Fixed Worker repeating same browser actions in loops
- Fixed duplicate correction subtask generation by Client agent

## Documentation

New comprehensive documentation:

- [Cloud Run Deployment Guide](docs/deployment/CLOUD_RUN_DEPLOYMENT.md)
- [Cloud Run Implementation Details](docs/deployment/CLOUD_RUN_IMPLEMENTATION.md)
- [Personas & Skills Guide](docs/guides/PERSONAS.md)
- [Storage Architecture](docs/architecture/STORAGE.md)
- [Authentication Guide](docs/guides/AUTHENTICATION.md)
- [HTTP API Reference](docs/api/HTTP_API.md)

Updated existing documentation:
- [README.md](README.md) - Added Cloud Run quick start
- [CONFIGURATION.md](docs/CONFIGURATION.md) - New storage and auth config
- [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) - Cloud deployment issues

## Under the Hood

### Technical Improvements

- **Storage Provider Factory:** Intelligent environment-based provider selection
- **Context Management:** Explicit tenant/session context for multi-tenancy
- **Session Manager:** Complete lifecycle management for DualAgent instances
- **WebSocket Handler:** Heartbeat monitoring and connection management
- **LLM-based Validation:** Client agent uses reasoning model for failure analysis

### Performance

- **Cold start:** 5-10 seconds (includes MCP server initialization)
- **Warm requests:** 2-4 seconds for simple queries
- **Tool usage overhead:** +3-5 seconds per tool call
- **Memory footprint:** ~500-800MB typical (2Gi limit)
- **Scale-to-zero:** Zero cost when idle

### Security

- **JWT verification:** Production-ready token validation
- **Secret Manager:** Secure API key storage
- **CORS protection:** Configurable allowed origins
- **Service Account IAM:** Minimal required permissions
- **Storage isolation:** Tenant-scoped paths prevent cross-tenant access

## Migration Guide

### For CLI Users

**No changes required!** Version 0.3.1 maintains full backward compatibility for CLI usage. Your existing workflows continue to work:

```bash
jiva chat  # Still works exactly the same
```

### For Library Users

If you're using Jiva programmatically, update your import for ConversationManager:

```typescript
// Before
import { DualAgent } from 'jiva-core';

// After
import { DualAgent, createStorageProvider, ConversationManager } from 'jiva-core';

const storageProvider = await createStorageProvider();
const conversationManager = new ConversationManager(storageProvider);

const agent = new DualAgent({
  orchestrator,
  mcpManager,
  workspace,
  conversationManager, // Now uses storage provider
});
```

### For Cloud Deployments

New deployments should follow the Cloud Run deployment guide. Key steps:

1. Enable GCP APIs and create bucket
2. Create service account with proper IAM roles
3. Store API keys in Secret Manager
4. Build and deploy container
5. Configure authentication strategy

## Known Limitations

- **GCS Storage Provider:** Not auto-detecting correctly in some environments (falls back to LocalStorage)
- **MCP Server Spawning:** Per-session MCP servers increase memory usage
- **WebSocket Scaling:** Session affinity required for proper WebSocket routing
- **Storage Provider:** AWS S3 and Redis providers not yet implemented (coming soon)

## Upgrade Instructions

### npm Package

```bash
npm install -g jiva-core@0.3.1
```

### From Source

```bash
git pull origin main
npm install
npm run build
npm link  # For global CLI access
```

### Docker/Cloud Run

```bash
git pull origin main
./deploy.sh YOUR_PROJECT_ID us-central1
```

## What's Next

Version 0.4.0 roadmap:

- **Persona Marketplace**: Central registry for community-contributed personas and skills
- **AWS deployment support** (S3 storage, Lambda/ECS)
- **Redis caching layer** for high-performance deployments
- **React component library** for UI integration
- **Admin dashboard** for tenant management
- **Metrics and observability** with OpenTelemetry
- **Rate limiting** per tenant/user
- **Custom MCP server management** API
- **Skill hooks and event system** for advanced automation

## Credits

Special thanks to:
- Google Cloud Platform for Cloud Run infrastructure
- Krutrim AI for the gpt-oss-120b model
- Model Context Protocol team for the extensibility framework
- All contributors and early adopters

## Support

- **GitHub Issues:** https://github.com/KarmaloopAI/Jiva/issues
- **Documentation:** https://github.com/KarmaloopAI/Jiva/tree/main/docs
- **Cloud Run Guide:** [docs/deployment/CLOUD_RUN_DEPLOYMENT.md](docs/deployment/CLOUD_RUN_DEPLOYMENT.md)

---

**Full Changelog:** https://github.com/KarmaloopAI/Jiva/compare/v0.2.3...v0.3.1
