From 95e1b9cb89a521edbf78b943ab9b79e333c73191 Mon Sep 17 00:00:00 2001 From: kasun Date: Sun, 15 Nov 2026 14:36:06 +0100 Subject: [PATCH] chore: add project docs and agent workflow setup --- .claude/hooks/check-on-stop.sh | 29 +++++ .claude/hooks/ruff-format.sh | 10 ++ .claude/scripts/gitea.sh | 45 +++++++ .claude/settings.json | 68 ++++++++++ .env.example | 18 +++ .githooks/commit-msg | 20 +++ .gitignore | 27 ++++ CLAUDE.md | 73 +++++++++++ README.md | 115 ++++++++++++++++- docs/agentic-workflow.md | 91 ++++++++++++++ docs/architecture.md | 224 +++++++++++++++++++++++++++++++++ docs/conventions.md | 62 +++++++++ docs/devlog.md | 18 +++ docs/roadmap.md | 34 +++++ docs/vision.md | 61 +++++++++ 15 files changed, 894 insertions(+), 1 deletion(-) create mode 100755 .claude/hooks/check-on-stop.sh create mode 100755 .claude/hooks/ruff-format.sh create mode 100755 .claude/scripts/gitea.sh create mode 100644 .claude/settings.json create mode 100644 .env.example create mode 100755 .githooks/commit-msg create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 docs/agentic-workflow.md create mode 100644 docs/architecture.md create mode 100644 docs/conventions.md create mode 100644 docs/devlog.md create mode 100644 docs/roadmap.md create mode 100644 docs/vision.md diff --git a/.claude/hooks/check-on-stop.sh b/.claude/hooks/check-on-stop.sh new file mode 100755 index 0000000..4e6ce9e --- /dev/null +++ b/.claude/hooks/check-on-stop.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Stop hook: block "done" while ruff or tests fail on changed Python code. +input=$(cat) +[[ "$(jq -r '.stop_hook_active // false' <<<"$input")" == "true" ]] && exit 0 +cd "$CLAUDE_PROJECT_DIR" || exit 0 +[[ -f pyproject.toml ]] || exit 0 +command -v uv >/dev/null || exit 0 +# -uall lists files inside new folders (e.g. a fresh src/), not just the folder. +git status --porcelain -uall | grep -q '\.py$' || exit 0 + +if ! out=$(uv run --quiet ruff check . 2>&1); then + echo "ruff check failed, fix before finishing:" >&2 + tail -n 30 <<<"$out" >&2 + exit 2 +fi +if grep -q pyright pyproject.toml && ! out=$(uv run --quiet pyright 2>&1); then + echo "pyright failed, fix before finishing:" >&2 + tail -n 30 <<<"$out" >&2 + exit 2 +fi +out=$(uv run --quiet pytest -q -x 2>&1) +status=$? +# 0 = passed, 5 = no tests collected yet; neither should block. +if [[ $status -ne 0 && $status -ne 5 ]]; then + echo "pytest failed, fix before finishing:" >&2 + tail -n 40 <<<"$out" >&2 + exit 2 +fi +exit 0 diff --git a/.claude/hooks/ruff-format.sh b/.claude/hooks/ruff-format.sh new file mode 100755 index 0000000..ac7e592 --- /dev/null +++ b/.claude/hooks/ruff-format.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PostToolUse hook: format and lint-fix a Python file after Claude edits it. +file=$(jq -r '.tool_input.file_path // empty') +[[ "$file" == *.py && -f "$file" ]] || exit 0 +command -v uv >/dev/null || exit 0 +cd "$CLAUDE_PROJECT_DIR" || exit 0 +[[ -f pyproject.toml ]] || exit 0 +uv run --quiet ruff format "$file" >/dev/null 2>&1 +uv run --quiet ruff check --fix "$file" >/dev/null 2>&1 +exit 0 diff --git a/.claude/scripts/gitea.sh b/.claude/scripts/gitea.sh new file mode 100755 index 0000000..aa31989 --- /dev/null +++ b/.claude/scripts/gitea.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Gitea API helper for managing this project (issues, labels, milestones, board, PRs). +# Not part of the Deverenz product. +# +# Usage: gitea.sh METHOD PATH [BODY] +# METHOD GET | POST | PATCH | PUT | DELETE +# PATH path below /api/v1, e.g. /repos///issues?state=open +# BODY JSON string, or @file to send a file +# +# Config (outside the repo, never committed): +# ${XDG_CONFIG_HOME:-~/.config}/deverenz-agent/url e.g. http://gitea.local:3000 +# ${XDG_CONFIG_HOME:-~/.config}/deverenz-agent/token agent account token, chmod 600 +set -euo pipefail + +method=${1:?usage: gitea.sh METHOD PATH [BODY]} +path=${2:?usage: gitea.sh METHOD PATH [BODY]} +body=${3:-} + +case "$method" in + GET | POST | PATCH | PUT | DELETE) ;; + *) echo "unsupported method: $method" >&2; exit 2 ;; +esac + +config=${XDG_CONFIG_HOME:-$HOME/.config}/deverenz-agent +for f in url token; do + [[ -s "$config/$f" ]] || { echo "missing $config/$f (see CLAUDE.local.md)" >&2; exit 2; } +done +url=$(<"$config/url") +token=$(<"$config/token") + +args=(-sS --fail-with-body -X "$method" -H "Accept: application/json") +# The token header is read from stdin so it never shows up in the process list. +args+=(-H @-) +if [[ -n "$body" ]]; then + [[ "$body" == "@-" ]] && { echo "BODY from stdin is not supported, use @file" >&2; exit 2; } + args+=(-H "Content-Type: application/json" --data-binary "$body") +fi + +out=$(curl "${args[@]}" "${url%/}/api/v1${path}" <<<"Authorization: token $token") \ + || { echo "$out" >&2; exit 1; } +if command -v jq >/dev/null && [[ -n "$out" ]]; then + jq . <<<"$out" 2>/dev/null || echo "$out" +else + echo "$out" +fi diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..e9e0777 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,68 @@ +{ + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "attribution": { + "commit": "", + "pr": "" + }, + "permissions": { + "allow": [ + "Bash(uv sync:*)", + "Bash(uv add:*)", + "Bash(uv run pytest:*)", + "Bash(uv run ruff:*)", + "Bash(git status:*)", + "Bash(git diff:*)", + "Bash(git log:*)", + "Bash(git show:*)", + "Bash(git add:*)", + "Bash(docker compose ps:*)", + "Bash(docker compose logs:*)", + "Bash(docker compose up:*)", + "Bash(docker compose down)", + "Bash(curl http://localhost:*)" + ], + "ask": [ + "Bash(uv run deverenz:*)", + "Bash(git commit:*)", + "Bash(git push:*)", + "Bash(docker compose down -v:*)", + "Bash(.claude/scripts/gitea.sh POST:*)", + "Bash(.claude/scripts/gitea.sh PATCH:*)", + "Bash(.claude/scripts/gitea.sh PUT:*)", + "Bash(.claude/scripts/gitea.sh DELETE:*)" + ], + "deny": [ + "Read(./.env)", + "Read(./.env.local)", + "Read(./.env.production)", + "Bash(cat .env:*)", + "Read(~/.config/deverenz-agent/**)", + "Bash(cat ~/.config/deverenz-agent:*)", + "Bash(rm -rf:*)" + ] + }, + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/ruff-format.sh" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-on-stop.sh", + "timeout": 300 + } + ] + } + ] + } +} diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e3c9e88 --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# Copy to .env and fill in. Never commit .env. + +# External git host (Gitea / Forgejo) +GITEA_URL=https://git.example.com +# Server: bot user token. CLI: your own token, so you are the PR author. +GITEA_TOKEN=changeme +WEBHOOK_SECRET=changeme + +# Any OpenAI-compatible API. Defaults to OpenAI; change the URL for other providers. +LLM_BASE_URL=https://api.openai.com/v1 +LLM_API_KEY=changeme +LLM_MODEL=changeme + +LANGUAGE=en + +# Project board column for merged tickets, and label for tickets with deviations +DONE_COLUMN=Done +DEVIATION_LABEL=scope-deviation diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..71123f2 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Enforce docs/conventions.md on every commit message. +msg_file="$1" +first_line=$(grep -v '^#' "$msg_file" | head -n1) + +# Let git's own merge/revert/fixup messages through. +[[ "$first_line" =~ ^(Merge|Revert|fixup!|squash!) ]] && exit 0 + +pattern='^(feat|fix|refactor|chore|docs|test|style)(\([a-z0-9-]+\))?: [a-z].*[^.]$' +if ! [[ "$first_line" =~ $pattern ]]; then + echo "commit-msg: '$first_line'" >&2 + echo " expected '(): ', lowercase start, no trailing period" >&2 + echo " types: feat fix refactor chore docs test style (see docs/conventions.md)" >&2 + exit 1 +fi + +if grep -qiE '^(Co-Authored-By:.*(claude|anthropic)|.*Generated with \[?Claude)' "$msg_file"; then + echo "commit-msg: no AI attribution lines (see docs/conventions.md)" >&2 + exit 1 +fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb57533 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Python / uv +__pycache__/ +*.py[cod] +.venv/ +build/ +dist/ +*.egg-info/ +.pytest_cache/ +.ruff_cache/ +.coverage +htmlcov/ + +# Secrets +.env +.env.* +!.env.example + +# Claude Code personal overrides +.claude/settings.local.json +CLAUDE.local.md + +# Prompt evaluation output +out/ + +# Editors +.vscode/ +.idea/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..85d30f9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,73 @@ +# Deverenz + +Self-hosted, platform-independent suite of project management measures with opinionated defaults, powered by any OpenAI-compatible LLM. The MVP covers a PR's life cycle. The key output: what the ticket asked for vs. what the PR actually does, recorded on the ticket. + +1. **Open:** `deverenz pr create` (CLI, developer's own token) writes title and description from the local diff and the linked issue, then opens the PR via the Gitea API. +2. **Update:** on each push, the server rewrites the Deverenz block in the PR description. +3. **Merge:** the server posts a delivery summary with a machine-readable record on the ticket (implemented / deviates / missing / unclear, plus ticket quality) and links it from the PR. It closes the ticket and moves it to Done if the delivery is clean, otherwise leaves it open for a PO decision. + +Deverenz ships as a CLI plus a single container. The git host and the LLM are external services reached over HTTP. Never bundle Gitea, Ollama or a model. + +MVP: Gitea only (Forgejo should work unchanged), issue number taken from the branch name, config via env vars only. No database, no web UI, no other forges yet. + +## Where to look + +- `docs/architecture.md`: the three stages in detail, Done gate, ticket checks, models, marked content and record block, modules, env vars, Gitea endpoints (incl. project boards), webhook rules, deployment, licensing. Read the relevant section before changing a module. +- `docs/vision.md`: why the product exists, agile stance, principles, future ideas. Not for implementation detail. +- `docs/roadmap.md`: milestone overview with links to the issues. Task status lives on the Gitea board, not in this file. +- `docs/conventions.md`: branch names, commit messages, issue titles. Follow it for every branch and commit. +- `docs/agentic-workflow.md`: how the project is managed and worked: tickets and board on Gitea, pipeline per ticket, verification rules, review checklist, current autonomy phase. Follow it for every ticket; change it only with the developer's OK. +- `docs/devlog.md`: one entry per finished ticket (time, cost, agent mistakes and what caught them). Draft the entry when a step is done. + +## Stack + +Python 3.12+ with `uv` · FastAPI + uvicorn · async `httpx` · Pydantic + `pydantic-settings` · `openai` SDK with configurable `base_url` · `pytest` + `respx` · `ruff` · `pyright` (strict) · Gitea Actions for CI · Docker image with only Deverenz in it. + +## Commands + +```bash +git config core.hooksPath .githooks # once after cloning: enforces commit conventions +uv sync +uv run pytest +uv run ruff check --fix . && uv run ruff format . +uv run pyright +.claude/scripts/gitea.sh GET '/repos///issues?state=open' # project management API +uv run deverenz pr create --dry-run # preview generated PR title/body +uv run deverenz merged owner/repo 1 --dry-run # preview merge report +docker compose up -d # deverenz only; reads .env +docker compose logs -f deverenz +``` + +## Project structure + +``` +src/deverenz/ config.py main.py webhook.py gitea.py board.py git_local.py + checks.py diff_filter.py summarize.py render.py cli.py +tests/fixtures/ stored Gitea webhook payloads and API responses +docs/ architecture.md, vision.md, roadmap.md, conventions.md, + agentic-workflow.md, devlog.md +``` + +## Conventions + +- Async throughout (`httpx.AsyncClient`, async FastAPI handlers). +- Type hints everywhere; Pydantic models only for fields we actually use, not the full Gitea API. +- Keep it small. Gitea client sits behind a small `Forge` protocol; no plugin framework, no abstractions for platforms we don't support yet. +- Never log tokens, secrets or full diffs. +- Work flows freely, Done has to be earned: warn during work, never block it; only clean deliveries move to Done automatically, everything else needs a visible human decision. +- Never edit an issue description. In PR bodies, only touch text between the `` markers. +- Generated text is reviewer-friendly: about 150–300 words, bullets over prose. +- Cost control: one LLM call per relevant event, never on every webhook. +- LLM output must work with small local models: plain JSON + `model_validate_json` + one retry, no provider-specific structured output. +- Verify Gitea API details against `/api/swagger` of the running instance and real payloads, not memory. + +## Workflow rules + +- Work on one ticket at a time. Plan first when a change touches more than one module. +- Managing this project on Gitea (tickets, board, PRs) is separate from the Deverenz product: never run Deverenz against its own repo. Draft tickets for approval before creating them. +- Before calling a task done: `uv run pytest`, `uv run ruff check .` and `uv run pyright` pass. +- The developer knows Java/TypeScript, not Python: explain Python constructs only where they differ, mapped to their Java/TypeScript counterparts. +- Never read, print or commit `.env`. Use `.env.example` for documenting variables. +- Prefer small commits, one per finished ticket. Ask before committing, pushing, opening a PR and merging. +- No Claude attribution (Co-Authored-By, "Generated with Claude Code") in commit messages or PR descriptions. +- Remote is a self-hosted Gitea (not GitHub): `gh` does not work here. Use `.claude/scripts/gitea.sh` for issues, labels, milestones, the board and PRs. diff --git a/README.md b/README.md index 98d5c86..c59970f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,115 @@ -# deverenz +# Deverenz +**Project management that runs itself, on your own git platform.** + +Deverenz is a self-hosted suite of project management measures with opinionated defaults. It connects your git platform, your tickets and any OpenAI-compatible LLM, so that every pull request is described, checked against its ticket, and recorded, without anyone having to organize it. + +> **Status: early design phase.** This is still more of a plan than working software. The concept is in place, implementation is just starting, and nothing is installable yet. The steps described below show the intended design; details are still being worked out and may change. The first version (MVP) is being built for Gitea and Forgejo; other platforms, starting with GitLab, are planned. See the [roadmap](docs/roadmap.md). + +## Why + +Good project management is expensive. It takes time, skill and people that a team doesn't always have, even in large companies, and then it ends up done badly or not at all. Git platforms already offer the building blocks (webhooks, boards, labels, milestones, APIs), but someone has to assemble them into a working process. + +Agile teams have a specific version of this problem. Preferring conversation over documentation is right, but in practice it often means: +- tickets aren't kept up to date +- decisions are made face to face and never written down +- developers lose track of what the actual target is +- stakeholders and clients get inconsistent, ad-hoc updates + +Deverenz automates the lightweight documentation agile tends to skip, and makes the gap between what was asked and what was built visible. + +## How it works + +This is the planned design; the details are still in progress. The first version covers the life of a pull request in three stages: + +1. **Open.** The developer runs `deverenz pr create`. Deverenz reads the local diff and the linked ticket (taken from the branch name, e.g. `feature/12-csv-export` → `#12`), lets the LLM write the PR title and description, and opens the PR through the platform's API. +2. **Update.** On every push, Deverenz refreshes its section of the PR description so it matches the latest code. Anything the developer wrote outside that section stays untouched. +3. **Merge.** Deverenz posts a delivery summary on the ticket. It lists each requirement as *implemented*, *deviates*, *missing* or *unclear*, and rates how clear the ticket itself was. + +### Done has to be earned + +Deverenz never blocks developers while they work. Missing tickets or vague requirements show up as warnings, not errors. The strictness sits at the end: + +- **Clean delivery** (linked ticket, clear requirements, everything implemented): the ticket is closed and moved to *Done* automatically. +- **Anything else:** the ticket stays open, and the summary says why. If a requirement deviates or is missing, the ticket gets a `scope-deviation` label. A person, usually the product owner, decides whether to accept the result or open a follow-up ticket. That decision is visible in the ticket's history instead of lost in a meeting. + +This maps onto Scrum's three pillars: **transparency** (every delivery is recorded), **inspection** (each PR is checked against its ticket) and **adaptation** (deviations require an explicit decision). + +### A queryable project history + +Every delivery summary contains a hidden, versioned, machine-readable record alongside the human-readable text. Over time, the tickets become a structured project history that anyone can query with their own tools or LLM, for example "what shipped this sprint, and where did we deviate?". + +## Principles + +- **Self-hosted, bring your own LLM.** Works with OpenAI or any OpenAI-compatible endpoint, including self-hosted models. Code never has to leave the company. +- **Opinionated defaults.** It works out of the box with a sensible process. +- **Work flows freely, Done has to be earned.** Warn during work, decide at Done. +- **Generated content is always marked** as generated. +- **Human-written requirements are never rewritten.** Deverenz comments; it doesn't edit ticket descriptions. +- **Cheap and predictable.** One LLM call per event. + +## Planned setup + +Deverenz will ship as one Python package with two parts: + +- **A CLI** that developers install locally. It opens PRs with their own access token, so they stay the PR author. +- **A single Docker container** that receives webhooks from the git platform and handles updates and merges with a bot account. + +The git platform and the LLM are external services. Deverenz doesn't bundle either. Configuration is done through environment variables; see [`.env.example`](.env.example). + +The platform connection sits behind a small interface. The MVP implements it for Gitea and Forgejo; GitLab is the next platform planned. + +## Documentation + +| Document | Contents | +|---|---| +| [docs/vision.md](docs/vision.md) | Why the project exists, agile stance, principles, future ideas | +| [docs/architecture.md](docs/architecture.md) | Technical design: stages, Done gate, data models, platform API, configuration | +| [docs/roadmap.md](docs/roadmap.md) | What's being built, in which order, and current progress | +| [docs/conventions.md](docs/conventions.md) | Branch names, commit messages, ticket titles | + +## Development + +Requirements: Python 3.12+, [uv](https://docs.astral.sh/uv/), git, Docker (for the container). + +```bash +git clone && cd deverenz +git config core.hooksPath .githooks # once: enforces the commit conventions +cp .env.example .env # fill in your git platform and LLM settings +uv sync +uv run pytest +``` + +Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) as described in [docs/conventions.md](docs/conventions.md); the commit hook checks this automatically. + +## Built with agentic coding + +Deverenz is developed with an AI coding agent ([Claude Code](https://claude.com/claude-code)) working alongside a human developer. The split of responsibilities: + +- **The human decides:** product direction, architecture choices, what gets built next, and what gets committed. Every commit is reviewed and approved by a person. +- **The agent proposes and executes:** it drafts plans and documentation, challenges design decisions, writes code and tests, and runs checks. + +The project is built spec-first: the design in [`docs/`](docs/) is written before the code, so the agent always works from the same documented context. The workflow per roadmap step: + +1. Plan the step with clear acceptance criteria, and review the plan before any code is written. +2. Implement it together with tests. +3. Review the diff, commit on a feature branch, update the roadmap. + +Guardrails in the repository keep this safe and consistent: + +| File | Purpose | +|---|---| +| `CLAUDE.md` | Project context and working rules the agent loads in every session | +| `.claude/settings.json` | Permissions: what the agent may run freely, what needs approval (commits, pushes, real runs), what is blocked (secrets) | +| `.claude/hooks/` | Formatting after every edit, and tests and lint before a task counts as done | +| `.githooks/commit-msg` | Enforces the commit conventions for humans and the agent alike | + +This is also a deliberate experiment in how far agentic coding can carry a real project, and the approach will be adjusted as experience grows. + +## License + +The core of Deverenz is licensed under [Apache-2.0](LICENSE). + +- External contributions require a Contributor License Agreement (CLA), so the project can offer commercial licenses later. +- Future commercial features will live in a separate `ee/` directory under a proprietary license. +- "Deverenz" is intended as a protected name: forks may use the code, but not the name. diff --git a/docs/agentic-workflow.md b/docs/agentic-workflow.md new file mode 100644 index 0000000..d0fa1ab --- /dev/null +++ b/docs/agentic-workflow.md @@ -0,0 +1,91 @@ +# Agentic Workflow + +> **Status: draft.** This is the approach currently being tried. Change it only with the developer's OK, and record why in the [dev log](devlog.md). + +**Current autonomy phase: 1 (interactive)** + +## Premise + +The developer is experienced in Java and TypeScript but new to Python. The agent writes most of the code. The human owns the requirements, the design, the verification and the merge decision. Python-specific knowledge goes into tooling (types, lint, tests, agent review) instead of being learned line by line. + +## Roles + +- **Human:** discusses and approves tickets, approves the plan, reviews, runs the result, approves every commit, push and merge. +- **Agent:** drafts tickets from discussions, creates them and moves them on the board, plans, writes tests and code, runs the checks, reviews its own diff, drafts the dev log entry. + +## Project management on Gitea + +This section is about how the project itself is managed. It has nothing to do with what Deverenz does as a product: Deverenz is never run against its own repo, and real runs go only to the sandbox repo. + +- **Source of truth:** issues and the project board in the project's Gitea repo. [roadmap.md](roadmap.md) is only the milestone overview and links to the issues. +- **Access:** the agent uses its own Gitea account (not the Deverenz bot) through `.claude/scripts/gitea.sh`. Read calls run freely; every write asks for approval. Repo, URL and token location are in `CLAUDE.local.md`. +- **Board columns:** Backlog / Todo / In progress / In review / Done. +- **Labels and milestones** are set up in the first planning session and live in Gitea, not in this file. + +### From discussion to tickets + +1. The human and the agent discuss a step, feature, bug or idea. +2. The agent drafts the resulting tickets: title (format in [conventions](conventions.md)), acceptance criteria, labels, milestone and column. +3. The human approves or corrects the drafts. +4. The agent creates them in one batch and links them from `roadmap.md` where they belong to a step. + +A discussion may produce several tickets, backlog items, bugs or a new project; the agent proposes all of them in the same draft. Bugs or ideas found during coding that are outside the current ticket's scope become a new draft ticket, not part of the current change. + +### Ticket status + +| Event | Column | +|---|---| +| Ticket created, not planned yet | Backlog | +| Ticket planned for the near future | Todo | +| Branch created, work started | In progress | +| PR opened | In review | +| PR merged after the human's OK | Done (and the issue is closed) | + +The agent makes these moves. Moving back (e.g. In review → In progress after review feedback) is fine too. + +## Pipeline per ticket + +1. **Ticket** with acceptance criteria, created as described above. +2. **Branch** `/-`; move the ticket to In progress. +3. **Plan** in plan mode: approach, files touched, one or more tests per acceptance criterion, Python-specific risks. The human approves before any code is written. +4. **Tests first**, then the implementation. +5. **Automated checks:** `ruff check`, `pyright` (strict) and `pytest`. Locally through the Stop hook, on every PR through CI. +6. **Agent review:** `/code-review` on the diff, including a pass for Python and async pitfalls (blocking calls in async code, mutable defaults, unclosed clients, broad `except`). +7. **Commit, push and PR** after the human's OK. The PR body ends with `Closes #`. Move the ticket to In review. +8. **Human review** with the checklist below, and a real run (`--dry-run` or the sandbox repo). +9. **Merge** after the human's OK, move the ticket to Done, add a dev log entry. + +## Verification rules + +- Tests are the spec: every acceptance criterion has at least one test, including failure cases. +- Don't silence a check to make it pass (`# type: ignore`, `# noqa`, skipped tests) without an inline reason and the human's OK. +- CI must be green before merging. + +## Human review checklist + +- Do the tests cover the acceptance criteria, including failures? +- Does the design follow `architecture.md` (module boundaries, `Forge` protocol, marked content)? +- Are errors handled: timeouts, API errors, invalid LLM output? +- Is it free of logged tokens, secrets and full diffs? +- Does a real run produce the expected output? +- Anything surprising? Ask the agent to explain it. + +## Explanations + +The agent explains Python constructs only where they differ from Java/TypeScript, and does so by mapping them to their Java/TypeScript counterparts (e.g. asyncio vs. promises, Pydantic vs. Zod, pytest fixtures vs. JUnit setup). + +## Autonomy phases + +Autonomy goes up only once the checks have shown they catch the agent's mistakes. + +| Phase | How work runs | Move on when | +|---|---|---| +| **1. Interactive** | One session at a time, human approves plan and every commit | CI runs on every PR, at least 3 tickets were done this way, and the dev log shows checks catching real mistakes | +| **2. Parallel** | Two sessions in separate git worktrees on independent tickets; agent review before human review | Two parallel tickets merged without conflicts or regressions | +| **3. Headless** | `claude -p` takes a ticket, works on a branch until the checks pass and opens a PR; human reviews and merges | (open) | + +The same permissions apply in every phase: nothing is pushed to `main`, and real runs only go against the sandbox repo. + +## Metrics + +Recorded in the [dev log](devlog.md) for each ticket: time, cost, agent mistakes and what caught them (test, types, lint, agent review, human review, real run), number of rework rounds, and one thing learned. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..276eea4 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,224 @@ +# 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 ...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 `` and ``. Only that block is ever rewritten. +- **Comments:** every Deverenz comment starts with ``. 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: + +``` + +``` + +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 `, `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. diff --git a/docs/conventions.md b/docs/conventions.md new file mode 100644 index 0000000..ac82bdf --- /dev/null +++ b/docs/conventions.md @@ -0,0 +1,62 @@ +# Git Conventions + +## Branch Naming + +``` +/ +``` + +- All lowercase, hyphens only — no camelCase or Title-Case +- Keep the description short (3–5 words); the branch name is not the place for detail +- If the branch belongs to an issue, include its number right after the type: `feature/12-comment-upsert`. Deverenz reads the ticket from this number. + +| Type | Use for | +|---|---| +| `feature/` | New functionality | +| `fix/` | Bug fixes | +| `refactor/` | Code changes with no behavior change | +| `chore/` | Tooling, deps, config, cleanup | +| `docs/` | Documentation only | + +**Example:** `feature/webhook-server` + +--- + +## Commit Messages + +Follow [Conventional Commits](https://www.conventionalcommits.org/): + +``` +(): + + +``` + +- **Type** — `feat`, `fix`, `refactor`, `chore`, `docs`, `test`, `style` (`feat` is the commit type for `feature/` branches) +- **Scope** — the module touched (e.g. `webhook`, `gitea`, `diff`, `summarize`, `render`, `cli`, `config`, `docker`). Leave it out for changes across the whole repo. +- **Summary** — imperative mood ("add", not "added" or "adds"); no period at the end +- **Body** — only when the reasoning isn't obvious from the diff (a constraint, a bug workaround, a decision). Skip it for simple/self-explanatory changes. +- No AI attribution lines (`Co-Authored-By`, "Generated with …"). + +**Examples:** +``` +feat(summarize): retry once with validation error on invalid JSON +fix(webhook): verify signature against raw body before parsing +style: reformat +refactor(gitea): move comment lookup behind Forge protocol +``` + +--- + +## Ticket Titles + +Frame as the outcome, not a task log: + +``` +: +``` + +**Examples:** +- `Feature: Post PR summary as a single updatable comment` +- `Bug: Webhook ignored when PR is reopened` +- `Chore: Drop lockfiles from diff before LLM call` diff --git a/docs/devlog.md b/docs/devlog.md new file mode 100644 index 0000000..5f94110 --- /dev/null +++ b/docs/devlog.md @@ -0,0 +1,18 @@ +# Dev Log + +One entry per finished roadmap step, newest first. The agent drafts the entry, the developer corrects it. Rules for the workflow are in [agentic-workflow.md](agentic-workflow.md). + + diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..a0f600d --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,34 @@ +# Roadmap + +Milestone overview. Each step becomes one or more Gitea issues; link them here once they exist. Status lives on the project board only (see [agentic-workflow.md](agentic-workflow.md)), so this file has no checkboxes. + +## Setup + +- **0. Project skeleton and CI:** `pyproject.toml` with uv, ruff (rule sets `E`, `F`, `I`, `B`, `UP`, `ASYNC`) and pyright in strict mode; empty `src/deverenz/` and `tests/` layout. A Gitea Actions workflow runs ruff, pyright and pytest on every PR. First check on the dev Gitea that Actions is enabled and a runner is available. + +## MVP + +- **1. PR draft prompt (most important):** `deverenz pr create --dry-run` reads the local diff and the linked issue and prints the generated title and description. Iterate on the prompt until reviewers find it genuinely useful. Everything else depends on this. + - Judge the prompt mainly on the requirement check: the deliberate-deviation case must be caught, and nothing may be falsely reported as implemented. + - Include the ticket checks: "no linked ticket" warning and the ticket quality rating with concrete gaps. + - Keep 3–5 realistic cases in `tests/prompt_cases//` (`diff.patch` + `issue.md`), including one with a deliberate deviation from the issue. + - `--case ` runs a stored case instead of the local repo; render all cases into gitignored `out/` to compare prompt versions side by side. + - Once that works, add a project skill `/try-prompt` that runs all cases. +- **2. Open PRs from the CLI:** `deverenz pr create` pushes the branch and opens the PR via the Gitea API. +- **3. Merge report from the CLI:** `deverenz merged owner/repo ` posts the delivery summary with the record block on the ticket, links it from the PR, and applies the Done gate (close + move to Done only when clean, otherwise leave open for a PO decision). Has `--dry-run`. +- **4. Webhook server:** FastAPI route and signature check. `synchronized` refreshes the PR body block; merge runs step 3's pipeline. +- **5. Packaging:** Dockerfile, `docker-compose.yml` (deverenz service only), `deverenz register owner/repo` to create the webhook via the API. +- **6. Tests:** replay stored payloads with pytest + respx. + +## Developer tooling (later) + +- Claude Code status line: show model, context usage, current branch and the open roadmap step at the bottom of each session (set up via `/statusline`) + +## Later + +- `--short` / `--detailed` output length flags +- Extra board columns (e.g. "Test todo" / "Test done") +- Let the LLM pick PR labels from the repo's existing labels +- Forgejo verification + +Bigger ideas (other forges, Jira, sprint reports, Definition of Ready, the customizing assistant) live in `vision.md`. diff --git a/docs/vision.md b/docs/vision.md new file mode 100644 index 0000000..0cf551d --- /dev/null +++ b/docs/vision.md @@ -0,0 +1,61 @@ +# Deverenz vision + +Why the product exists and where it is heading. For implementation detail see `architecture.md`; for what's being built now see `roadmap.md`. + +## Problem + +Project management can be bad or missing entirely, because doing it well is expensive: it takes time, skill and people that a team doesn't always have, even in large companies. Git platforms already offer the building blocks (webhooks, boards, labels, milestones, APIs), but someone has to assemble them into a working process. + +Agile and Scrum make this worse in one specific way. Valuing conversation over documentation is right, but in practice it often turns into laissez-faire: +- tickets aren't kept up to date +- decisions are made face to face and never written down +- developers, project managers and product owners lose track of targets and objectives +- the company or client gets inconsistent, ad-hoc updates + +## Positioning + +Deverenz is a **suite of project management measures with opinionated defaults**. It works out of the box: install it, point it at a repo, and a sensible, consistent process happens without anyone designing it. + +- **Self-hosted, bring your own LLM.** Any OpenAI-compatible endpoint; code never has to leave the company. +- **Platform-independent, built step by step.** The MVP is proven on Gitea and Forgejo first; GitLab is the next platform, others follow. + +## Agile stance + +Deverenz strengthens Scrum's three pillars and patches its typical weaknesses: + +| Pillar | How Deverenz supports it | +|---|---| +| Transparency | Every delivery leaves a standardized record on the ticket, written automatically | +| Inspection | Each PR is checked against the ticket's requirements (implemented, deviates, missing, unclear), and the ticket's own quality is rated | +| Adaptation | Deviations require a visible decision (accept or follow-up ticket) instead of a hallway agreement | + +The result is the lightweight documentation agile tends to skip, without anyone having to write it. + +## Standardized records + +Every merged delivery leaves a structured, versioned record on its ticket: Markdown for people, plus a hidden JSON block for machines. Over time this becomes a queryable project history. Anyone can point their own LLM at it (for example through the git platform's MCP server) and ask "what shipped this sprint, and where did we deviate?". Deverenz is the **writer** of this history; MCP servers and scripts are the **readers**. + +## Principles + +- **Work flows freely, Done has to be earned.** Warn during work, never block it. Only clean deliveries move to Done automatically; everything else needs a visible human decision. +- **Generated content is clearly marked** and never pretends to be human-written. +- **Never rewrite human-authored requirements.** Ticket descriptions belong to their authors. +- **Cheap and predictable.** One LLM call per event. +- **One measure finished end to end before the next.** + +## Future + +- An assistant that customizes Deverenz per team on the fly: strictness, output length, columns, language +- Ticket quality check on the ticket itself (Definition of Ready): when a ticket is created or moved to "In progress", Deverenz comments with the concrete gaps (missing acceptance criteria, unmeasurable terms, unclear scope) so they're fixed before work starts, not discovered at merge. The MVP only rates ticket quality at PR and merge time. +- Sprint review report built from the records of a milestone (milestone = sprint), for the company or client +- `/accept` comment command as an explicit PO acceptance of deviations +- More measures: stale ticket detection, release notes, test columns +- Configurable strictness per team (e.g. block PR creation without a ticket) +- Other forges (GitLab, GitHub, Bitbucket), Jira integration, an admin UI + +## Risks + +- **Garbage in, garbage out.** Vague tickets give vague checks. Deverenz can't fix bad input, but it makes it visible: every report and record states the ticket's quality and its gaps, and requirements it can't judge are marked "unclear" rather than guessed. That keeps answers about a ticket honest, whether a person reads it or an LLM is asked about it later. +- **Trust.** A wrong "all requirements implemented" does more damage than no report. Accuracy over coverage. +- **Scope creep.** A suite of half-finished measures is worth less than one that works. +- **Big platforms.** Atlassian, GitHub and GitLab are moving into AI project insight. The defensible space is self-hosted, cross-forge and process-opinionated. -- 2.54.1