# Luzia CLI - Unified Orchestration for AI Agent Tasks

Luzia is a unified command-line interface for dispatching and managing AI agent tasks across multiple projects. It provides pattern-based routing, Docker container isolation, background job management, knowledge graph integration, and research capabilities.

## Table of Contents

- [Quick Start](#quick-start)
- [Architecture](#architecture)
- [Command Reference](#command-reference)
  - [Project Task Dispatch](#project-task-dispatch)
  - [Project Management](#project-management)
  - [Job Management](#job-management)
  - [Failure Management](#failure-management)
  - [Maintenance](#maintenance)
  - [Research](#research)
  - [Deep Reasoning](#deep-reasoning)
  - [Documentation & QA](#documentation--qa)
  - [Internal Commands](#internal-commands)
- [Configuration](#configuration)
- [Permissions](#permissions)
- [Exit Codes](#exit-codes)
- [Examples](#examples)

---

## Quick Start

```bash
# List available projects
luzia list

# Dispatch a task to a project
luzia musica "fix the audio playback bug"

# Check job status
luzia jobs

# View project history
luzia history musica
```

---

## Architecture

### Core Components

```
┌─────────────────────────────────────────────────────────────────┐
│                      LUZIA CLI                                   │
│  Pattern-based routing dispatcher                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │   Projects   │  │   Docker     │  │  Knowledge   │          │
│  │   Config     │  │   Bridge     │  │    Graph     │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
│         │                  │                  │                  │
│         v                  v                  v                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │ config.json  │  │  Containers  │  │   SQLite     │          │
│  │              │  │  (per-proj)  │  │   Databases  │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

### Key Directories

| Path | Description |
|------|-------------|
| `/opt/server-agents/orchestrator/` | Luzia installation |
| `/opt/server-agents/orchestrator/bin/luzia` | Main CLI script |
| `/opt/server-agents/orchestrator/lib/` | Library modules |
| `/opt/server-agents/orchestrator/config.json` | Project configuration |
| `/var/log/luz-orchestrator/` | Log directory |
| `/var/log/luz-orchestrator/jobs/` | Background job storage |
| `/etc/zen-swarm/memory/` | Knowledge graph databases |

### Execution Model

1. **Natural Language Tasks**: Spawn autonomous Claude agents with full permissions
2. **Shell Commands**: Execute directly in project Docker containers
3. **Background Jobs**: Track with job IDs, monitor completion via notifications

---

## Command Reference

### Project Task Dispatch

The primary way to interact with projects:

```bash
luzia <project> <task>
```

#### Behavior

- **Natural language tasks** (e.g., "fix the login bug") spawn a Claude agent
- **Shell commands** (e.g., `npm install`) execute directly in Docker container
- Returns immediately with job ID: `agent:<project>:<job_id>`

#### Shell Command Detection

These prefixes trigger direct execution:
`npm`, `node`, `python`, `pip`, `git`, `ls`, `cat`, `grep`, `find`, `make`, `cargo`, `go`, `yarn`, `pnpm`, `docker`, `cd`, `pwd`, `echo`, `touch`, `mkdir`, `rm`, `cp`, `mv`, `curl`, `wget`, `which`, `env`, `export`, `source`, `bash`, `./`, `sh`, `test`

#### Examples

```bash
# Natural language task (spawns Claude agent)
luzia musica "add dark mode to the settings page"

# Shell command (direct execution)
luzia overbits npm run build

# Show project info only
luzia dss
```

#### Options

| Flag | Description |
|------|-------------|
| `--verbose` | Show detailed output |
| `--fg` | Run in foreground (shell commands only) |

---

### Project Management

#### `luzia list`

List all registered projects with status.

```bash
luzia list
luzia list --verbose  # Include focus areas
```

Output shows:
- `[RUN]` - Container is running
- `[---]` - Container stopped

#### `luzia status [project] [--conductor]`

Show system status including active tasks and containers.

```bash
luzia status           # All projects
luzia status musica    # Specific project
luzia status --conductor  # Conductor tasks only
```

#### `luzia stop <project>`

Stop a project's Docker container.

```bash
luzia stop musica
```

#### `luzia history <project> [limit]`

View recent changes from the project's knowledge graph.

```bash
luzia history musica
luzia history overbits 20
```

---

### Job Management

#### `luzia jobs [job_id]`

List or inspect background jobs.

```bash
# List recent jobs (last 20)
luzia jobs

# Show specific job details
luzia jobs 143521-ab12
```

Output indicators:
- `[✓]` - Completed
- `[…]` - Running
- `🤖` - Agent task
- `📦` - Docker command

#### `luzia logs <project|job_id>`

View logs for a project or specific job.

```bash
luzia logs musica         # Latest project log
luzia logs 143521-ab12    # Specific job output
```

#### `luzia kill <job_id>`

Terminate a running agent.

```bash
luzia kill 143521-ab12
```

#### `luzia notify [limit]`

View agent completion notifications.

```bash
luzia notify       # Last 10
luzia notify 20    # Last 20
```

---

### Failure Management

Smart retry system with exit code classification.

#### `luzia failures [options]`

List and manage failed jobs.

```bash
# List recent failures
luzia failures

# Show specific failure details
luzia failures 143521-ab12

# Summary by exit code
luzia failures --summary

# Auto-retry all fixable failures
luzia failures --auto-retry
```

#### `luzia retry <job_id>`

Retry a specific failed job.

```bash
luzia retry 143521-ab12
```

#### Exit Code Classification

| Code | Meaning | Retryable |
|------|---------|-----------|
| 0 | Success | No |
| 1 | General error | Yes |
| 2 | Shell misuse | No |
| 126 | Permission denied | No |
| 127 | Command not found | No |
| 130 | SIGINT (Ctrl+C) | Yes |
| 137 | SIGKILL (OOM) | Yes |
| 143 | SIGTERM | Yes |
| 254 | Claude CLI error | Yes |
| -9 | Killed by user | No |

---

### Maintenance

#### `luzia cleanup [subcommand] [--dry-run]`

Clean up old jobs, containers, and logs.

```bash
# Full maintenance
luzia cleanup

# Preview only
luzia cleanup --dry-run

# Specific cleanups
luzia cleanup jobs         # Old job directories
luzia cleanup containers   # Stale containers
luzia cleanup conductor    # Stale conductor tasks
luzia cleanup all          # Everything
```

#### `luzia maintenance`

Show maintenance status and recommendations.

```bash
luzia maintenance
```

Displays:
- Job statistics (total, running, completed, failed)
- Container count and age
- Disk usage
- Retention policy settings
- Recommendations for cleanup

#### Retention Policy

| Setting | Value |
|---------|-------|
| `JOB_MAX_COUNT` | 50 (always keep last N) |
| `JOB_MAX_AGE_DAYS` | 3 days (completed jobs) |
| `JOB_FAILED_MAX_AGE_DAYS` | 7 days (failed jobs) |
| `CONTAINER_MAX_LIFETIME_HOURS` | 24 hours |
| `NOTIFICATION_LOG_MAX_LINES` | 1000 lines |

---

### Research

Three-phase research flow with knowledge graph integration.

#### `luzia research [project] <topic>`

Start a research session.

```bash
luzia research admin "multi-agent orchestration patterns"
luzia deep research musica "audio synthesis libraries"
luzia web research overbits "react performance optimization"
```

#### Research Phases

1. **Context Expansion** - Expand topic into search branches
2. **Branching Web Search** - Execute parallel searches
3. **Final Synthesis** - Consolidate findings into knowledge graph

#### `luzia research-list [project]`

List research sessions.

```bash
luzia research-list admin
```

#### `luzia research-show <session_id>`

Show research session details.

```bash
luzia research-show abc12345
```

#### `luzia research-knowledge [project]`

Show project knowledge graph.

```bash
luzia research-knowledge admin
```

#### Internal Research Commands

Used during research flow:

```bash
luzia research-update <session_id> <phase> <json_data>
luzia research-graph <session_id> <entities_json>
```

---

### Deep Reasoning

#### `luzia think deep <topic>`

Enhanced deep logic framework using Zen MCP with Gemini 3.

```bash
luzia think deep "how to optimize database queries"
luzia think deep --code "implement caching layer"
luzia think deep --bug "race condition in auth"
luzia think deep --arch "microservices vs monolith"
luzia think deep --qa "test coverage strategy"
```

#### Modes

| Mode | Lens Emphasis |
|------|---------------|
| `--code` | Technical, Scale, Integration |
| `--bug` | Technical, Failure, Temporal |
| `--arch` | Technical, Scale, Integration, Temporal |
| `--qa` | User, Failure, Scale, Integration |

#### Analysis Stages

1. **Decomposition** (First Principles) - Break down to fundamental truths
2. **Multi-Lens Analysis** (Refraction) - Examine through 7 lenses
3. **Synthesis** - Combine insights, generate solutions
4. **Validation** - Checklist verification

---

### Documentation & QA

#### `luzia docs [domain] <query>`

Search knowledge graphs.

```bash
luzia docs "nginx configuration"
luzia docs sysadmin "backup"
luzia docs projects "api endpoints"
luzia docs --show entity_name
luzia docs --stats
luzia docs --sync   # Sync .md files to KG
```

#### Domains

- `sysadmin` - Server admin docs, commands, procedures
- `users` - User management, permissions, workflows
- `projects` - Project-specific docs, features, APIs
- `research` - Research sessions, findings

#### `luzia qa [options]`

Run QA validation for Luzia itself.

```bash
luzia qa              # Run all validations
luzia qa --test-all   # Verbose output
luzia qa --update-docs  # Update reference docs
luzia qa --sync       # Sync to knowledge graph
```

Validates:
- Python syntax
- Route handlers
- Docstring accuracy
- Config validity
- Required directories

#### `luzia fix <issue>`

Troubleshooting helper.

```bash
luzia fix "configuration corrupted"
luzia fix "build failed"
luzia fix "container connection refused"
```

---

### Queue Commands

Load-aware task queue with priority scheduling.

#### `luzia queue [project] [--clear]`

Show queue status.

```bash
luzia queue
luzia queue --clear   # Clear pending tasks
```

#### `luzia dispatch <project> <task> [options]`

Queue a task with priority.

```bash
luzia dispatch musica "fix bug" --priority 3
luzia dispatch overbits "deploy" --now  # Immediate execution
```

Priority:
- 1-3: High priority tier
- 4-10: Normal priority tier

---

### Interactive Work

#### `luzia work on <project> [task]`

Interactive work session or task dispatch.

```bash
luzia work on musica
luzia work on overbits "refactor auth module"
```

For the Luzia project itself (dogfooding), spawns an interactive Claude session.

---

### Internal Commands

Used by subagents for container operations. Output is JSON.

```bash
# Execute command in container
luzia --exec <project> <command>

# Write file in container
luzia --write <project> <path> <content>
luzia --write <project> <path> -   # Read content from stdin

# Read file from container
luzia --read <project> <path>

# Get project context
luzia --context <project>
```

---

## Configuration

### config.json Structure

```json
{
  "orchestrator": {
    "name": "sarlo-orchestrator",
    "model": "sonnet",
    "max_concurrent_subagents": 10
  },
  "projects": {
    "project_name": {
      "path": "/home/project_name",
      "description": "Project description",
      "subagent_model": "haiku",
      "tools": ["Read", "Edit", "Bash", "Glob", "Grep"],
      "focus": "Project focus area",
      "color": "#FFFFFF",
      "extra_mounts": ["/opt/path:/opt/path"],
      "user": "custom_user"
    }
  },
  "shared_tools": {
    "zen": "Deep reasoning via PAL MCP",
    "sarlo-admin": "Server administration"
  },
  "routes": {
    "management": ["list", "status", "stop"],
    "project_execution": ["<project> <task>"],
    "special_operations": ["work on <project>", "think deep <topic>"]
  }
}
```

### Project Configuration Fields

| Field | Required | Description |
|-------|----------|-------------|
| `path` | Yes | Project home directory |
| `description` | No | Human-readable description |
| `subagent_model` | No | Model for subagents (default: haiku) |
| `tools` | No | Allowed Claude tools |
| `focus` | No | Project focus area |
| `color` | No | Hex color for terminal output |
| `extra_mounts` | No | Additional Docker volume mounts |
| `user` | No | Override run-as user |

---

## Permissions

### Triple-Check Permission System

1. **Admin/Root**: Full access to all projects
2. **Operators Group**: Access to all projects
3. **Project Owner**: Access to own project
4. **Project Group Member**: Access to project

### Guest Restrictions

Guest users are limited to read-only commands:

**Allowed**: `list`, `status`, `jobs`, `logs`, `queue`, `docs`, `help`, `health`

**Blocked**: `kill`, `cleanup`, `maintenance`, `retry`, `work`, `research`, `think`, `qa`, `dispatch`

---

## Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error / Unknown command |
| 126 | Permission denied |

---

## Examples

### Daily Workflow

```bash
# Start of day - check status
luzia status
luzia jobs

# Work on a project
luzia musica "implement the new playlist feature"

# Monitor progress
luzia jobs
luzia logs 143521-ab12

# Check for failures and retry
luzia failures
luzia retry 143521-ab12

# End of day - cleanup
luzia cleanup --dry-run
luzia cleanup
```

### Research Session

```bash
# Start research
luzia research admin "kubernetes autoscaling strategies"

# Check research status
luzia research-list admin

# View findings
luzia research-show abc12345
luzia research-knowledge admin
```

### Deep Analysis

```bash
# Architecture decision
luzia think deep --arch "event sourcing vs CRUD for order system"

# Debug complex bug
luzia think deep --bug "intermittent timeout in payment processing"
```

### Queue Management

```bash
# Queue multiple tasks
luzia dispatch musica "update dependencies" --priority 5
luzia dispatch musica "run tests" --priority 3
luzia dispatch overbits "deploy staging" --priority 1

# Check queue
luzia queue

# Execute immediately (bypass queue)
luzia dispatch admin "check disk space" --now
```

---

## Troubleshooting

### Container Issues

```bash
# Check container status
docker ps | grep luzia

# Restart container
luzia stop musica
luzia musica "test"

# Manual cleanup
luzia cleanup containers
```

### Job Stuck

```bash
# Check job status
luzia jobs <job_id>

# View output
luzia logs <job_id>

# Kill if needed
luzia kill <job_id>
```

### Permission Errors

```bash
# Check permissions
id
groups

# Verify project access
luzia --verbose <project> <task>
```

---

## Version

- **Script**: `/opt/server-agents/orchestrator/bin/luzia`
- **Version**: 1.0.0
- **Last Updated**: 2026-01-08
- **Python**: 3.10+

---

## Related Documentation

- `/opt/server-agents/docs/UNIFIED-ORCHESTRATION-ARCHITECTURE.md`
- `/opt/server-agents/docs/AI-AGENT-LUZIA-GUIDE.md`
- `/opt/server-agents/CLAUDE.md`
