Metadata-Version: 2.4
Name: qp-conductor
Version: 0.4.0
Summary: Cognitive orchestration engine for autonomous organizations
Author-email: Quantum Pipes <team@quantumpipes.io>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/quantumpipes/conductor
Project-URL: Documentation, https://github.com/quantumpipes/conductor/blob/main/INTEGRATION.md
Project-URL: Repository, https://github.com/quantumpipes/conductor
Project-URL: Changelog, https://github.com/quantumpipes/conductor/blob/main/CHANGELOG.md
Keywords: orchestration,multi-agent,agent-swarm,autonomous-ai,governance,capsule,adaptation,drift-detection,air-gap,enterprise
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml>=6.0
Provides-Extra: cli
Requires-Dist: typer>=0.21; extra == "cli"
Provides-Extra: api
Requires-Dist: fastapi>=0.135; extra == "api"
Requires-Dist: uvicorn>=0.42; extra == "api"
Provides-Extra: vault
Requires-Dist: qp-vault>=1.2.0; extra == "vault"
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Provides-Extra: sqlite
Requires-Dist: aiosqlite>=0.22; extra == "sqlite"
Provides-Extra: scheduler
Requires-Dist: sqlalchemy>=2.0; extra == "scheduler"
Requires-Dist: aiosqlite>=0.22; extra == "scheduler"
Provides-Extra: postgres
Requires-Dist: sqlalchemy>=2.0; extra == "postgres"
Requires-Dist: asyncpg>=0.31; extra == "postgres"
Provides-Extra: all
Requires-Dist: qp-conductor[api,cli,vault]; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=9.0; extra == "dev"
Requires-Dist: pytest-asyncio>=1.3; extra == "dev"
Requires-Dist: pytest-cov>=7.0; extra == "dev"
Requires-Dist: httpx>=0.28; extra == "dev"
Requires-Dist: ruff>=0.15; extra == "dev"
Requires-Dist: mypy>=1.19; extra == "dev"
Requires-Dist: types-PyYAML>=6.0; extra == "dev"
Dynamic: license-file

<div align="center">

# QP Conductor

**Unleash the swarm. Keep the leash.**

Conductor decomposes natural language goals into capability-ordered plans, dispatches a swarm of specialized agents across 9 domains, and keeps humans in control at every critical junction. Every orchestration decision is cryptographically sealed via the [Capsule Protocol](https://github.com/quantumpipes/capsule). The adaptation engine learns from every execution. The safety gates never sleep.

[![Python](https://img.shields.io/badge/Python-3.11+-3776AB.svg)](https://www.python.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![PyPI](https://img.shields.io/pypi/v/qp-conductor)](https://pypi.org/project/qp-conductor/)
[![Tests](https://img.shields.io/badge/Tests-615_passing-brightgreen.svg)](tests/)
[![Capabilities](https://img.shields.io/badge/Capabilities-42_across_9_domains-orange.svg)](src/qp_conductor/capabilities/)
[![Security](https://img.shields.io/badge/Security-100%2F100-brightgreen.svg)](SECURITY.md)
[![Coverage](https://img.shields.io/badge/Coverage-90%25+-brightgreen.svg)](tests/)

</div>

---

## The Architecture

Conductor takes a natural language goal, analyzes it against 42 registered capabilities, composes a dependency-ordered execution plan, calculates the appropriate autonomy level, and orchestrates a swarm of agents with human checkpoints at every critical junction.

```
┌─────────────────────────────────────────────────────────────────┐
│                        CONDUCTOR                                │
├──────────────┬──────────────────────────────────────────────────┤
│  ANALYZE     │  Natural language -> intent + capability reqs     │
│  COMPOSE     │  Requirements -> topological execution plan       │
│  AUTONOMY    │  Risk + confidence -> oversight level (L0-L4)     │
│  ORCHESTRATE │  Dispatch agents, parallel execution, Capsule     │
│  CHECKPOINT  │  Human approval gates, async wait pattern         │
│  ADAPT       │  Signal capture -> pattern mining -> adapters     │
│  DRIFT       │  Behavioral consistency via cosine distance       │
│  REMEMBER    │  Organizational memory from past executions       │
├──────────────┴──────────────────────────────────────────────────┤
│  Protocol-based: LLM · Agent · Capsule · Vault · KillSwitch     │
│  Safety: HIGH-risk never auto-approved · Kill switch every       │
│  iteration · Security agents never adapted · Injection blocked   │
└─────────────────────────────────────────────────────────────────┘
```

---

## Why Conductor

Task runners dispatch work. When something goes wrong, or when a compliance officer asks "why did the AI make that decision and who approved it?", a task runner has no answer.

Conductor solves three problems that task runners do not:

**1. Capability-aware decomposition.**
Goals are analyzed against 42 registered capabilities across 9 domains. The composer produces a dependency-ordered plan where each step maps to a specific agent with known tools, risk level, and estimated duration. This is not prompt chaining. It is structured planning with topological ordering.

**2. Risk-proportionate human oversight.**
Every task receives an autonomy level (L0 blocked through L4 fully autonomous) calculated from capability risk, tool danger, and YAML-configurable rules. HIGH-risk tasks always require human review. This is enforced at the safety gate level, not configurable away.

**3. Self-improvement with safety constraints.**
The adaptation engine captures signals (tool results, user feedback, timing data), mines patterns, validates proposed changes against safety gates, and creates adapters. Security agents are forbidden from adaptation. Injection patterns are always blocked. Behavioral drift is monitored via cosine distance on embedding fingerprints.

---

## Install

```bash
pip install qp-conductor
```

| Command | What You Get | Dependencies |
|---|---|---|
| `pip install qp-conductor` | Core orchestration, 42 capabilities, state machines, adaptation, drift | **1** (pyyaml) |
| `pip install qp-conductor[vault]` | + Organizational memory with semantic search | + qp-vault |
| `pip install qp-conductor[redis]` | + Production signal queue for adaptation engine | + redis |
| `pip install qp-conductor[cli]` | + `conductor` command-line tool | + typer |
| `pip install qp-conductor[api]` | + FastAPI REST endpoints | + fastapi, uvicorn |
| `pip install qp-conductor[scheduler]` | + Persistent scheduler (SQLite) | + sqlalchemy, aiosqlite |
| `pip install qp-conductor[postgres]` | + Persistent scheduler (PostgreSQL) | + sqlalchemy, asyncpg |
| `pip install qp-conductor[all]` | Everything | All of the above |

Combine extras:

```bash
pip install qp-conductor[vault,redis,api]       # Production API server
pip install qp-conductor[cli,scheduler]          # Development with persistence
```

---

## Quick Start

```python
from qp_conductor import (
    Goal, GoalService, TaskService, InMemoryStorage,
    CapabilityRegistry, CapabilityComposer, AutonomyCalculator,
)

# Initialize
storage = InMemoryStorage()
goal_service = GoalService(storage=storage)

# Natural language to structured goal
goal = await goal_service.create(
    user_id=user_id,
    description="Research financial regulations and write a summary",
)

# Compose a capability-ordered execution plan
registry = CapabilityRegistry()  # Loads 42 YAML capabilities
composer = CapabilityComposer(capability_registry=registry)

# Approve tasks from the priority inbox
task_service = TaskService(storage=storage)
tasks, count = await task_service.get_pending_review_tasks(user_id)
await task_service.batch_approve([t.id for t in tasks], user_id)
```

---

## 7 Subsystems

| Subsystem | What It Does |
|-----------|-------------|
| **Goal Analyzer** | Natural language to capability requirements. Intent classification (GOAL/SPECIFICATION/HYBRID/AMBIGUOUS). |
| **Capability Composer** | Requirements to dependency-ordered execution plan. Topological sort. |
| **Autonomy Calculator** | YAML-configured oversight levels (L0 blocked through L4 fully autonomous). |
| **Orchestrator** | Multi-agent dispatch with parallel execution and Capsule sealing. |
| **Checkpoint Manager** | Human approval gates with async wait pattern. |
| **Adaptation Engine** | Self-improvement: signal capture, pattern mining, safety validation, adapter creation. |
| **Drift Detector** | Behavioral consistency monitoring via cosine distance on embedding fingerprints. |

Plus: **Organizational Memory** (learns from past goals), **Persistent Scheduler** (cron-based recurring workflows), **Priority Inbox** (risk-sorted task approval), **Auto-Approval Rules** (pattern-based with safety constraints).

---

## 42 Capabilities Across 9 Domains

| Domain | Count | Capabilities |
|--------|-------|-------------|
| **Analysis** | 10 | Financial, market, risk, pattern detection, comparative, legal, accounting, HR, data, criteria evaluation |
| **Planning** | 4 | Strategic, project, resource, task decomposition |
| **Creation** | 5 | Code generation, test generation, content, documentation, formal documents |
| **Investigation** | 5 | Research, debugging, root cause, vision, performance analysis |
| **Validation** | 3 | Code review, compliance check, evidence collection |
| **Communication** | 2 | Stakeholder, progress reporting |
| **Execution** | 2 | Deployment, shell execution |
| **Audio** | 4 | Transcription, understanding, synthesis, diarization |
| **Sysadmin** | 5 | Health check, diagnosis, remediation, validation, learning |

Add new capabilities by dropping a YAML file in the registry directory:

```yaml
# capabilities/registry/my_capability.yaml
name: my_capability
domain: analysis
description: What this capability does
risk_level: medium
required_tools:
  - tool_name
dependencies: []
estimated_duration_minutes: 10
```

No code changes required. The registry auto-discovers YAML files.

---

## Autonomy Levels

The swarm's leash length is calculated per-task, not set globally.

| Level | Name | What Happens |
|-------|------|-------------|
| **L0** | BLOCKED | Cannot proceed without human action |
| **L1** | SUPERVISED | Human reviews every step |
| **L2** | CHECKPOINT_MAJOR | Human reviews high-risk steps only |
| **L3** | CHECKPOINT_END | Human reviews final output (default) |
| **L4** | FULL | Fully autonomous |

Configure via YAML rules:
```yaml
increase_rules:
  - id: low_risk_research
    condition: { all_capabilities_risk_level: "low" }
    adjustment: +1
decrease_rules:
  - id: destructive_tools
    condition: { any_tool_in: [shell_execute, file_delete] }
    adjustment: -1
```

---

## Safety Constraints (Non-Negotiable)

These are hardcoded into the safety gate layer. You cannot accidentally disable them.

1. **HIGH-risk tasks never auto-approved**: Deploy, delete, decision tasks always require human review
2. **Security agents never adapted**: Auditor and deployer agents cannot receive prompt modifications
3. **Injection patterns always blocked**: Shell injection, SQL injection, path traversal, secret leakage
4. **Kill switch always checked**: Every agent iteration checks the kill switch

---

## Protocol-Based Integration

Conductor uses structural subtyping for all external dependencies. No direct imports from other packages.

```python
from quantumpipes import Agent, KillSwitch
from quantumpipes.intelligence import CapabilityRouter
from qp_capsule import CapsuleChain, Seal
from qp_vault import AsyncVault

from qp_conductor import GoalAnalyzer, CapabilityRegistry

analyzer = GoalAnalyzer(
    capability_registry=CapabilityRegistry(),
    llm_service=router,  # Any object matching LLMProtocol
)
```

| Protocol | Satisfied By |
|----------|-------------|
| `LLMProtocol` | `quantumpipes.intelligence.CapabilityRouter` |
| `AgentProtocol` | `quantumpipes.Agent` |
| `CapsuleChainProtocol` | `qp_capsule.CapsuleChain` |
| `SealProtocol` | `qp_capsule.Seal` |
| `KillSwitchProtocol` | `quantumpipes.KillSwitch` |
| `VaultProtocol` | `qp_vault.AsyncVault` |

See [INTEGRATION.md](./INTEGRATION.md) for the complete integration guide.

---

## API Reference

### Goal Service

```python
goal = await service.create(user_id, "Prepare Q4 tax filings")
goal = await service.provide_clarification(goal.id, user_id, answers=["Federal only"])
goal = await service.update_progress(goal.id)
goal, stats = await service.cancel(goal.id, user_id)
```

### Task Service (Priority Inbox)

```python
tasks, count = await service.get_pending_review_tasks(user_id, sort="priority")
await service.approve(task_id, user_id)
await service.decline(task_id, user_id, reason="Not needed")
await service.batch_approve([id1, id2, id3], user_id)
```

### Auto-Approval Rules

```python
rule = await service.create_rule(
    user_id=user_id,
    name="Auto-approve low-risk research",
    criteria=RuleCriteria(
        task_types=["research", "search"],
        min_confidence=0.8,
        max_risk=RiskLevel.LOW,  # HIGH is forbidden
    ),
)
```

### Adaptation Engine

```python
signals.capture_tool_result("web_search", success=True, duration_ms=250)
signals.capture_user_feedback("output-1", feedback_type="rating", rating=4)
proposals = await engine.run_cycle(tenant_id=tenant_id)
```

### Drift Detection

```python
detector = BehavioralDriftDetector()
detector.add_baseline("agent_selection", [1.0, 0.0, 0.0])
result = detector.check("agent_selection", new_embedding)
# result.severity: NONE | LOW | MEDIUM | HIGH
```

### Scheduler

```python
schedule = await scheduler.register(
    name="daily_cycle",
    cron="0 2 * * *",
    timezone="America/Chicago",
    goal_template="daily_content",
)
```

### Organizational Memory

```python
memory = OrganizationalMemory(vault=vault)
await memory.record_goal(
    tenant_id=tenant_id,
    goal_type="research",
    goal_summary="Researched tax regulations",
    success=True,
    lessons=["Government websites had the most current data"],
)
insights = await memory.get_insights("financial research", tenant_id)
```

---

## Package Structure

```
src/qp_conductor/
  models/           Goal, Task, Workflow, Capability, AutoApprove dataclasses
  state_machines/   GoalStateMachine (25 transitions), TaskStateMachine (14 transitions)
  core/             GoalAnalyzer, CapabilityComposer, AutonomyCalculator, CheckpointManager
  capabilities/     CapabilityRegistry + 42 YAML definitions across 9 domains
  goals/            GoalService, TaskService, AutoApproveService
  storage/          StorageProtocol + InMemoryStorage
  adaptation/       AdaptationEngine, SignalCapture, SafetyGates, AdapterStore
  drift/            BehavioralDriftDetector (cosine distance)
  memory/           OrganizationalMemory (in-memory + optional Vault)
  scheduler/        Cron scheduler (in-memory, persistent backends planned)
  genome/           Hub Genome parser (YAML -> autonomous business config)
  cli/              Typer CLI (requires: pip install qp-conductor[cli])
  integrations/     FastAPI mount (requires: pip install qp-conductor[api])
  protocols.py      Protocol interfaces for Core, Capsule, Vault integration
```

---

## Testing

```bash
make test                                   # Full suite with coverage
pytest tests/ -m safety -v                  # Safety-critical tests only
pytest tests/ --cov=qp_conductor            # Coverage report (90% threshold)
```

---

## Part of the Quantum Pipes Stack

| Package | Purpose | Install |
|---|---|---|
| **[qp-capsule](https://github.com/quantumpipes/capsule)** | Cryptographic audit protocol | `pip install qp-capsule` |
| **[qp-vault](https://github.com/quantumpipes/vault)** | Governed knowledge store | `pip install qp-vault` |
| **qp-conductor** | Orchestration engine | `pip install qp-conductor` |
| **qp-conduit** | Infrastructure management | Shell toolkit |
| **qp-tunnel** | Encrypted remote access | Shell toolkit |

Each independently useful. Together, the governed AI platform for autonomous organizations.

---

## Documentation

| Document | Audience |
|---|---|
| [Getting Started](./docs/getting-started.md) | Developers |
| [Architecture](./docs/architecture.md) | Developers, Architects |
| [API Reference](./docs/api-reference.md) | Developers |
| [Persistence](./docs/persistence.md) | DevOps, Developers |
| [Integration Guide](./INTEGRATION.md) | Developers, Architects |
| [Changelog](./CHANGELOG.md) | Developers |
| [Contributing](./CONTRIBUTING.md) | Contributors |
| [Security Policy](./SECURITY.md) | Security Teams |

---

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md). Bug fixes with tests, new capabilities (YAML definitions), and documentation improvements are welcome.

## License

[Apache License 2.0](./LICENSE).

---

<div align="center">

*Unleash the swarm. Keep the leash.*

An open-source orchestration engine for autonomous organizations

[Integration Guide](./INTEGRATION.md) · [Security Policy](./SECURITY.md) · [Changelog](./CHANGELOG.md)

Copyright 2026 [Quantum Pipes Technologies, LLC](https://quantumpipes.com)

</div>
