# Heimdall - your PR buddy

# The Problem with PR Review: Why We Built Heimdall

Every open-source maintainer knows this rhythm. A pull request opens. Someone asks whether the fix actually fixes anything. Someone else points at a missing test, a missing label, an issue that was never linked. The thread grows. The maintainer repeats the same checklist. And somewhere between the third reminder and the fifth rebase, a bad fix gets merged because nobody had the energy to re-verify it after the last push.

AI coding tools have made this worse, not better. It is cheaper than ever to generate a diff that looks plausible and fails in exactly the way a tired reviewer will not notice. Letting an agent post to GitHub unsupervised is a supply-chain incident waiting to happen.

**Heimdall is built for the gap between "the diff looks fine" and "I am confident enough to comment on it."**

---

## The Origin Story

We didn't set out to build a PR triage tool. We set out to solve our own problem: the maintainer burnout that comes from being the bottleneck on every decision.

The breaking point came when we realized that the "AI revolution" in code review was mostly generating more noise. Tools that auto-comment on PRs without human oversight create a false sense of security. A bot saying "LGTM" on a diff it doesn't actually understand is worse than no review at all.

We wanted something different: **agents that do the grunt work, but humans who keep the authority.**

---

## What We Actually Built

Heimdall runs inside a **Mattermost + Switch AI** room. Three agents — **Huginn** the reproducer, **Loki** the sceptic, and **Heimdall** the desk — test and question every PR. Nothing reaches GitHub until a maintainer approves the exact saved draft text, verified by SHA-256 hash.

The rule that shapes everything: **agents may think, test, and draft; only an approval with a matching hash lets Gjallarhorn write to GitHub.**

---

## The Five Problems We Solved

| Problem | Our Answer |
| --- | --- |
| **"Does this fix actually work?"** | Huginn runs the repo's own test command against the PR head *and* the base commit, then reports paired results. Verdicts rest on saved run data, not vibes. |
| **Reviews that never finish** | Loki scans the changed lines, cites findings by `file:line`, caps at five, and refuses anything that isn't a concrete defect introduced by the diff. |
| **The repeating maintainer checklist** | Intake checks linked issues, assignees, required labels, open-PR limits, CLA, and CI once, in plain code, and posts the result to the triage room. |
| **Unsupervised AI posting to GitHub** | Gjallarhorn — the only writer to GitHub — posts only when an approval row exists whose `draft_hash` matches the exact text being posted. No approval, no comment. No hash match, no comment. |
| **Reproduction you cannot trust** | Huginn's GitHub Actions workflow runs with `contents: read`, no secrets, and the test command passed through `env` — never interpolated into a shell script. |

---

## How a PR Moves Through the System

Every pull request flows through the same stages. Only `triage` changes a PR's state, through one pure transition function: `triage.domain.next_state(...)`.

**1\. Webhook Intake** — GitHub delivers events. Signatures verified, deliveries deduplicated on `X-GitHub-Delivery`.

**2\. Intake — Plain-Code Rule Checks** — Six checks (linked issue, labels, assignee, CLA, CI, open-PR limit) run against the PR head. Results stored per rule per commit.

**3\. Reproduction — Huginn** — Runs the validated test command with and without the fix on GitHub Actions (read-only, no secrets, max 3 attempts). Submits a verdict: `reproduced`, `not_covered`, `setup_failed`, or `inconclusive`.

**4\. Review — Loki** — Reviews the current diff with read-only tools. Up to 5 findings, each cited `file:line`. Tone filter strips guesses about how code was written.

**5\. Desk — Heimdall** — Summarizes intake, reproduction, and review into a Switch card. Renders draft replies to maintainer commands (`/heimdall approve|revise|fix|retry`). Hashes every draft with SHA-256.

**6\. Approval** — Maintainer reacts 👍 to a draft. Approval records the exact draft hash. Mechanical tasks (lint, typo, missing import) use `approver = "policy:auto_suggest"` — still through an approval row, still hash-bound.

**7\. Publish — Gjallarhorn** — Delivers the GitHub comment only while the stored `draft_hash` still matches. If the draft was revised, the hash mismatches and nothing posts. Every approval appends an audit row.

---

## The Three Agents: Specialized, Not General

| Agent | Role | Output |
| --- | --- | --- |
| **Huginn** | Reproducer | Paired test runs + `HuginnVerdict` |
| **Loki** | Sceptic | Up to 5 findings cited `file:line`, or clean pass |
| **Heimdall** | Desk | Switch card, draft replies, mechanical tasks, command parsing |

All three run on the same agentic runtime (`agents/_runtime.py`). The model chooses steps; the runtime enforces tool allow-lists, JSON-schema validation, secret scanning, tone filtering, context budgets, turn/token limits, and a single `submit_*` exit. Agents never import a vendor LLM SDK — the provider is config (`LLM_DEFAULT_*` falling back per agent via `LLM_HUGINN_*`, `LLM_LOKI_*`, `LLM_HEIMDALL_*`), never a code change.

---

## Why Mattermost + Switch AI?

We didn't choose Switch because it's trendy. We chose it because it's the only platform that treats AI agents as **first-class teammates in a chat room you own**.

**What Heimdall implements on Switch:**

1. **Three agents as room participants** — Each registers via the agent protocol (WebSocket), gets its own identity and API key, posts threaded replies, responds to mentions (`@loki review this`).
2. **One thread per PR** — The triage card is the root; intake checklist, Huginn's verdict, Loki's findings, Heimdall's draft all reply in that thread. Context stays in one place.
3. **Built-in auth, authorization, approval cards** — `apps.bridge.setup` handles agent registration, addressing policies (only triage room members can mention agents), Mattermost↔Switch room linkage, and native approval cards for the 👍 flow.
4. **Separation: agents vs. infrastructure** — Agents run as independent processes with their own WebSocket. Worker posts via transactional outbox using agent identities. Bridge (Bifröst) relays reactions back. A compromised agent can't post as another; outbox guarantees idempotent delivery.
5. **Provider-agnostic AI** — Heimdall's agents use an `AiAdapter` (config via `LLM_DEFAULT_*` / `LLM_<AGENT>_*`). Switch ships no models — you bring your own (Claude Code, Codex, OpenCode, any OpenAI-compatible API). Switching models = config change, not code change.
6. **Self-hosted, no vendor lock-in** — Mattermost + Switch run on your infrastructure (Docker Compose, Postgres). No SaaS dependency. You own the conversation history, agent keys, and audit trail.
7. **Proven pattern** — The Switch AI ["Open source: review a contribution" use case](https://docs.switchagents.ai/switch-rooms/use-cases/open-source-contribution) describes this exact pattern. The [Flip the Switch hackathon](https://dev.to/yash_thokal_a1899d36b0351/i-gave-my-github-repo-an-ai-triage-team-that-cant-do-anything-without-my-yes-1h6n) produced "Maintainer Desk" and "Issue Desk" projects implementing the same human-in-the-loop triage pattern.

---

## The Architecture Philosophy: Boring Infrastructure, Sharp Boundaries

We didn't invent new patterns. We composed proven ones:

- **Module borders** — Import only through `api.py`. Never reach into another module's `models.py`.
- **Pure domain** — `domain.py` takes values, returns values. No FastAPI, SQLModel, githubkit, httpx, or adapters.
- **Ports and adapters** — Services depend on Protocols in `ports.py`. Wiring happens in `apps/*/main.py`.
- **One transaction per use case** — Commit everything or nothing.
- **Outbox for side effects** — Never call GitHub or Switch from a service. Write an outbox row; the sender delivers with an idempotency key.
- **Jobs in Postgres** — Procrastinate jobs enqueued inside the same transaction as the state change.
- **State machine owns PR state** — Only `triage` changes `prs.state`, only through `triage.domain.next_state(...)`.
- **Tenancy everywhere** — Every table has `installation_id`. Every query filters on it. No exceptions.

This isn't clever. It's discipline. It means the logic stays testable, the outside world stays replaceable, and the system doesn't surprise you at 2 AM.

---

## Architecture: How the Pieces Fit Together

At a high level, Heimdall is a **state machine wrapped around three agents**, with Postgres as the source of truth and an outbox guarding every external write.

```markdown
flowchart LR
    GH[GitHub PR Events] --> API[Webhook API
    Verify + Persist]
    API --> DB[(Postgres
    Events + Job Queue)]
    DB --> TRIAGE[Triage State Machine
    next_state(...)]
    TRIAGE --> OUT[Transactional Outbox
    Idempotency Keys]
    OUT --> SWITCH[Switch Room
    Thread per PR]
    TRIAGE --> HUGINN[Huginn Reproducer
    GitHub Actions]
    HUGINN --> DB
    TRIAGE --> LOKI[Loki Reviewer
    Read-Only Diff]
    LOKI --> DB
    HUGINN --> DESK[Heimdall Desk
    Card + Draft]
    LOKI --> DESK
    DESK --> OUT
    OUT -->|Approval| APPROVAL[Approval Row
    draft_hash]
    APPROVAL --> GJALLARHORN[Gjallarhorn
    Only GitHub Writer]
    GJALLARHORN --> GH
    DB --> AUDIT[(Audit Log
    Every Decision)]
```

### The Flow in Plain English

**1\. GitHub knocks** — A webhook arrives. The API verifies the signature, deduplicates on `X-GitHub-Delivery`, and writes the event to Postgres in the same transaction that queues triage handling.

**2\. Triage decides** — The state machine (`triage.domain.next_state`) is the only thing that can change a PR's state. It moves `received -> checking` and enqueues Huginn and Loki in parallel. On failure, it moves to `intake_failed`.

**3\. Agents work** — Huginn runs your test command on the PR head and base commit (GitHub Actions, read-only, no secrets). Loki reviews the diff with read-only tools. Both write results back to Postgres.

**4\. Desk assembles** — The Heimdall agent reads the stored results, builds a Switch card, renders a draft, and hashes it with SHA-256. The draft sits in the outbox, waiting.

**5\. Human approves** — You react 👍 in the Switch thread. The Bridge (Bifröst) records an approval row with the exact `draft_hash`.

**6\. Gjallarhorn delivers** — The only component that writes to GitHub. It re-checks the hash matches *at post time*, then posts the exact approved text. If you edited the draft, the hash mismatches and nothing posts.

**7\. Everything audited** — Every approval, auto-suggest, repro dispatch appends an audit row in the same transaction. You can reconstruct any decision.

### Why This Architecture?

| Principle | What It Buys Us |
| --- | --- |
| **State machine owns state** | No surprise transitions; PR state is predictable and testable |
| **Outbox for side effects** | No duplicate GitHub comments; no lost Switch posts; crash-safe |
| **Pure domain, no I/O** | Unit tests run in milliseconds; no mocks needed |
| **Ports + adapters** | Swap GitHub for GitLab, Switch for Slack, Postgres for SQLite in tests |
| **Tenancy everywhere** | Multi-installation from day one; no data leakage |
| **One transaction per use case** | Atomicity by default; no partial states |
| **Agents only** `submit_*` | Runtime enforces tool allow-lists, budgets, tone filters; agents can't go rogue |

This architecture isn't exciting. That's the point. It's boring infrastructure that does one thing well: **guarantee that nothing reaches GitHub without a maintainer's explicit, hash-verified approval.**

---

## Security by Design, Not Bolted On

- **PR content is untrusted data** — Titles, bodies, diffs, comments, test output wrapped as `<pr_data>` data. Never followed as instructions. Never passed to a shell.
- **Only Gjallarhorn writes to GitHub** — Only against an approval row whose hash matches at posting time.
- **Mechanical tasks still go through approval** — `auto_suggest` uses `approver = "policy:auto_suggest"` but still requires a hash-matched approval row.
- **No** `pull_request_target` — Repro workflows get `contents: read` only. Test command via `env`, never shell interpolation.
- **Tokens, keys, diffs never logged** — Only IDs.

---

## The Best Use Case: Hash-Bound PR Triage with Human-in-the-Loop

This is what Heimdall exists for: **end-to-end PR triage where AI does the work but humans keep the authority — enforced cryptographically.**

### The Flow

1. **Intake** (plain code) checks linked issue, labels, assignee, CLA, CI — results posted to the PR thread
2. **Huginn** runs the repo's test command on PR head + base commit on GitHub Actions (read-only, no secrets) → paired verdict
3. **Loki** reviews the diff with read-only tools → up to 5 findings, each cited `file:line`
4. **Heimdall (Desk)** builds a summary card + draft reply, hashes the draft with SHA-256
5. **Maintainer** reacts 👍 to the draft in Switch → approval row recorded with `draft_hash`
6. **Gjallarhorn** (the only GitHub writer) re-checks the hash matches *at posting time* → posts comment

### Why This Works

| Property | How It's Achieved |
| --- | --- |
| **No unsupervised AI writes** | Only Gjallarhorn writes; only with matching `draft_hash` |
| **Maintainer keeps final say** | 👍 on exact draft text; edited draft = hash mismatch = no post |
| **Audit trail** | Every approval, auto-suggest, repro dispatch logged in same transaction |
| **Reproducible verification** | Huginn's paired runs (with/without fix) stored as artifacts |
| **Grounded reviews** | Loki's findings cite `file:line`; tone filter removes speculation |
| **Fits your workflow** | Runs in your Mattermost/Switch, uses your GitHub App, your test command |

### What Makes It Unique

- **Hash-binding at post time, not draft time** — A revised draft can never slip out under an old approval
- **Auto-suggest still goes through approval** — Mechanical fixes require a hash-matched approval row
- **Reproduction is isolated** — GitHub Actions gets `contents: read` only, test command via `env`, no `pull_request_target`
- **Tenancy everywhere** — Every table has `installation_id`; every query filters on it; no cross-repo leakage

This use case — **AI-assisted triage with cryptographic human approval** — is what Heimdall was built for. Everything else (module architecture, outbox, state machine, agent runtime) exists to make this flow reliable, auditable, and secure.

---

## Try It Locally

```bash
# 1. Install and migrate
uv sync
docker compose up -d postgres
uv run alembic upgrade head

# 2. Configure
cp .env.example .env
# Fill in HEIMDALL_GITHUB_APP_ID, HEIMDALL_GITHUB_WEBHOOK_SECRET,
# HEIMDALL_SWITCH_URL, SMEE_URL and the LLM defaults.
# Put the GitHub App private key at secrets/github-app.pem.

# 3. Set up Switch rooms and tokens (safe to re-run)
docker compose up -d
uv run python -m apps.bridge.setup

# 4. Start the full stack
docker compose --profile app --profile tunnel up -d --build
```

Install the GitHub App on a repo with Actions enabled, subscribe to `pull_request`, `workflow_run`, `check_suite`, `installation`, `installation_repositories`, then open a PR and watch its thread appear in the `triage` room.

**Fast tests (no DB, no network):**

```bash
uv run pytest tests/unit
uv run ruff check . && uv run ruff format --check .
uv run pyright
```

---

## The Philosophy

We didn't build Heimdall because we wanted more AI in the loop. We built it because we wanted *less* — less noise, less repetition, less "looks good to me" on code that doesn't work.

The agents do the grunt work: they run the tests, they read the diff, they cite the lines. The maintainer does the one thing only a maintainer can do: **decide**.

If that sounds like the workflow you've been missing, [read the docs](docs/index.md) or [jump straight to the quickstart](README.md#quickstart).

---

*Heimdall — the gatekeeper who never sleeps, and never lets a bad commit through without a witness.*
