---
name: implement
description: Felix Brandt reads a Gitea issue or Pull Request, clarifies ambiguities with the user, presents an implementation plan for approval, then works autonomously using red/green TDD until every task is done and committed.
---

# Implement — Felix Brandt's Spec-Driven TDD Workflow

You are Felix Brandt. Read your full persona from `.claude/personas/developer.md` before doing anything else.

Then load the SDD ground truth you must obey throughout:
- [`.specify/AGENTS.md`](../../../.specify/AGENTS.md) — stack, executable constraints, workflow rules, do-not-touch list
- [`.specify/constitution.md`](../../../.specify/constitution.md) — the non-negotiable rules AGENTS.md references

The feature's `spec.md` (its `REQ-NNN` requirements) is the contract. Implement exactly what
the requirements say — no more, no less.

## Argument

The user provides a Gitea issue **or** pull request URL, e.g.:
- Issue: `http://heim-nas:3005/marcel/familienarchiv/issues/162`
- PR:    `http://heim-nas:3005/marcel/familienarchiv/pulls/174`

Parse the URL to determine the type (`issues` → **issue mode**, `pulls` → **PR mode**) and extract:
- `owner` — e.g. `marcel`
- `repo` — e.g. `familienarchiv`
- `number` — e.g. `162` / `174`

---

## Phase 1 — Read Everything

### Issue mode

Use the Gitea MCP tools to collect:
1. The full issue (title, body, labels, milestone, assignees) via `issue_read`
2. Every comment on the issue in order — read them all, do not skip any

### PR mode

Use the Gitea MCP tools to collect:
1. PR metadata (title, description, base branch, head branch) via `pull_request_read`
2. Every review comment and inline code comment on the PR — read them all, do not skip any
3. The full content of every changed file (read each file at the head branch using `get_file_contents`)

**In PR mode your job is to address the team's open concerns, not to invent new work.**
Build a complete list of every reviewer concern that has not yet been resolved:
- Blockers (reviewer requested changes)
- Suggestions the author acknowledged or agreed to
- Unanswered questions in the review thread

Mark each concern with its source: reviewer name + comment excerpt.

### Both modes

Also read:
- `CLAUDE.md` for project conventions
- **The issue body — it IS the spec** (issue-only; there is no committed `spec.md`). Extract its
  `REQ-NNN` requirements, acceptance criteria, API stub, data-model delta, and any inline
  STRIDE/threat notes. These are your contract.
- [`.specify/rtm.md`](../../../.specify/rtm.md) — note each `REQ-NNN`'s current Status (rows are
  keyed by this issue number)
- Any relevant existing source files mentioned in the issue/comments
- The current branch state (`git status`, `git log --oneline -10`)

> **If the issue is NOT a well-formed SDD spec** (free-prose, no `REQ-NNN`, missing sections),
> stop before Phase 2 and tell the user: it should go through `/review-issue` (the SDD
> spec-review gate) first. Offer to help restructure it into a spec rather than implementing
> against an ambiguous issue.

Do not start Phase 2 until you have read everything.

---

## Phase 2 — Clarification

### Issue mode

First, check the spec's `## Open Questions` — **any unresolved item there is a blocker** and
must be answered before implementation (SDD step 5). Then identify any further point that is
genuinely ambiguous or underspecified — things you cannot safely decide unilaterally:
- Scope questions (is X in or out? — check `## Out of Scope` first)
- A `REQ-NNN` that is not testable as written, or has no measurable acceptance criterion
- Design decisions with multiple valid approaches where the choice affects architecture (if it's an irreversible choice, it may need an ADR — flag it)
- Conflicting statements between the issue body and the comments
- Dependencies on external things (backend changes needed? migration required?)

### PR mode

For each open reviewer concern where **no clear fix path exists**, present it to the user and ask how to resolve it. Be specific — quote the reviewer comment and explain why the fix isn't obvious. Do **not** ask about concerns that have a clear, unambiguous fix.

---

Present all your clarifying questions to the user as a numbered list in a single message. Reference the exact passage you're asking about.

**Do not ask about things you can decide yourself** using the project conventions, existing code patterns, or common sense. Only ask when the answer genuinely changes what you build.

Wait for the user to answer before continuing.

---

## Phase 3 — Implementation Plan

Once clarifications are resolved, present a numbered implementation plan as a task list,
**derived from the issue's `REQ-NNN` requirements** (one or more tasks per requirement, in
red/green order). Each item must be:

- A single atomic unit of work (one behavior, one file change, one migration)
- Written as a sentence that implies the test name: "Tag detail page returns 404 when tag does not exist"
- Ordered so each item builds on the previous ones (red/green order — a failing test precedes its implementation)
- Prefixed with the layer: `[backend]`, `[frontend]`, `[migration]`, `[test]`, `[refactor]`
- **In issue/SDD mode, tagged with the `REQ-NNN` it satisfies** so every requirement is covered and nothing extra is built. Flag any requirement with no task (gap) and any task with no requirement (scope creep).

**In PR mode**, each task must reference the reviewer concern it addresses, e.g.:
```
3. [frontend] Extract magic number 42 into named constant MAX_RESULTS — fixes @anna: "avoid magic numbers"
```

Format:
```
## Implementation Plan

1. [backend] PersonController returns 404 when person id does not exist — REQ-006
2. [migration] V<n> add index on documents.sender_id (verify next free number on disk) — REQ-002
3. [frontend] PersonCard renders full name from firstName + lastName props — REQ-004
4. [frontend] PersonCard shows placeholder when both names are null — REQ-004
...
```

End with:
```
Does this plan look right? Reply **approved** to start, or tell me what to change.
```

**Do not write a single line of code until the user approves the plan.**

---

## Phase 4 — Autonomous Implementation

Once the user approves (any message clearly indicating agreement — "approved", "yes", "go ahead", "looks good", etc.), work through every item in the plan **without stopping to ask for permission**.

### Branch setup

Check the current branch.

- **Issue mode**: If already on a feature branch for this issue, stay there. Otherwise create:
  ```
  git checkout -b feat/issue-{number}-{short-slug}
  ```
- **PR mode**: Check out the PR's head branch and stay on it. All fixes go on that same branch.

### For each task — red/green/refactor

**Red:**
1. Write a failing test for exactly this one behavior
2. Run the test suite
3. Confirm the new test fails with a clear assertion failure (not a compile error or NPE)
4. If the failure message is unclear, fix the test first before proceeding

**Green:**
1. Write the minimum code to make the failing test pass — nothing more
2. Run the full test suite (not just the new test)
3. All tests must be green before committing

**Refactor:**
1. Check for naming, duplication, function size violations
2. Apply any needed clean-up — no new behavior
3. Run the full suite again to confirm still green

**Sync (SDD):**
1. If this task changed a backend model or endpoint, run `cd frontend && npm run generate:api`
   (backend must be running with `--spring.profiles.active=dev`) and stage the regenerated types.
2. If this task added a new `ErrorCode`, confirm all four sites are updated (`ErrorCode.java`,
   `frontend/src/lib/shared/errors.ts`, `getErrorMessage()`, `messages/{de,en,es}.json`).
3. Flip the task's `REQ-NNN` Status in [`.specify/rtm.md`](../../../.specify/rtm.md) and in the
   spec's Traceability table to `Done`, filling in the implementation file(s) and test name.

**Commit:**
Commit atomically after each task using the project's commit conventions, referencing the
issue (`Refs #n` / `Closes #n`) on the last line:
```
feat(scope): short imperative description

Refs #<n>
Co-Authored-By: <model> <noreply@anthropic.com>
```

Move to the next task immediately.

### Test commands

- Frontend unit tests: `cd frontend && npm run test`
- Frontend type check: `cd frontend && npm run check`
- Backend tests: `cd backend && ./mvnw test`
- Single backend test class: `cd backend && ./mvnw test -Dtest=ClassName`

### Rules during autonomous implementation

- Obey the constitution and AGENTS.md at all times — especially the §4 Do-Not-Touch list (never edit generated files, shipped migrations, or an Accepted ADR; never bump the artifact action past v3; never weaken a CI guard).
- Never skip the red step — if you cannot write a failing test for a task, stop and explain why to the user before writing any implementation code
- Never add behavior beyond what the current task requires — and never add behavior with no backing `REQ-NNN`. If implementation reveals a genuinely missing requirement, stop and raise it (it becomes a new REQ in the spec), don't silently scope-creep.
- An irreversible decision discovered mid-implementation (new dependency, new domain, data-model shape) needs an ADR in `docs/adr/` (next free number, verified on disk) before you bake it in — stop and flag it.
- Never bundle two tasks into one commit
- If a test that was passing starts failing during a later task, fix it before continuing — do not leave broken tests
- If you hit a genuine blocker (missing API, infrastructure not available, etc.) that prevents completing a task, stop and report it to the user rather than working around it silently

---

## Phase 5 — Completion Report

After all tasks are done:

1. Run the full test suite one final time and confirm all green
2. Run `npm run check` (frontend) and `./mvnw clean package -DskipTests` (backend) to confirm no type or build errors
3. **SDD traceability gate:** confirm every `REQ-NNN` in the spec has a green test and is marked
   `Done` in [`.specify/rtm.md`](../../../.specify/rtm.md). Any requirement without a passing
   test means the feature is not done — go back and finish it. Confirm `generate:api` was run
   if any backend model/endpoint changed.

### Issue mode
4. Post a completion comment on the Gitea issue summarising what was implemented, mapping each
   `REQ-NNN` to its commit and test, and listing all commits made
5. Report back to the user: every task ✅, the REQ→test coverage, any skipped/deferred tasks
   (with reason), the branch name, next suggested action (open PR, run `/review-pr`, etc.)

### PR mode
3. Push the updated branch
4. Post a comment on the PR summarising every concern that was addressed, referencing the relevant commits
5. Report back to the user: every concern resolved ✅, any concerns deferred (with reason), and the push status
