agentleFS
amiable-devamiable-dev/llm-council/CLAUDE.md

llm-council

CLAUDE.md51 starsChanged 11 months agoMITView on GitHub

Durable architecture, design rationale, and gotchas for future sessions. This file is a map and a rationale, not an API reference — for function signatures, read the source (they go stale here). When you change behavior that contradicts a note below, update the note. LLM Council is a 3-stage deliberation system where multiple LLMs collaboratively answer a question. The core innovation: anonymized peer review in Stage 2 (models rank "Response A/B/C…", not each other by name) so they can't play…

  • Reads credentials
  • Commits and pushes

The file

We split this CLAUDE.md into the rules it gives an agent

5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Very specific:

    Run the HTTP API: llm-council serve [--host H] [--port 8000] (default 127.0.0.1:8000 — loopback since 0.54.

    line 14
  2. Very specific:

    Keep package-internal imports relative (from .x import …).

    line 188
  3. Very specific:

    Update CHANGELOG.md (Keep a Changelog: Added / Changed / Fixed / Removed).

    line 200
  4. Very specific:

    Wait for required checks: Test, Lint, Type Check, DCO (DCO needs --signoff).

    line 203
  5. Very specific:

    Verify: gh run list --workflow=publish.yml --limit=1, then pip index versions llm-council-core.

    line 206

≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md — Technical Notes for LLM Council

Durable architecture, design rationale, and gotchas for future sessions. This file is a map and a rationale, not an API reference — for function signatures, read the source (they go stale here). When you change behavior that contradicts a note below, update the note.

Project Overview

LLM Council is a 3-stage deliberation system where multiple LLMs collaboratively answer a question. The core innovation: anonymized peer review in Stage 2 (models rank "Response A/B/C…", not each other by name) so they can't play favorites.

It is a single Python package (src/llm_council/) exposing a CLI, an HTTP/REST server, and an MCP server. There is no separate frontend or backend/ directory — older docs referencing backend.main, frontend/src/, main.py, or storage.py describe a retired layout.

Running & Developing

  • Install / setup: make setup (deps + .env), or make install (deps only).
  • Run the HTTP API: llm-council serve [--host H] [--port 8000] (default 127.0.0.1:8000 — loopback since 0.54; was 0.0.0.0. A non-loopback bind with no LLM_COUNCIL_API_TOKEN warns on stderr and still starts; the bundled Dockerfile/railway.json pass --host 0.0.0.0 explicitly). Entry point is llm_council.cli:main; the FastAPI app lives in src/llm_council/http_server.py.
  • Other CLI subcommands: setup-key (store API key in keychain, ADR-013), bias-report (cross-session bias analysis, ADR-018), install-skills, gate, ignore (inspect the verify file-selection trust boundary — --print-defaults/--explain/--init, ADR-053).
  • Quality gates: make test / make test-fast / make test-cov, make lint (ruff), make typecheck (mypy), make check (lint+typecheck), make fix. ~120 test files in tests/.
  • tests/test_openrouter.py verifies OpenRouter connectivity and that a model identifier resolves before you add it to the council.
  • Relative imports: modules import siblings as from .unified_config import …. Keep imports relative within the package.
  • ADRs live in docs/adr/. Most subsystems below cite the ADR that introduced them — read it for design context.
  • Every source file stays reviewable (#720). Council verify caps input at 50K chars; a bigger file can't be reviewed, and a diff passed as evidence is not accepted as review. tests/test_issue720_file_size_ratchet.py holds every src/ file to 40K (headroom for a test file + evidence in one review); the files already over it are grandfathered in CEILINGS at their size, which may only be lowered. When a change would push a file over, split it in the same PR (patch where names are CONSUMED — see the council.py note), and delete its CEILINGS entry once it's under.
  • Definition of Done includes the published docs site (docs/ + mkdocs.yml nav), not just README/CLAUDE.md/CHANGELOG — the site froze at ADR-038 when it was left out of epic DoDs. tests/test_docs_drift.py enforces the mechanical parts (env reference, ADR nav, guide snippets).

Architecture: the L1→L4 layer model (ADR-024)

Requests flow through four layers with formal boundary contracts in layer_contracts.py:

  • L1 Tier (tier_contract.py, ADR-022) — picks a confidence tier (quick|balanced|high|reasoning, plus frontier) and its TierContract (timeouts, token budget, peer-review/verifier flags, allowed/aggregator models, escalation policy).
  • L2 Triage (triage/, ADR-020) — domain classification, wildcard specialist selection, per-model prompt optimization (e.g. Claude XML), complexity heuristics.
  • L3 Council (council.py) — the 3-stage deliberation core.
  • L4 Gateway (gateway/, gateway_adapter.py, ADR-023/030) — provider calls, circuit breaking.

Principles (ADR-024): layer sovereignty (each layer owns its decision), explicit/auditable escalation, failure isolation (gateway failures don't cascade into tier changes), constraint propagation downward, observability by default. Every boundary crossing validates and emits a LayerEvent (emit_layer_event()); observability/ bridges those events to StatsD/Prometheus (ADR-030).

Module map (src/llm_council/)

Council core

  • council.py — the two orchestrators (run_council_with_fallback, run_full_council), config helpers with patched-attr test semantics, deprecated-constant __getattr__. Split below the review cap (ADR-046 P0, #408): stage functions live in council_stages.py (stage1_collect_responses[_with_status], stage1_5_normalize_styles, stage2_collect_rankings, stage3_synthesize_final, quick_synthesis), ranking/Borda/shadow-votes in council_rankings.py (parse_ranking_from_text, calculate_aggregate_rankings), shared constants + ADR-011 usage accounting in council_usage.py. council.py re-exports every moved name, so llm_council.council.X imports and patches keep working; patches on names CONSUMED inside stage functions (e.g. query_models_parallel) must target llm_council.council_stages.*. Moved code reads config helpers through the council module at call time, preserving patch("llm_council.council.CHAIRMAN_MODEL", …). Stage-timeout GOTCHA (#648): stage2_collect_rankings and stage3_synthesize_final each default timeout=120.0, and for a long time BOTH consult orchestrators simply omitted the argument — so peer review and chairman synthesis ran at 120s regardless of tier, and LLM_COUNCIL_TIMEOUT_MULTIPLIER (which correctly reaches TierContract.per_model_timeout_ms) never reached either stage. That was invisible until the chairman became claude-opus-5 (#635) and every reasoning-tier consult lost its synthesis. Both orchestrators now pass resolve_stage_timeout(per_model_timeout) (council_usage.py) = max(per_model, TIMEOUT_STAGE_FLOOR=120); the floor exists because high tier's per-model budget is 90s and balanced's 45s, so the literal ADR-040 waterfall cap would have SHRUNK those stages. run_full_council is tier-agnostic and takes an optional per_model_timeout (None ⇒ the floor); the HTTP /v1/council/run endpoint passes the high-tier contract's value, the tier it already assumes for its evidence budget. A new call to either stage function must pass timeout explicitly — tests/test_issue648_consult_stage_timeouts.py AST-pins every call site in council.py, because the original defect was an omitted kwarg that reads as correct code.
  • consult_render.py (#660) — pure presentation helpers for the consult surface: synthesis_heading / degradation_notice / status_block / render_consult_body. Exists because consult_council hardcoded ### Chairman's Synthesis for EVERY outcome with the "N of M models" disclosure appended below the content, so a chairman-failed fallback (one member's raw text) was rendered with the authority of a completed council. Invariants: the heading is a function of metadata["synthesis_type"]/status and never defaults to the success heading on unknown input; the notice precedes the body; the JSON status block is emitted unconditionally (a block that appears only on degradation is itself something a caller must detect). GOTCHA: synthesis_type gained single_model_raw — set in run_council_with_fallback only when quick_synthesis reports outcome["chairman"] == "failed"; the old code labelled that case partial, which is why it read as deliberation. quick_synthesis cannot label its own output, so it reports facts back through the caller-supplied outcome dict (same pattern as shared_raw_responses). Its chairman call was a hardcoded timeout=15.0 — the ONLY synthesis attempt on the global-timeout path, so a heavyweight chairman that had just blown a 90s stage-1 budget was re-asked with 15s; call sites now pass the tier budget and are AST-pinned in tests/test_issue660_honest_degradation.py (#648's defect class). Dissent for verdict_type="synthesis" lives in metadata["dissent"] and was never read by the MCP surface (rendered only inside the ADR-025b verdict block) — include_dissent=true was a silent no-op in the DEFAULT verdict type.
  • openrouter.py — query_model / query_models_parallel; returns {content, reasoning_details?}; returns None on failure (graceful degradation). Per-model timeouts ARE independent (asyncio.wait_for per task, then gathered) — a recurring misdiagnosis; the tier total is enforced separately as run_council_with_fallback's synthesis_deadline.
  • http_server.py, mcp_server.py, cli.py — the three entry surfaces. skills/ — bundled skills (install-skills).

Tiering & model selection

  • tier_contract.py (ADR-022), unified_config.py (ADR-024, see below).
  • metadata/ (ADR-026/028) — model metadata abstraction. StaticRegistryProvider (offline, bundled models/registry.yaml, ~61 models / 10 providers) and DynamicMetadataProvider (OpenRouter API + TTL cache). Background discovery worker + request-time discovery (ADR-028). intersection.py resolves tier membership for multi-tier models (e.g. o1-preview).
  • triage/ (ADR-020), reasoning/ (ADR-026 Phase 2 — effort levels), performance/ (ADR-026 Phase 3 — internal performance index from real sessions).

Frontier tier lifecycle (ADR-027/029)

  • voting.py — VotingAuthority (FULL / ADVISORY / EXCLUDED). Frontier tier defaults to ADVISORY (Shadow Mode): votes logged + evaluated but zero weight in consensus.
  • audition/ (ADR-029) — cold-start state machine SHADOW → PROBATION → EVALUATION → FULL (+ QUARANTINE). New models earn voting weight by volume before counting.
  • graduation.py — promote frontier → high (≥30 days, ≥100 sessions, <2% errors, ≥75th pct).
  • cost_ceiling.py — frontier capped at 5× high-tier avg cost. frontier_fallback.py — hard fallback frontier → high on timeout/rate-limit/API error.

Evaluation & scoring

  • rubric.py (ADR-016) — multi-dimensional scoring (accuracy/relevance/completeness/conciseness/clarity). Accuracy acts as a ceiling (calculate_weighted_score_with_accuracy_ceiling): accuracy <5 caps at 4.0, 5–6 caps at 7.0, ≥7 uncapped — prevents confident-but-wrong answers ranking well. Falls back to holistic parsing if rubric JSON won't parse.
  • safety_gate.py (ADR-016) — caps score on harmful-pattern detection; context-aware exclusions for educational/defensive content.
  • evaluation.py, quality/, verdict.py, dissent.py — additional evaluation/quality surfaces.
  • gateway/ (ADR-030) — EnhancedCircuitBreaker (sliding-window failure rate, default 25% over 10-min window, 30-min cooldown, half-open probes) + per-model registry that emits L4_CIRCUIT_BREAKER_OPEN/CLOSE. scoring.py — cost-scoring algorithms (linear/log_ratio/exponential).

Compute-optimal deliberation (ADR-044, Phase 1–3)

  • graduated_depth.py (P3) — decision engine + opt-in hook (plan_escalation) for the depth ladder single→mini(3)→full: prefix-superset model sets (shallow responses always reusable, escalation only ADDS models), escalation gated on known-low CSS/confidence (unknown never escalates), ADR-011 estimator prices the added rung, opt-in BudgetEnforcer can veto (auditable, never a silent downgrade), approved escalations emit L2_DELIBERATION_ESCALATION. merge_usage_summaries sums usage across rungs (cost_known ORs). Active ladder still unwired (slice 2, gated on shadow data). #618 shadow telemetry IS wired into both orchestrators post-rankings: evaluate_and_log_shadow_depth classifies every full-depth run ("was full depth necessary?" — mini_would_suffice/premature_halt_risk/would_escalate/…) using internally-computed CSS (deliberately independent of LLM_COUNCIL_QUALITY_METRICS — that's an output-annotation flag) plus a counterfactual mini-rung CSS (subset re-rank of the mini prefix's reviews; approximation, both error directions observable), and appends JSONL to .council/depth/decisions.jsonl (numeric signals only, soft-fail, response byte-identical). Enablement criterion for slice 2: premature_halt_risk rate. GOTCHA (metric, ADR-036): unanimous clean rankings score CSS exactly 0.7 (the threshold boundary — winner margin caps at 0.25 under uniform spacing) and an all-tied aggregate returns 1.0 ("consensus on equality"), so rotational disagreement reads as perfect consensus.
  • early_consensus.py (P2) — unassailable_leader (strict Borda-margin math: decided iff leader > best rival + remaining×(n−1)) + borda_update + estimate_reviewers_cost (ADR-011 history). Stage 2 checks per completion on the incremental path; flag ON cancels outstanding reviewers cooperatively and emits L3_EARLY_CONSENSUS_TERMINATION (votes/cost saved); flag OFF (default) is shadow mode — logs the would-have-terminated point so savings are measurable before enabling. Detection is non-authoritative and soft-fail; dissent extraction still runs on collected reviews.
  • metadata/selection.py _blend_quality_with_performance — opt-in (LLM_COUNCIL_PERFORMANCE_SELECTION) blend of the live index (mean_borda_score) into static quality, weighted by confidence tier (PRELIMINARY 0.3 / MODERATE 0.6 / HIGH 0.8, cap 0.8; INSUFFICIENT→static). select_tier_models compares static vs blended selections and emits L2_PERFORMANCE_SELECTION_APPLIED only when the set changed (route receipt). Soft-fail; flag-off is byte-identical.

Cost & token accounting (ADR-011, Phase 1–4)

  • budget/ (Phase 4) — opt-in budget enforcement, DEFAULT OFF. CostEstimator pre-query estimate (low/expected/high) from per-model cost history; BudgetEnforcer tiered pre_query_check (STRICT/BALANCED/PERMISSIVE) + mid_query_check (abort gracefully between stages, never mid-completion). Every reject/warn/abort emits an auditable L1_BUDGET_DECISION LayerEvent — budget never causes a silent tier change (ADR-024). Enable via LLM_COUNCIL_BUDGET_ENFORCEMENT=true + LLM_COUNCIL_BUDGET_MODE; wire at the L1 entry (module + hook, not in the hot path by default).
  • performance/ (Phase 3) — ModelSessionMetric.cost_usd + ModelPerformanceIndex.mean_cost_usd/.quality_per_cost (Borda-per-dollar). tracker.get_cost_per_quality and get_all_cost_aware_scores provide an opt-in cost-aware ranking — get_all_cost_aware_scores is identical to get_all_model_scores unless LLM_COUNCIL_COST_AWARE_SELECTION=true, and is the SOLE path by which cost may influence selection (audited). persist_session_performance_data records per-model cost from the council's usage.by_model (only when cost_known). Both consult orchestrators persist since #692 via council_usage.persist_council_performance — the single write path, so the two cannot drift, AST-pinned in tests/test_issue692_consult_performance_record.py. Before it, performance_metrics.jsonl had exactly ONE writer (the verify path) and every consult — the expensive path — left no cost trail, so a recorded total could not be reconciled against a provider invoice. Schema 1.1.0 makes borda_score and latency_ms nullable alongside the existing nullable cost_usd, all for one reason: an unmeasured value must not be written as a zero, because a zero is a measurement (borda 0.0 = "ranked last", latency 0 = "answered instantly"). Both _index_from_records and get_all_model_scores skip nulls when averaging — mypy caught the second site, not the tests. GOTCHA: run_full_council (HTTP /v1/council/run) has no per-model latency at all — stage1_collect_responses returns only {model, response} — so it records latency_ms: None; wiring it with a 0 would have poisoned the p50/p95 percentiles that tier-budget decisions and MEASURED_LATENCY_S read. Partial runs DO record (deliberate divergence from verify, which persists nothing on timeout): a timed-out consult still billed. Store resolution is LAZY (#693): resolve_store_path() / tracking_enabled(), never the module constants directly. PERFORMANCE_STORE_PATH and PERFORMANCE_TRACKING_ENABLED survive as optional overrides (default None ⇒ read the env per call) because a lot of tests monkeypatch them by name. They used to BE the resolved values, computed at import time, which made LLM_COUNCIL_PERFORMANCE_STORE unsettable from a test — collection imports before any test body runs — and the suite appended 1,868 test/model-a fixture rows to the operator's real ~/.llm-council/performance_metrics.jsonl, a quarter of the file. Those rows carry cost_usd: null, so a third of the file read as a cost-capture failure and the investigation chased the wrong defect; real coverage from 2026-07-04 was 2330/2330. tests/conftest.py's autouse isolate_performance_store redirects every test to tmp_path AND resets the get_tracker() singleton (which memoises the path from its first call); tests/test_issue693_store_isolation.py fails if the resolved path is ever under the real HOME. Operator cleanup is documented, never automatic (docs/guides/performance-store.md) — council does not rewrite a measurement file it did not author.
  • observability/posthog_emitter.py + ai_generation.py + adjudication.py (ADR-050, epic #472) — opt-in, off-by-default PostHog LLM-analytics emission. posthog_emitter (D1): POSTHOG_API_KEY/POSTHOG_HOST (EU ingestion eu.i.posthog.com), import-guarded lazy client (the [posthog] extra is never imported when unconfigured ⇒ byte-identical), non-blocking soft-fail emit(), bounded idempotent shutdown(), scrub_exception (D3, logs type only). ai_generation (D2): maps usage.by_model → one $ai_generation per member, $ai_trace_id=verification_id, cache-subtraction clamp $ai_input_tokens=max(0,prompt−cache_read) (PostHog hit-rate tile assumes exclusive counting), $ai_total_cost_usd=ADR-011 ground truth when cost_known; allowlist mapper (D3, never emits $ai_input/$ai_output_choices); wired soft-fail into verification/api.py (_emit_posthog_generations, gated before import). adjudication (D4): emit_adjudication posts a follow-up $ai_metric keyed to $ai_trace_id (numeric value + adjudication_label) — the epic-loop retro hook, NOT PostHog's automated Evaluations. GOTCHA: $ai_metric value-type/scope is verify-before-impl (public docs don't pin it). Display side (project amiable-llm-ops/212129, dashboard 793592) pre-exists. Part 4 (feature-flag tier routing) deferred to a future ADR.
  • observability/usage_metrics.py (Phase 2) — emit_usage_metrics emits per-model token/cost via the MetricsAdapter (ADR-030) using OTel GenAI names (gen_ai.client.token.usage histogram + llm_council.cost.usd gauge); wired into both council entry points, soft-fail. examples/observability/ ships an OTel-Collector overlay (Prometheus/Grafana + OTLP → PostHog), a Grafana dashboard, and configs — one emitter, many sinks; dashboards are BYO-backend (ADR-009).
  • gateway/cost_resolver.py — CostResolver stamps cost_usd + cost_source on each call: provider ground-truth for OpenRouter/Requesty (inline usage.cost, previously discarded), registry_estimate for Direct APIs (registry.yaml pricing × tokens), local_zero for Ollama. registry_pricing_lookup bridges to metadata.get_provider().get_pricing. ADR-049 D3: resolve() prices cache_read/_write_5m/_write_1h_tokens (the provider's SEPARATE fields, additive to prompt_tokens) via optional same-named per-1K classes in registry.yaml (Anthropic entries carry 0.1×/1.25×/2× prompt); an absent class bills at the prompt price; provider-cost path never consults them (ground truth already includes the discount).
  • openrouter.py query_model now captures cost/cached_tokens; council.py aggregates per-stage and per-model (_add_cost_to_usage → _build_usage_summary, shared by both entry points) into metadata["usage"] = {by_stage, by_model, total} — each carries cost_usd/cached_tokens. Never presents an estimate as a bill (cost_source distinguishes). Cost accounting never fails a run (soft-fail).
  • cost_summary.py format_cost_summary renders usage with progressive disclosure: one dense line by default, full per-model/per-stage breakdown only under include_details. Surfaced in MCP consult_council ("Cost & Tokens") and as a typed usage field on the HTTP CouncilResponse. Releases: one version bump per epic, not per PR (git-tag/setuptools-scm; publish.yml triggers on tag only).

Prompt caching (ADR-049)

  • D1 (#459) — verification/api.py _build_verification_prompt assembles stability-ordered segments static_head → evidence → subject → volatile_tail; the snapshot SHA lives ONLY in the tail (was line 1, killing cache reuse from byte zero). render_info["segments"] = contiguous {name,start,end,est_tokens(=chars//4)} — the D2 breakpoint map. Byte-stability golden-tested (tests/test_prompt_segments.py).
  • D5 (#463) — prompt_cache_ttl(path_default) reads LLM_COUNCIL_PROMPT_CACHE_TTL (5m|1h, invalid ⇒ path default; NOT LLM_COUNCIL_CACHE_TTL, which is the response cache). Verify publishes ttl=prompt_cache_ttl("1h"); CacheContext.ttl dataclass default is 5m (interactive). tests/integration/test_live_cache_probe.py = opt-in LIVE two-call probe (LLM_COUNCIL_LIVE_CACHE_PROBE=true, ~$0.05, never CI) asserting second-call cache reads > 0 + discounted usage.cost; its docstring carries the quarterly re-probe note for the REFUTED matrix rows (OpenAI/Gemini/DeepSeek via OpenRouter).
  • D4 (#462) — cache-WRITE + route/session telemetry: openrouter.py _extract_cache_write_tokens (precedence: Anthropic cache_creation_input_tokens → per-TTL cache_creation.*_input_tokens sum → OpenRouter prompt_tokens_details.cache_write_tokens — the OpenRouter name is empirically observed, not vendor-documented; missing ⇒ 0, full-price accounting). cache_write_tokens rides ADR-011 aggregation (council_usage.py per stage/model/total) into verify input_metrics; query_model results carry route + session_id; input_metrics.cache_session_id groups rounds so hit-rate per subject is reconstructable from .council/logs alone (zero reads across rounds = broken prefix or lapsed TTL).
  • D2 (#460) — cache_context.py: request-scoped CacheContext ContextVar (segments + session_id + ttl, house _request_api_key pattern). run_verification publishes session_id="verify:{sha1(sorted target_paths)[:12]}" (stable across rounds — NEVER per-round SHA, affinity-only per ADR-049) and clears in finally. build_openrouter_payload consumes it: OpenRouter session_id on all vendors + cache_control breakpoints ({"type":"ephemeral","ttl":"1h"}) for anthropic/* at evidence/subject boundaries — only when the prompt MATCHES the segment map (stage-2/3 no-op) and cumulative est_tokens meets the per-model min prefix (re-checked 2026-10-09: Fable 5/5.1, Opus 5/5.5, Sonnet 5.5, Haiku 5.5: 512; Opus 4.8/Sonnet 5: 1,024; Haiku 4.5 + unknown: 4,096 — NOT monotonic across generations; below-minimum marks are silently uncached so we skip them). ≤2 of the 4-breakpoint limit used. LLM_COUNCIL_PROMPT_CACHING=false ⇒ byte-identical payloads; default ON (deliberate — price-class-only, payload format empirically verified). gateway/base.py CachingCapability descriptor on RouterCapabilities. GOTCHA: LLM_COUNCIL_CACHE_TTL already exists (response cache, seconds) — D5's prompt-cache TTL knob must use a different name (LLM_COUNCIL_PROMPT_CACHE_TTL).

Bench (ADR-048)

  • bench/publication.py + bench/adapters.py (P3, #420) — results page regenerated from harness output (bench report --publish); dependency-free DeepEval/RAGAS bridges (make_council_eval_callable, council_to_ragas_row — stage-1 drafts as contexts); framework wiring examples in examples/eval_bridges/.
  • bench/matrix.py (P2, #419) — config matrix (solo:<model>/council/graduated) over the same dataset; quality_per_dollar = pass_rate/known-cost (None when cost unknown/zero — never fabricated); solo configs skip min_score floors (no consensus signal); per-config runs individually capped; methodology + caveats in bench/METHODOLOGY.md.
  • bench/harness.py (P1, #418) — golden-dataset drift regression: bench/dataset/v1/ (20 items, envelopes = any-of must_contain groups + min_score consensus floor; governance in bench/dataset/GOVERNANCE.md), per-run cap enforced against ACTUALS with graceful partial abort (exit 2), monthly guard summed from .council/bench/runs/*.json, baseline snapshot + regression compare (exit 1 on drift). council_runner is injectable — CI tests never spend. Nightly workflow .github/workflows/bench.yml; NEVER per-PR.

Bias (ADR-015/018, ADR-047 P4)

  • bias_audit.py (ADR-015) — per-session indicators: length↔score correlation (pure-Python Pearson), reviewer calibration, position bias. These are anomaly indicators, not statistically robust proof — with N=4–5 models there are only 4–5 data points (≥30 needed for significance), and a single ordering can't separate position effects from quality.
  • bias_amplification.py (ADR-047 P4, #416) — reviewer-agreement decomposition: agreement_index × position_alignment per session; high agreement that tracks display order = amplification suspect (multi-agent judges can AMPLIFY shared bias, not cancel it). Report-only by contract (pure, no writes — test-pinned); surfaced via llm-council bias-report --amplification.
  • bias_persistence.py (ADR-018 P1) — JSONL store, ConsentLevel (OFF→RESEARCH). bias_aggregation.py (ADR-018 P2-3) — cross-session pooled correlation w/ CIs (Fisher-z), confidence tiers, temporal trends, anomaly flagging. Surfaced via llm-council bias-report. Query-hash secret (#614): LLM_COUNCIL_HASH_SECRET, else a random per-install secret created once (0600) at LLM_COUNCIL_HASH_SECRET_FILE / beside the bias store; if it cannot be created, hashing is SKIPPED — never a known default (a published key enables a dictionary attack on the store). tests/conftest.py redirects the file so no test writes the real HOME.

MCP 2026-07-28 adoption (ADR-045)

  • mcp_tasks.py (P1) — SDK-independent Tasks layer: TaskStore (durable .council/tasks/, 24h TTL from created_at, size-capped mtime-LRU eviction, in-memory fallback, atomic writes, terminal states first-writer-wins), 128-bit capability task ids (no enumeration API — the id IS the authz), LLM_COUNCIL_MCP_TASKS kill-switch, and sdk_supports_tasks() feature-detection (note: mcp 1.26 within the pin already ships the EXPERIMENTAL SEP-1686 types). Blocked-pending-SDK: maybe_expose_tasks is a documented no-op until the stable SDK v2 pin bump (targeted 2026-07-28), so sync tools stay byte-identical.
  • Stateless audit (P3) — docs/adr-045-p3-state-inventory.md inventories all MCP-path state for multi-instance deployment: TaskStore is the cross-instance contract (two-instance smoke: tests/test_stateless_smoke.py); per-instance circuit breakers/metrics/caches are deliberate (optimality, not correctness); _layer_events is a bounded ring buffer (MAX_LAYER_EVENTS). Re-audit if the MCP server gains streamable-HTTP transport.
  • server_card.py (P2) — SEP-2127 Server Card generated from the live FastMCP tool registry (no drift; test-pinned). Served by the HTTP server at /server-card + /.well-known/mcp/server-card.json (unauthenticated, like /health); llm-council server-card prints it; static server-card.json at repo root for registry submission (drift-tested, regenerate on release). Council-specific data (tools, tiers) lives under namespaced _meta — SEP-2127 cards exclude top-level primitive listings. RE-CHECK after 2026-07-28: RC schema vendored at tests/fixtures/server_card_v1_rc.schema.json; re-vendor + re-validate when the final schema ships.

Streaming (ADR-046)

  • P3 MCP progress: stage-2 per-reviewer progress flows to ctx.report_progress via the orchestrator's stage2_progress wrapper — created only when on_progress has a consumer (unconditional wiring would flip stage 2 onto the incremental path for every run).
  • P2 token streaming: stream_tokens=true on the SSE endpoint → stream_synthesis on run_council_with_fallback → stage3_synthesize_final(on_synthesis_delta=…) → gateway_adapter.query_model_stream_with_status (gateway complete_stream). Streamed path assembles the SAME result object (equality-tested); transport failure falls back to the non-streaming call; CancelledError propagates (never a fallback); streamed usage is {} ⇒ ADR-011 reports cost UNKNOWN (stream protocol carries no usage).
  • P1 rich SSE events: webhooks/_council_runner.py wraps every SSE event in the v1 envelope (v/session_id/ts/seq); run_council_with_fallback wires on_model_complete (stage1, through query_models_with_progress) and on_review_event (stage2 incremental path) into the EventBridge ONLY when a stream consumer exists — no consumer ⇒ None callbacks ⇒ pre-P1 code paths byte-identical (test-pinned). Event names: stage1.response, stage2.review, consensus.early_termination, stage3.start; terminals stay council.complete/council.error (ADR-046 implementation note). An on_event-only EventBridge has an EMPTY subscription set — always pass a webhook_config with the event list (see _council_runner).

Observability & telemetry

  • observability/external_spend.py (ADR-056, #695) — opt-in, off-by-default OTLP spans reporting council spend to the skills-telemetry ADR-010 external artefact contract. One span per RUN (not per model call), emitted where the ADR-011 usage summary already exists, from both consult orchestrators and the verify path. EXTERNAL_ATTRIBUTES is the SINGLE source of truth for what may be sent, and tests/test_issue695_external_spend.py compares it longhand, in both directions, against the published set transcribed from stdtel-conform --print-contract (stdtel 0.5.0, contract v2; v1 was stdtel/artefact.py @ 3d93d8b) — an attribute outside that set is DROPPED SILENTLY downstream, so a rename yields a column of nulls rather than an error, and a test comparing the constant to itself would pass through exactly that. GOTCHAS: contract v2 (#707, stdtel 0.5.0) — observed spend goes in std.external.cost_usd with cost_source provider/local; a #694 registry_estimate goes ONLY in std.external.cost_estimated_usd; cost_usd is the aggregate's own per-call cost_observed_usd (provider + local), NEVER total minus estimate; a usable amount with no mappable label, or a non-zero local_zero, sets cost_unattributed and withholds all cost attributes (round 3: a label SET made one provider call vouch for the whole sum); an incomplete total sends NO cost attributes (neither amount; both are lower bounds); an unobserved amount OMITS the attribute (never 0, never null). Build test usage through _add_cost_to_usage/_build_usage_summary, never by hand — v0.50.0's estimate guard read cost_source off the usage total, which the real aggregate never carried, so the rule held only in tests; the total now carries cost_source, cost_sources (the set seen — mixed loses which), cost_estimated_usd, cost_incomplete. skills-telemetry is OPTIONAL and never coupled: no dependency on, or import of, stdtel, and nothing in the required CI touches it. The drift check lives in the advisory external-contract.yml (every job continue-on-error), and tests/test_skills_telemetry_is_optional.py pins all of that. The longhand test is the gate. Operator: the endpoint must be set in the MCP server's env block — Claude Code strips it from the shell environment; std.artefact.source is emitter, never hook/transcript, which would claim an observation nothing outside this process made; session.id is the CLAUDE session from CLAUDE_CODE_SESSION_ID and is omitted (not faked) outside one, because council's own ids join to nothing. council_health_check.external_telemetry reports absence with a reason — a no-op emit path is right, silence is not, or an operator cannot tell "nothing was spent" from "nothing was recorded" (ADR-056 D8). stdtel-conform is a SECOND OPINION, not the gate; scripts/dump_external_spans.py produces the OTLP JSON it reads.
  • observability/ (ADR-030 metrics export — StatsD/Prometheus/NoOp), telemetry.py / telemetry_client.py, webhooks/.
  • Webhook destination guard (GHSA-r7rh-j9cj-h9hh, SSRF): webhooks/url_guard.py is the sole judge of where a webhook may go — verdict on the RESOLVED address (never the URL spelling), all records must be public, and WebhookDispatcher connects to the checked address (pinned_ip + Host header + httpx sni_hostname, so TLS still verifies the name; resolved once before the retry loop; follow_redirects=False is load-bearing). https_only relaxes the scheme ONLY. LLM_COUNCIL_WEBHOOK_ALLOWED_HOSTS is the one operator exception (private + plain http, exact host/host:port); there is no localhost dev exception any more. http_server._authorize_request_webhook: no LLM_COUNCIL_API_TOKEN ⇒ 403 for non-allowlisted webhook_url; statically-bad URL ⇒ 400. Rejection messages are fixed strings that never echo the URL (logged; unresolvable and resolves-private must be indistinguishable). Tests patch the url_guard._resolve_host seam — a webhook test with a non-allowlisted DNS name and no seam does real DNS. Run lifecycle (#739/#740): run_full_council has NO bridge code of its own — @deliver_council_webhooks (webhooks/run_session.py) owns it: ASYNC-mode bridge (queue worker ⇒ a receiver never delays the run), emits council.deliberation_start → council.complete (carries result) or council.error (exception, or the all-models-failed result) via EventBridge.emit_webhook (events with no LayerEvent behind them), then shuts the bridge down. webhook_delivery="await" (library default: drained before return, so an asyncio.run() loop can't drop events) vs "background" (HTTP endpoint; drain_webhook_deliveries runs on server shutdown). Soft-fail throughout; no webhook_config ⇒ plain passthrough. Settings (#741): WebhookDispatcher reads webhook_settings() at CONSTRUCTION (was import-time constants + wrong attr name timeout); LLM_COUNCIL_WEBHOOK_HTTPS_ONLY is wired and fails safe. STILL OPEN: webhooks.enabled (default false) is consulted by nothing; max_retries is really max ATTEMPTS (0 ⇒ nothing is sent).

Verification (ADR-034/040/041/053) — verification/api.py, verification/pipeline.py, verification/prompt.py, verification/file_ops.py, verification/coverage.py

  • api.py split (#720). api.py keeps run_verification (global deadline, salvage, screening, cap/empty-subject stops) and the endpoint; pipeline.py holds _run_verification_pipeline + the waterfall helpers; prompt.py holds _build_verification_prompt. api.py re-exports all three, but patches must target the consuming module: the stage functions, calculate_aggregate_rankings and build_verification_result → llm_council.verification.pipeline.*; the file fetch → llm_council.verification.prompt.*; _build_verification_prompt, _run_verification_pipeline, VerificationContextManager stay on api (run_verification consumes them). api.py deliberately no longer imports the stage functions, so a stale patch("…api.stage1_…") raises instead of silently calling a real model.
  • run_verification() wraps _run_verification_pipeline() (stages 1–3) in asyncio.wait_for() with a global deadline = tier_contract.deadline_ms/1000 × 2.0 (VERIFICATION_TIMEOUT_MULTIPLIER; raised from 1.5 so stage 3 isn't starved on slow days — balanced 180s, high 360s). On timeout, if stage 2 completed, the partial result salvages an advisory rubric/confidence signal (verdict stays unclear).
  • Waterfall time budget (ADR-040): stage1 = 50% of remaining, stage2 = 70% of what's left, stage3 = the rest, less a short tail (_stage3_tail_reserve = min(5s, 5%)). Stages 1–2 are capped by tier_timeout["per_model"] (it bounds the slowest of N parallel calls); stage 3 is NOT (#686): it is one call, the global deadline bounds it, and the per-model cap (45s balanced / 90s high vs a ~204s chairman) turned completed deliberations into unclear(infra_failure). The cap was drift from ADR-040, which always specified "all remaining". The tail exists so stage 3's own timeout fires before the outer wait_for (graceful path + local finish still run). tests/test_issue686_stage3_gets_the_rest.py fakes the pipeline clock and pins both the full and the partly-consumed budget.
  • Durable partial state: partial_state is updated after each stage and survives CancelledError, so a timeout still returns completed_stages. VerifyResponse carries timeout_fired, completed_stages, and (ADR-041) timing / input_metrics.
  • Per-tier input caps TIER_MAX_CHARS (quick 15K, balanced 30K, high/reasoning 50K). Per-file truncation (#342) is surfaced as an expansion_warnings entry rather than silently dropped; reasoning/high can read a file of almost 50K (the cap minus the prompt around it).
  • Subject fitting (#747): verification/subject_budget.py — TIER_MAX_CHARS caps the WHOLE prompt, so prompt.py passes the fetch max_chars = cap − (instructions + evidence + tail) (subject_room); sizing files against the cap alone made every change of about the cap's size input_too_large (the CI gate reviewed no code from 2026-09-28 until this fix). assemble_subject takes files in review_priority order (source, tests, config, docs — CHANGELOG.md/CLAUDE.md/README.md used to sort first and fill the budget alone), skips a file that does not fit and keeps going, and always includes the first file (cut to fit). The coverage receipt is built AFTER fitting (coverage_receipt): unfitted files are omitted with reason too_large (acknowledged by default for discovered paths; an explicitly named one clamps), never reviewed. The raw git show call stays in file_ops (a closure is handed to the fitter; AST-pinned). The gate workflow sets fail-on-unclear: true.
  • Performance tracker is wired on success only, wrapped in try/except so telemetry never fails verification.
  • Empty subject (#704). With target_paths=None, discovery runs git diff-tree -r <sha>^1 <sha>. The one-argument form prints NOTHING for a merge commit, and a PR's github.sha IS one, so the required CI gate reviewed an empty prompt on every PR (three passes and a fail over the same nothing). Not -m --first-parent: diff-tree ignores --first-parent and -m diffs every parent. When the #555 receipt says zero files were reviewed and the caller named none, run_verification returns error: no_reviewable_content before any model call, and gate exits 3 (GATE_EXIT_NOTHING_REVIEWED), never 2, which llm-council-action turns into a passing check. Explicit target_paths=[] is exempt (evidence-only). GOTCHA for tests: a fake snapshot with target_paths=None now stops early; stub _fetch_files_for_verification_async_with_metadata with a receipt (see tests/integration/verification/test_council_integration.py). council-gate.yml runs version: latest so gate fixes reach the gate.
  • Findings channel / mechanical gate (ADR-051, epic #484, C1–C3 in v0.36.0): verification/findings.py — opt-in LLM_COUNCIL_STRUCTURED_FINDINGS (default OFF, explicit true-set; flag-off byte-identical). The chairman's BINARY-verdict JSON gains a findings-first findings[]; parse_findings extracts it via an LLM-resilient string-aware balanced-brace scanner (_extract_json_object, preferred_key="findings") and soft-fails to the legacy prose path. verdict_policy(findings) is the mechanical gate: verdict = pure function of findings (any critical ⇒ fail), computed in build_verification_result when findings_source == "structured" (else legacy); blocking_issues = critical subset (List[BlockingIssueResponse], no type break). Severity is normalized fail-safe (_normalize_severity: missing/unrecognized/typo/blocker-ish ⇒ critical; only explicit non-critical synonyms downgrade). Models in schemas.py (Finding, VerifyDiagnostics); threaded into the result via api.py. C4 (#488) adds diagnostics.findings_by_severity + a defensive verdict_evidence_mismatch invariant marker; C5 (#489) adds diagnostics.inner_verdict/inner_confidence/inner_confidence_calibrated (structured verdict BEFORE the low-confidence UNCLEAR softening) and makes build_verification_result's mechanical block mutate result atomically (calibrate once, throw-free apply — a mid-block error leaves the legacy result intact). C6 (#490) documents the full response contract in docs/guides/verify.md and adds TestVerifyResponseFieldDrift (tests/test_docs_drift.py): every VerifyResponse/Finding/VerifyDiagnostics field must appear by name in verify.md or api.md or CI reds. Default-ON flip is a later breaking release. Spec: docs/adr/ADR-051-implementation-spec.md.
  • Screening judge (ADR-047 P3, #415): verification/screening.py — three-state LLM_COUNCIL_SCREENING (off default/shadow/active); eligibility INVARIANTS (blocking evidence — dicts AND Pydantic models — security focus, risk globs, 5K cap) checked before any model call; unanimity rule ≥LLM_COUNCIL_SCREEN_MIN_SCORE (9) on every dimension; decisions logged to .council/screening/decisions.jsonl; active-pass returns PASS-with-audit-note (screening.acted=true, council never ran). Soft-fail ⇒ full council.
  • Confidence calibration (ADR-047 P2, #414): verification/calibration.py — corpus loader/analyzer over .council/logs, PAV isotonic fit against human dispositions (.council/calibration/dispositions.jsonl → mapping.json), piecewise-linear CalibrationMapping (identity fallback, monotonicity enforced on load). confidence_calibrated reported on every response — telemetry only since ADR-054 D3a (#563): the LLM_COUNCIL_CALIBRATED_CONFIDENCE PASS gate was removed; no verdict threshold consumes either confidence number (D3b findings-uncertainty confidence is #628, gated on structured stage-1 findings). CLI: llm-council calibration-report [--fit].
  • UNCLEAR disambiguation (ADR-047 P1, #413): unclear_reason ∈ {infra_failure, low_confidence, timeout} on every unclear verdict (derive_unclear_reason in verdict_extractor.py; timeout checked first, then #403 error_status, else low_confidence). Exit code stays 2 — automation routes on the reason: retry infra, accept-and-audit low confidence, re-tier timeouts. #597 retry_hint (verification/escalation.py, pure): set when the run ran out of time — timeout, OR infra_failure whose stage-3 error_status == "timeout" (the #686 path; a chairman timeout is starvation, not infra) — and always points UP the TIER_LADDER (quick→balanced→high→reasoning; reduce_scope at the top). A lower tier has a SHORTER deadline, so a same/lower-tier retry during a slow window starves harder; the old timeout rationale said "use a faster tier", which was backwards. Advice only — auto-escalation would be opt-in + audited (ADR-044), not here. None when error marker is set (non-deliberated cap results).

File selection & coverage (ADR-053, epic #546 — v0.39.0 security slice + v0.40.0 P3). file_ops.select_blobs(snapshot_id, candidates) is the SOLE selection chokepoint (every candidate producer — blob/tree/diff-tree branches — routes through it; an unfiltered fetch is unrepresentable, AST-test-pinned). Layered, in order: Q3 secret boundary (_is_secret_path, compiled-in, case-insensitive, NOT overridable — closed the #540/#543 leak, shipped v0.39.0), Q2 garbage (path-component match), then Q1 decodability gated by LLM_COUNCIL_FILE_SELECTION (content default since the #557 flip, 2026-08-21 = git NUL heuristic + snapshot .gitattributes via git --attr-source=<sha> grep -I + linguist attrs + .svg-noise + the .llmignore family via pathspec; allowlist = the pre-flip TEXT_EXTENSIONS predicate, the one-var opt-out; shadow acts on allowlist and logs the delta to .council/selection/decisions.jsonl). Content-mode helpers make one git call each and pass -- before pathspecs. Coverage receipt (expansion_metadata["coverage"] → CoverageReport): typed {path,reason,origin} omissions + conservation invariant, additive/default-ON. Coverage clamp (verification/coverage.py, #556): coverage_policy()/coverage_ack_reasons()/coverage_clamp_decision() — a pass over an unreviewed changed/explicit file → unclear(incomplete_coverage). Opt-in: coverage._DEFAULT_POLICY="warn" (byte-identical); the ONE-LINE flip to clamp is #557, gated on shadow telemetry, and also activates gate_rejects_warn(). ADR ERRATUM: Q1's example list wrongly includes .envrc, which Q3a correctly denies (security wins; #573).

Key design decisions

Stage 2 prompt format — strict, to stay parseable: (1) evaluate each response individually, (2) emit a FINAL RANKING: header, (3) numbered list (1. Response C, 2. Response A, …), (4) nothing after the ranking. parse_ranking_from_text() handles numbered and plain forms; fallback regex extracts any Response X in order if a model misbehaves.

Anonymization / label_to_model — models see Response A/B/…; the backend keeps the mapping. Enhanced format (v0.3.0+) uses explicit indices to avoid string-parsing fragility:

{"Response A": {"model": "openai/gpt-4", "display_index": 0}, ...}
# INVARIANT: labels assigned in lexicographic order (A=0, B=1, …)

De-anonymization is for display only. Metadata (label_to_model, aggregate_rankings) is returned via the API but not persisted.

Error handling — continue with whatever responses succeed; never fail the whole request on a single model failure; only surface an error if all models fail.

Offline mode ("Sovereign Orchestrator", ADR-026) — LLM_COUNCIL_OFFLINE=true forces StaticRegistryProvider, disables external metadata/routing, and still completes all core council operations on stale/limited metadata.

Configuration (unified_config.py, ADR-024)

Single Pydantic source of truth consolidating ADR-020/022/023/026/030/031. Priority: YAML file > env vars > defaults. YAML searched at $LLM_COUNCIL_CONFIG → ./llm_council.yaml → ~/.config/llm-council/llm_council.yaml. Supports ${VAR} substitution. Sections: tiers, triage, gateways, model_intelligence, evaluation (rubric/safety/bias/scoring/circuit_breaker/audition), metrics.

Tier pools have ONE definition: src/llm_council/models/default_pools.yaml (#690), which ships in the wheel. default_pools.py loads it; tier_contract._DEFAULT_TIER_MODEL_POOLS, TierConfig.ensure_default_pools and CouncilConfig.models all derive from it and hold no literals — tests/test_issue690_pool_single_source.py AST-fails if one comes back, and tests/test_tier_pool_hygiene.py runs the budget/preview/registry invariants against it. The repo's llm_council.yaml deliberately does NOT declare tiers.pools, so this project runs the shipped defaults instead of shadowing them. GOTCHA: that file is not packaged, which is exactly how #685 shipped a changelog entry that was false for every PyPI install — it edited the unpackaged copy and left two Python literals stale. A user's tiers.pools.<tier> still wins per tier; omitted tiers fall back to the packaged definition. Model selection precedence at run time is explicit arg > tier pool > council.models (so LLM_COUNCIL_MODELS is a fallback, not a tier override). Chairman (#725, chairman.py): test patch on council.CHAIRMAN_MODEL > explicit council.chairman/LLM_COUNCIL_CHAIRMAN (every tier) > the tier in scope's aggregator_model > the default tier's aggregator. council.chairman now defaults to None; before #725 aggregator_model was dead config and every tier synthesised with opus-5 (the root of #686/#597). The tier is a request-scoped ContextVar set by run_council_with_fallback and run_verification and reset in their finally; run_full_council sets none, so it (and the response-cache key, and the health probe) use the default tier's chairman. Never read config.council.chairman directly — it is None unless an operator set one; call resolve_chairman().

Environment variable index

VarEffect
LLM_COUNCIL_MODELSOverride council members
LLM_COUNCIL_TIMEOUT_MULTIPLIERScales every tier timeout (timeouts.multiplier, 0.1–10.0, default 1.0). Since #648 it also reaches the consult path's stage 2/3 budgets. NOT the verify path's VERIFICATION_TIMEOUT_MULTIPLIER (a fixed 2.0 code constant)
LLM_COUNCIL_PERFORMANCE_SELECTIONADR-044 P1: blend the live performance index into model selection (default off; auditable route receipt on change)
LLM_COUNCIL_EARLY_CONSENSUSADR-044 P2: cancel remaining Stage-2 reviewers once the Borda leader is mathematically unassailable (default off = shadow mode, which only logs would-have-saved)
LLM_COUNCIL_GRADUATED_DEPTHADR-044 P3: graduated deliberation depth ladder single→mini→full with consensus-gated escalation + budget veto (default off). #618 shadow telemetry (.council/depth/decisions.jsonl) records regardless of the flag
LLM_COUNCIL_BENCH_MAX_USD (2.00) / _BENCH_MONTHLY_USD (30.00)ADR-048 bench spend caps (per-run graceful abort; month-to-date refusal)
LLM_COUNCIL_SCREENING (off|shadow|active) / _SCREEN_MAX_CHARS (5000) / _SCREEN_MIN_SCORE (9)ADR-047 P3 screening pre-gate (default off; shadow logs only; active short-circuits unanimous passes — never blocking-capable requests)
LLM_COUNCIL_MCP_TASKSADR-045 P1 kill-switch: disable MCP Tasks exposure even on a task-capable SDK (default enabled-when-supported)
LLM_COUNCIL_PROMPT_CACHINGADR-049 D2 kill-switch: Anthropic cache_control breakpoints + OpenRouter session_id on the verify path (default ON — price-class-only; false ⇒ byte-identical payloads)
LLM_COUNCIL_PROMPT_CACHE_TTL (5m|1h)ADR-049 D5: prompt-cache TTL override; verify defaults 1h, interactive 5m; invalid ⇒ path default. NOT LLM_COUNCIL_CACHE_TTL (response cache)
LLM_COUNCIL_FILE_SELECTION (content|allowlist|shadow)ADR-053 Q1 verify file classification; default content since the #557 flip (NUL heuristic + snapshot .gitattributes + linguist + .llmignore). allowlist = pre-flip opt-out
LLM_COUNCIL_REVIEW_SVGADR-053 Q2: review .svg in content mode instead of omitting it as noise (default off)
LLM_COUNCIL_COVERAGE_POLICY (warn|clamp|fail)ADR-053 #556 coverage clamp; default warn (opt-in, byte-identical) — flips to clamp in a later release (#557). clamp ⇒ pass over an unreviewed changed/explicit file → unclear(incomplete_coverage)
LLM_COUNCIL_COVERAGE_ACK_REASONSADR-053 #556: omission reasons the clamp ignores; default binary,generated,vendored,too_large,ignored,noise
LLM_COUNCIL_MODEL_INTELLIGENCE=trueEnable dynamic model selection (ADR-026)
LLM_COUNCIL_OFFLINE=trueForce offline / static provider
LLM_COUNCIL_DISCOVERY_ENABLED / _INTERVAL (300) / _MIN_CANDIDATES (3)Background discovery (ADR-028)
LLM_COUNCIL_PERFORMANCE_TRACKING (true) / _STOREInternal performance index (ADR-026 P3)
LLM_COUNCIL_AUDITION_ENABLED (true) / _MAX_SEATS (1) / _SHADOW_SESSIONS (10) / _EVAL_SESSIONS (50)Audition (ADR-029)
LLM_COUNCIL_METRICS_ENABLED / _BACKEND (none|statsd|prometheus) / LLM_COUNCIL_STATSD_HOST / _PORTMetrics export (ADR-030)
RUBRIC_SCORING_ENABLED / SAFETY_GATE_ENABLED / BIAS_AUDIT_ENABLED / BIAS_PERSISTENCE_ENABLEDEvaluation toggles (ADR-031)
RUBRIC_RANDOMIZE_DIMENSION_ORDER#592: permute rubric criteria order per council call (default off ⇒ byte-identical prompt). Per-call, not per-reviewer — stage 2 shares one prompt; per-reviewer is #602
WILDCARD_ENABLED / PROMPT_OPTIMIZATION_ENABLEDTriage features (ADR-020)

Reasoning effort levels (reasoning/): MINIMAL 10% (quick/creative), LOW 20% (balanced), MEDIUM 50% (high/coding), HIGH 80% (reasoning/math), XHIGH 95% (opt-in). Applied per stage: stage1 on, stage2 off, stage3 on by default.

Performance/bias confidence tiers (sample size): INSUFFICIENT <10, PRELIMINARY 10–30, MODERATE 30–100, HIGH 100+.

Data flow

Query
 → Stage 1: parallel queries → [responses]
 → Stage 1.5 (optional): style normalization
 → Stage 2: anonymize → parallel ranking queries → [evaluations + parsed rankings]
 → Aggregate rankings (Borda)
 → Bias audit (if enabled)
 → Stage 3: chairman synthesis with full context
 → {stage1, stage2, stage3, metadata}

The flow is async/parallel wherever possible to minimize latency.

Gotchas

  1. Keep package-internal imports relative (from .x import …).
  2. Ranking parse failures fall back to permissive Response X regex extraction.
  3. Metadata (label_to_model, aggregate_rankings) is ephemeral — API response only, never written to storage.
  4. Per-session bias metrics are extreme-anomaly indicators, not significance tests (see bias note above).
  5. Reviewer output is untrusted all the way down (#709/#680/#679). A provider can send content: null, so read it as .get("content") or "", never .get("content", ""); the default does not fire for a stored None, and that crashed a live verify after stage 1 had completed. Read a stage-2 entry's parsed ranking with council_rankings.parsed_ranking_of(entry), never .get("parsed_ranking", {}); an AST test fails if the dict-default form comes back. Raw scores go through _normalize_raw_score (coerced like every other score, non-finite dropped, clamped to [0, 1]) because they feed the aggregate's final sort key.

Release Workflow

Branch protection: PRs + passing CI are required. Never push directly to master, even for releases.

  1. git checkout master && git pull origin master
  2. git checkout -b release/v0.X.0
  3. Update CHANGELOG.md (Keep a Changelog: Added / Changed / Fixed / Removed).
  4. git commit --signoff -m "chore(release): Prepare v0.X.0 release" then push the branch.
  5. Open PR: gh pr create --title "Release v0.X.0" --body "…".
  6. Wait for required checks: Test, Lint, Type Check, DCO (DCO needs --signoff). Do not merge until green.
  7. gh pr merge --squash --delete-branch.
  8. After merge, tag from updated master: git tag -a v0.X.0 -m "…" && git push origin v0.X.0 — this triggers publish.yml (build → test wheel → publish to PyPI → announce: auto-creates the GitHub Release with --generate-notes and posts a Discord embed via DISCORD_RELEASES_WEBHOOK secret; both idempotent/soft-fail, #644). Release creation authenticates with the RELEASE_PAT secret (fine-grained PAT, Contents: read+write) so the release: published event triggers release-security.yml (SBOM + SLSA provenance, #646) — default-token releases don't emit workflow triggers; falls back to github.token (release still created, SBOM skipped) when the PAT is unset/expired, so rotate the PAT before it expires.
  9. Verify: gh run list --workflow=publish.yml --limit=1, then pip index versions llm-council-core. The GitHub Release no longer needs manual backfill (announce job creates it).

Versioning: git tags via hatch-vcs/setuptools-scm; src/llm_council/_version.py is auto-generated + gitignored. SemVer (MAJOR breaking / MINOR feature / PATCH fix).

Future enhancement ideas

Streaming responses; conversation export (md/PDF); model performance analytics over time; configurable council/chairman at runtime; custom ranking criteria.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.