Metadata-Version: 2.5
Name: quorum-engine
Version: 0.4.0
Summary: A structured multi-agent deliberation engine for high-stakes decisions
Project-URL: Homepage, https://github.com/bryansparks/quorum
Project-URL: Repository, https://github.com/bryansparks/quorum
Project-URL: Bug Tracker, https://github.com/bryansparks/quorum/issues
Project-URL: Changelog, https://github.com/bryansparks/quorum/blob/main/CHANGELOG.md
Author-email: Bryan Sparks <bryan@drycanyon.com>
License: MIT License
        
        Copyright (c) 2026 Bryan Sparks
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: agents,ai,crewai,decision-making,deliberation,llm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Requires-Dist: crewai<0.80,>=0.70.0
Requires-Dist: langchain-anthropic<2,>=0.3.0
Requires-Dist: langchain-openai<2,>=0.3.0
Requires-Dist: pydantic<3,>=2.0.0
Requires-Dist: python-dotenv<2,>=1.0.0
Requires-Dist: ruamel-yaml<1,>=0.18.0
Requires-Dist: setuptools<81,>=68.0.0
Requires-Dist: typer[all]<1,>=0.12.0
Provides-Extra: dev
Requires-Dist: fastapi>=0.110.0; extra == 'dev'
Requires-Dist: httpx>=0.27.0; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest-mock>=3.14.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Provides-Extra: docgen
Description-Content-Type: text/markdown

# Quorum

Quorum is a structured multi-agent deliberation engine. Give it documents and a question; it returns a reasoned decision with confidence score, dissent trail, and an actionable recommendation.

## Install

```bash
pip install quorum-engine
pip install quorum-engine[docgen]   # optional: document artifact generation
```

The distribution name on PyPI is `quorum-engine` (the bare `quorum` name belongs
to an old Flask extension); the import name is just `quorum`.

## Quick start

```python
from quorum import Quorum

result = Quorum.deliberate(
    objective="Should we adopt the proposed API contract schema?",
    documents=[contract_text, design_doc_text],
)

print(result.decision)
print(f"Confidence: {result.confidence:.0%}")
print(f"Recommendation: {result.recommendation}")

if result.requires_human_review:
    print("Human review required before proceeding.")
```

With no further arguments, Quorum:

- **Picks the panel from your objective and documents.** It matches keywords (no extra LLM call) to
  specialist roles such as `risk_assessor`, `legal_counsel`, `financial_analyst` or `technical_architect`,
  and always seats at least three specialists, plus the Challenger and Synthesizer. Pass `roster=[...]` to
  choose the panel yourself.
- **Runs at `standard` depth**, which adds the Meta-Reviewer and a challenge round. Pass `depth="fast"` for
  quick triage or `depth="thorough"` for the full protocol.
- **Stops after 30 minutes** (`timeout_seconds=1800`). Slow models can take 15 to 30 minutes at `standard` and
  longer at `thorough`; raise the limit up to 3600 seconds in that case. A run that hits the limit returns a
  partial result with `"timeout"` in `result.failure_modes`.

It needs an LLM provider: set `QUORUM_LLM_PROVIDER` and the matching API key (see Install).

## Deliberation depth

The `depth` parameter controls how much analytical enrichment the deliberation applies. All three levels use the same three-round structure; deeper levels add more within each round.

```python
result = Quorum.deliberate(
    objective="Should we adopt the proposed API contract schema?",
    documents=[contract_text, design_doc_text],
    depth="standard",   # "fast" | "standard" | "thorough"
)
```

| Depth | What's added | Cost vs. fast |
|---|---|---|
| `fast` | Baseline 3-round debate | 1× |
| `standard` | R1 self-critique · multi-mode challenger · Meta-Reviewer (R2.5) · specialist ranking | ~1.5–2× |
| `thorough` | All of standard + two-phase execution · convergence-adaptive routing · multi-turn challenger · Evolution Agent (Phase 3) | ~3–4× |

**`standard`** is the default, and the recommended choice for most use cases. **`fast`** is appropriate for quick triage. **`thorough`** is for high-stakes decisions where quality matters more than latency.

## Privacy and data flow

Quorum is a library: it runs in your process, has no server of its own, and writes nothing to disk except
transcripts and results you ask it to save.

**Where your documents go.** The objective and documents are sent to the LLM provider you configure for the
specialist agents. If you enable the optional fact ledger or verifier, the facts, the debate text and the
synthesis also go to the providers you name for them (an OpenRouter model for extraction or the legacy judge,
and TypeSafe Jev or Cloudflare Clef for a decision-model judge). API keys are read from environment variables
you name; Quorum never writes them to configs, results or logs.

**Telemetry.** Quorum runs its agents on [crewAI](https://github.com/crewAIInc/crewAI), and crewAI sends
anonymous usage telemetry to `telemetry.crewai.com` by default. By crewAI 0.79's source and its own
documentation, that is structural metadata only: the crewAI and Python versions, a crew identifier, the process
type, whether memory is on, and counts of agents and tasks. It does not include prompts, documents, agent goals,
task descriptions, outputs, or environment variables, because those are shared only when a crew sets
`share_crew`, which Quorum never does. (This comes from reading the source; the network traffic itself has not
been inspected.)

To turn it off, set `OTEL_SDK_DISABLED=true` in the environment or in your `.env` file before running:

```bash
export OTEL_SDK_DISABLED=true
```

Quorum does not change crewAI's default, so telemetry is on unless you set this.

## Service integration

For production use, construct a `QuorumClient` once at service startup and reuse it across requests:

```python
from quorum import QuorumClient

# At startup — once
client = QuorumClient()
client.initialize(
    specialist_llm=app.llm,
    synthesizer_llm=app.frontier_llm,
    charter="All decisions must comply with GDPR.",
    default_roster=["analyst", "risk_assessor", "challenger", "synthesizer"],
)

# Per request — async
result = await client.deliberate(
    objective="Is this proposal well-supported by the evidence?",
    documents=[doc1, doc2],
    depth="standard",
)

match result.recommendation:
    case "auto_approve":
        proceed_automatically(result)
    case "human_review":
        queue_for_review(result)
    case "human_required":
        escalate(result)
```

> **Note:** `Quorum.deliberate()` is a synchronous convenience method that accepts plain strings. `QuorumClient.deliberate()` is async and accepts `str` or `Document` objects. Use `QuorumClient` for all production service integrations.

## Primary path: QuorumClient + YAML teams

`QuorumClient` (plus the CLI) is the supported, recommended entry point into Quorum. `Quorum.deliberate()` / `Quorum.adeliberate()` remain as convenience shortcuts for quick scripts and prototyping. The bundled FastAPI HTTP service (`quorum/service.py`) is **experimental** and not part of the supported release surface.

Declarative YAML team configuration lets you build a fully-configured client — roster, charter, guardrails, model tiers — from a single spec file:

```python
from quorum import QuorumClient

client = QuorumClient.from_yaml("team.yaml", transcript_dir="./transcripts")
result = client.deliberate_sync(
    objective="Should we proceed?",
    documents=[open("proposal.md").read()],
)
print(result.decision, result.confidence)
```

Passing `transcript_dir` also enables the audit trail: final `.md`/`.jsonl` transcripts and a crash-recovery `.partial.md` checkpoint are persisted automatically.

## Understanding the result

| Field | Type | Description |
|---|---|---|
| `decision` | `str` | Final decision text |
| `reasoning` | `str` | Synthesizer's explanation for the decision |
| `confidence` | `float` 0–1 | Synthesizer's certainty |
| `recommendation` | `str` | `auto_approve` / `human_review` / `human_required` |
| `dissenting_opinions` | `list` | Minority views not adopted |
| `requires_human_review` | `bool` | True when confidence < threshold |
| `convergence` | `dict` | R1 position agreement score and flags |
| `specialist_rankings` | `list` | Heuristic evidence-quality ranking of R1 specialists (standard/thorough) |
| `meta_review_summary` | `str` | Meta-Reviewer's pattern synthesis (standard/thorough) |
| `evolution_summary` | `str` | Evolution Agent's refined synthesis (thorough only) |
| `failure_modes` | `list` | Named failure modes detected during deliberation |
| `verification` | `dict \| None` | Advisory verifier verdict (`status`, `normalized_score`, redacted `verifier_metadata`, per-criterion scores, `confidence_gap`). Present only when a verifier is configured. Never mutates `decision`/`confidence`/`recommendation` |
| `verifier_trace` | `dict \| None` | Verifier reasoning trace (full on success; minimal `{status, reason}` on an engine-side exception). Not included in `to_dict()` output |
| `fact_ledger` | `dict \| None` | Advisory fact-survival measurement (`n_facts`, per-round `system_retention`/`agent_retention`, `survival_at_synthesis`, `casualties`, `never_raised`). Present only when the fact ledger is configured. Never mutates `decision`/`confidence`/`recommendation`. Metadata includes `judge_provider`/`decision_calls` when a decision-model judge is selected |

## Verification (optional, advisory)

Quorum ships an independent **LLM-as-a-Verifier** measurement layer that wraps the
deliberation and scores its output — without changing the decision. It reads a score
from a scoring-token logit distribution (per the [LLM-as-a-Verifier paper](LLM_VERIFIER_ENHANCEMENT.md))
and writes an advisory verdict to `result.verification`. **It never mutates
`decision`, `confidence`, or `recommendation`** — display it, log it, or gate on it,
but the deliberation's outcome is untouched.

Enable it with a `verifier:` block in your YAML (works in both the `TeamSpec` and
thin CLI formats):

```yaml
verifier:
  enabled: true
  provider: internal          # "fake" | "internal" | "openrouter"
  scoring: structured         # "structured" | "logprob"
  api_key_env: OPENROUTER_API_KEY  # env-var NAME, never the key itself
```

- `"internal"` — heuristic verifier, zero LLM cost, the default.
- `"openrouter"` — an SLM via OpenRouter (native `top_logprobs`); LIVE-gated behind
  `QUORUM_RUN_LIVE=1`. The verifier need not be a frontier model.

`QuorumClient.from_yaml` and `quorum deliberate` pick it up automatically;
`quorum validate` reports whether it's enabled, and `quorum verify` re-verifies a
saved result. See [docs/VERIFICATION.md](docs/VERIFICATION.md) for the full schema,
the programmatic API, reading the verdict, and the §14 security invariants
(`api_key_env` names only; no raw logprobs in output; redacted `verifier_metadata`).

## Fact-survival ledger (optional, advisory)

Quorum can also measure whether the issue-critical facts in your documents
**survive the deliberation** — the twin of convergence (agents can agree more
while knowing less). Enable it with a `fact_ledger:` block (seed your own facts
or extract them at intake with a cheap SLM), and read `result.fact_ledger`
— per-round retention, the casualty list with the round each fact died in,
and the never-raised list — always beside `result.convergence` (which now
carries `stance_entropy`). **It never mutates `decision`, `confidence`, or
`recommendation`**, and any failure degrades gracefully
(`fact_ledger_unavailable` in `failure_modes`). See
[docs/FACT_LEDGER.md](docs/FACT_LEDGER.md) for the full schema, the
programmatic API, and the cost profile.

## Seed positions

Inject expert positions into the deliberation alongside agent-generated analyses. Seeds compete on equal footing — the Challenger and Synthesizer read them as declared positions.

```python
result = Quorum.deliberate(
    objective="Should we migrate the payment service to event sourcing?",
    documents=[design_doc],
    seed_positions=[
        "Engineering Lead position: MODIFY — event sourcing is correct but requires "
        "a 6-month migration buffer that the current Q3 deadline does not accommodate.",
    ],
    depth="standard",
)
```

## Document model (optional)

Use `Document` instead of a plain string when source provenance and trust weighting matter:

```python
from quorum import Document

doc = Document(
    content="The proposed schema introduces three breaking changes...",
    source="contract_v3.pdf",
    reliability=0.95,
)

result = await client.deliberate(
    objective="Should we adopt the schema?",
    documents=[doc],
)
```

Agents are told the document's source and reliability score, allowing them to weight evidence and cite sources in their analysis.

In YAML configs and on the CLI (`--documents`), `documents` entries may also be paths to text files; they are read and their path becomes the source. In Python, pass the text (or a `Document`) yourself.

## DocGen (optional)

`DocumentGenerator` turns a `DeliberationResult` into a formatted document artifact — without re-running the debate:

```python
from quorum.docgen import DocumentGenerator, DocumentSpec

gen = DocumentGenerator(llm=app.cheap_llm)
spec = DocumentSpec(artifact_type="executive_brief", audience="C-suite")
document = await gen.generate(result, spec)
```

Built-in artifact types: `decision_summary`, `executive_brief`, `risk_report`, `adr`.

→ [Full Integration Guide](docs/integration-guide.md)
