Files
deverenz/docs/architecture.md
T

225 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Deverenz architecture
Detailed design reference. CLAUDE.md has the short version; read this when working on the matching module.
## Workflow
Deverenz covers a PR's life in three stages:
1. **Open** — the developer runs `deverenz pr create`. The LLM writes the PR title and description from the local diff and the linked issue, and the PR is opened through the Gitea API. No Gitea UI needed.
2. **Update** — on every push to the PR, the server regenerates the Deverenz part of the PR description so it matches the latest diff.
3. **Merge** — the server posts a delivery summary with a machine-readable record on the ticket (including deviations from the requirements) and links it from the PR. Clean deliveries are closed and moved to Done; otherwise the ticket stays open for a PO decision.
Why, and where this is heading: `vision.md`.
```
Developer machine External services
----------------- -----------------
deverenz pr create -- diff + issue --> LLM (any OpenAI-compatible API)
(developer's token) <-- PrDraft ----
-- POST /pulls --> Gitea / Forgejo
Gitea --webhook--> Deverenz container (the only thing we ship, bot token)
1. verify signature, filter event, respond 200 immediately
2. background job (one at a time per PR)
3. fetch PR, diff, linked issues via Gitea API
4. filter diff (drop lockfiles, generated files, huge files)
5. LLM call -> JSON -> validate (PrDraft or DeliverySummary)
6. synchronized: rewrite marked block in PR body
merged: ticket comment + record, PR link comment, Done gate
```
Deverenz ships as a single container plus a CLI from the same package. The git host and the LLM are always external services reached over HTTP and configured through env vars. We never bundle or run Gitea, Ollama or any model ourselves.
Nothing runs inside the git host except a bot user (with an access token) and a webhook pointing to Deverenz.
## Stage 1: `deverenz pr create`
1. Read the current branch. Take the issue number from the branch name (`feature/12-comment-upsert` → `#12`, see `docs/conventions.md`). `--issue 12` overrides. No issue is allowed: the requirement check is skipped and a "No linked ticket" warning is added.
2. Diff locally with `git diff <base>...HEAD` and run it through `diff_filter`.
3. Fetch the issue (title and body are the requirements).
4. LLM → `PrDraft`.
5. Print a preview and ask for confirmation (`--yes` skips it, `--dry-run` stops here).
6. Push the branch if the remote doesn't have it, then `POST /pulls` with title, body, `base`, `head` and the optional `--reviewer` / `--label` values.
The PR body ends with `Refs #12`, not `Closes #12`. A closing keyword would make Gitea close the issue on every merge, even when the Done gate says it needs a PO decision. Deverenz closes the issue itself when the delivery is clean (see "Done gate").
## Stage 2: PR updated (`synchronized`)
Regenerate the `PrDraft` from the latest diff and replace only the text between the body markers (see "Marked content"). Title and anything the developer wrote outside the markers stay unchanged. On `opened`, do the same only if the body has no Deverenz block yet (for PRs opened in the UI).
## Stage 3: PR merged
1. Fetch PR, final diff and linked issues.
2. LLM → `DeliverySummary`.
3. Run the checks and decide the Done gate (below).
4. Upsert a marked comment with the record block on each linked issue.
5. Upsert a short marked comment on the PR: "Delivery summary posted on #12".
6. Apply the Done gate.
### Done gate
Work flows freely, Done has to be earned.
- **Clean** = a linked ticket, `ticket_quality.level == "clear"`, and no requirement has status `deviates` or `missing`.
- **Clean:** close the issue and move it to the column named `DONE_COLUMN` on every project board it belongs to. If no such column exists, log a warning and skip the move.
- **Not clean:** leave the issue open and where it is. If a requirement deviates or is missing, add `DEVIATION_LABEL` (create the label if the repo doesn't have it). The ticket comment ends with the reason (deviation, vague ticket, …) and: "Not moved to Done: PO decision needed. Close and move to Done to accept, or open a follow-up ticket."
- Human acceptance is just closing and moving the ticket; Gitea's timeline records who did it and when. No extra mechanics in the MVP.
- The record's `done_gate` field is `"auto"` or `"needs_decision"`.
## Checks during work (warn, never block)
- **No linked ticket:** neither the branch name nor `--issue` gives an issue number.
- **Vague ticket:** the issue body is empty or very short (deterministic check, forces `missing`), or the LLM rates it `vague` in the same call (no extra call). The LLM names the concrete gaps, e.g. "no acceptance criteria", "'fast' is not measurable", "unclear which user role".
Ticket quality is shown wherever the content appears: in the PR body, the ticket comment and the record. Anyone reading the ticket, or an LLM asked about it later, can see how much the requirement check can be trusted. A `vague` rating also lowers the confidence of the requirement check: those items are reported as "unclear" rather than "implemented".
Warnings are shown in the `pr create` preview, written into the PR body block (`⚠ No linked ticket`, `⚠ Ticket has no clear acceptance criteria`), and stored in the merge record's `warnings`. They never stop a PR from being created or updated.
### Ticket rules
- **Never edit the issue description.** It is the original requirement, owned by the author/PO. Discrepancies go in the Deverenz comment and the label; the PO decides whether to update the ticket or open a follow-up.
- The board move API takes the **global issue id** (`issue.id` from the API), not the repo-local `#12`.
## Models
```python
class PrDraft(BaseModel): # reviewer-facing
title: str # Conventional Commits style, e.g. "feat(webhook): ..."
summary: str # 2-3 sentences: what and why
changes: list[str]
how_to_test: list[str]
requirement_check: list[str] # only deviating, missing or unclear items; empty if all met
ticket_quality: TicketQuality
warnings: list[str] # filled by code (checks.py); not part of the schema sent to the LLM
class TicketQuality(BaseModel):
level: Literal["clear", "vague", "missing"]
gaps: list[str] # what is unclear, e.g. "no acceptance criteria"
class RequirementItem(BaseModel):
requirement: str
status: Literal["implemented", "deviates", "missing", "unclear"]
note: str
class DeliverySummary(BaseModel): # PM-facing, posted on the ticket
user_impact: str # what changes for end users, plain language
delivered: list[str]
requirements: list[RequirementItem]
risks: list[str]
open_points: list[str]
ticket_quality: TicketQuality
```
Ask the LLM for JSON matching the schema and validate with `model_validate_json`. On failure, retry once with the validation error in the prompt. This must work with small models too, so don't rely on provider-specific structured-output features.
**Length:** comfortable for a reviewer: about 150–300 words when rendered, bullets over prose, at most about 5 bullets per section. `--short` / `--detailed` come later.
## Marked content
- **PR body:** the generated part sits between `<!-- deverenz:start -->` and `<!-- deverenz:end -->`. Only that block is ever rewritten.
- **Comments:** every Deverenz comment starts with `<!-- deverenz -->`. Before posting, list comments, find the one with the marker authored by the bot user, and edit it. Create a new one only if none exists.
- **Visible label:** every generated block and comment ends with a short line like "_Generated by Deverenz from the diff and #12. Check before relying on it._" Generated content never passes as human-written.
### Record block
Each ticket merge comment ends with a hidden, machine-readable record so the project history can be queried by any LLM or script:
```
<!-- deverenz:record v1
{"issue": 12, "pr": 34, "merged_at": "2026-11-20T14:03:00Z",
"model": "<LLM_MODEL>", "done_gate": "needs_decision", "warnings": [],
"summary": { ...DeliverySummary.model_dump() ... }}
-->
```
Bump the version on breaking changes and keep a reader for older versions. The Markdown above the block is for people; the block is the stable contract.
## Components
| Module | Responsibility |
|---|---|
| `config.py` | `Settings` class (pydantic-settings), fails fast on missing env vars |
| `main.py` | FastAPI app, `POST /webhook/gitea`, `GET /health` |
| `webhook.py` | HMAC signature verification, event/action filtering |
| `gitea.py` | Async Gitea client with only the endpoints we need |
| `board.py` | Find the issue's projects, resolve the Done column, move the issue |
| `git_local.py` | Current branch, issue number from branch name, local diff, push |
| `checks.py` | Ticket checks (no ticket, vague ticket) and the Done gate decision. Pure functions, no I/O |
| `diff_filter.py` | Split unified diff into files, drop noise, truncate to a size limit |
| `summarize.py` | Prompts, LLM call, JSON validation with one retry |
| `render.py` | `PrDraft` / `DeliverySummary` → Markdown with markers |
| `cli.py` | `deverenz pr create`, `deverenz merged owner/repo <pr>`, `deverenz register owner/repo` |
Keep the Gitea client behind a small `Forge` protocol so a GitLab adapter can be added later. Do not build a larger plugin framework yet.
## Configuration (env vars)
| Variable | Purpose |
|---|---|
| `GITEA_URL` | Base URL of the external Gitea/Forgejo instance |
| `GITEA_TOKEN` | Server: bot user token. CLI: the developer's own token, so they are the PR author |
| `WEBHOOK_SECRET` | Shared secret for signature verification (server only) |
| `LLM_BASE_URL` | OpenAI-compatible endpoint (default `https://api.openai.com/v1`; any compatible provider or self-hosted server works) |
| `LLM_API_KEY` | API key for that endpoint, supplied by the operator or developer |
| `LLM_MODEL` | Model name |
| `LANGUAGE` | Output language (default `en`) |
| `DONE_COLUMN` | Project board column for clean merged tickets (default `Done`) |
| `DEVIATION_LABEL` | Label added when a requirement deviates or is missing (default `scope-deviation`) |
The CLI reads the same variables from the environment or `~/.config/deverenz/.env`.
## Gitea API endpoints used
Verified on the dev instance (API 28.3.0). Re-check details against `/api/swagger` of the running instance.
PRs and comments:
- `POST /repos/{owner}/{repo}/pulls` (title, body, head, base, labels, reviewers, …)
- `GET /repos/{owner}/{repo}/pulls/{index}`
- `PATCH /repos/{owner}/{repo}/pulls/{index}` (rewrite body block)
- `GET /repos/{owner}/{repo}/pulls/{index}.diff`
- `GET /repos/{owner}/{repo}/issues/{index}`
- `PATCH /repos/{owner}/{repo}/issues/{index}` with `{"state": "closed"}` (Done gate, clean only)
- `GET /repos/{owner}/{repo}/issues/{index}/comments`
- `POST /repos/{owner}/{repo}/issues/{index}/comments`
- `PATCH /repos/{owner}/{repo}/issues/comments/{id}`
Labels:
- `GET /repos/{owner}/{repo}/labels`, `POST /repos/{owner}/{repo}/labels`
- `POST /repos/{owner}/{repo}/issues/{index}/labels`
Project boards:
- `GET /repos/{owner}/{repo}/projects` (also `/orgs/{org}/projects` for org boards)
- `GET /repos/{owner}/{repo}/projects/{id}/columns`
- `GET /repos/{owner}/{repo}/projects/{id}/columns/{column_id}/issues`
- `POST /repos/{owner}/{repo}/projects/{id}/issues/{issue_id}/move` with `{"column_id": …}` (global issue id)
Setup:
- `POST /repos/{owner}/{repo}/hooks` (for `deverenz register`)
PRs are issues in Gitea, so PR comments go through the issues endpoints.
## Webhook handling
- Event header: `X-Gitea-Event: pull_request`
- Signature header: `X-Gitea-Signature` = hex HMAC-SHA256 of the **raw request body** with `WEBHOOK_SECRET`. Read the raw body before parsing JSON. Compare with `hmac.compare_digest`.
- Relevant actions: `opened` (only without a Deverenz block), `synchronized`, and `closed` with `pull_request.merged == true`. Ignore the rest. Confirm action names against real payloads.
- Respond 200 immediately, process in the background (FastAPI `BackgroundTasks` for the MVP).
- Use an `asyncio.Lock` per PR so rapid pushes don't trigger parallel LLM calls. Jobs lost on restart are acceptable for the MVP.
## Deployment and local development
- One Python package, two entry points: the CLI (installed on developer machines with `uv tool install`) and the server (the Docker image).
- The Docker image contains only Deverenz. `docker-compose.yml` defines just the `deverenz` service, reads `.env` and exposes the webhook port.
- Gitea (or another git host) and the LLM provider are external. Point `GITEA_URL` and `LLM_BASE_URL` at them.
- For development, use a test repo on an existing Gitea instance and the CLI's `--dry-run` flags.
Gotcha: Gitea blocks webhooks to private/internal addresses by default. If Deverenz runs on a private network, the Gitea admin must add its host to `[webhook] ALLOWED_HOST_LIST` in Gitea's config, otherwise no events arrive.
## Licensing
- Core is **Apache-2.0**.
- External contributions require a **CLA** so the project can offer commercial licenses later.
- Future commercial features go into a separate `ee/` directory under a proprietary license (open-core model).
- "Deverenz" is intended to be protected as a trademark; forks may use the code but not the name.