Zum Inhalt

QA Agent Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Build a structured QA oversight system consisting of two new skills (qa-review, qa-retro), a wrapper for systematic-debugging, an extension to the tdd skill, a structural coverage script, two Semgrep rules, and a CI workflow.

Architecture: Local: qa-review skill dispatches a fresh sub-agent that reads the git diff and writes missing RED tests. Retrospective: qa-retro is embedded in the systematic-debugging and tdd bug-fix flows. CI: a Python script and two Semgrep rules enforce structural invariants without LLM calls.

Tech Stack: Markdown (skills), Python 3.12 (check_test_coverage.py + its tests), YAML (Semgrep rules + GitHub Actions), pytest


File Map

New files — skills

  • ~/.claude/skills/qa-review/SKILL.md — main skill: dispatches QA sub-agent
  • ~/.claude/skills/qa-review/qa-categories.md — the 5 check categories in detail
  • ~/.claude/skills/qa-review/domain-composition-rules.md — Wirkgefüge composition rules
  • ~/.claude/skills/qa-review/report-format.md — output format for the sub-agent
  • ~/.claude/skills/qa-retro/SKILL.md — structured retrospective for bugs that slipped through
  • ~/.claude/skills/systematic-debugging/SKILL.md — wrapper: loads superpowers:systematic-debugging + qa-retro step

Modified files — skills

  • ~/.claude/skills/tdd/SKILL.md — add Step 3: mandatory qa-review call

New files — CI

  • scripts/check_test_coverage.py — structural coverage check (3 invariants)
  • api/tests/test_check_test_coverage.py — unit tests for the script
  • .semgrep/rules/klartext-fake-silent-constant.yaml — fake classes must not return silent placeholders
  • .semgrep/rules/klartext-router-no-try-except.yaml — routers must not catch exceptions
  • .github/workflows/qa.yml — CI workflow: runs script + Semgrep QA rules
  • docs/superpowers/qa-learnings/.gitkeep — creates the learnings folder

Task 1: Create qa-categories.md

Reference document for the 5 QA check categories. Read by the sub-agent as part of its context.

Files: - Create: ~/.claude/skills/qa-review/qa-categories.md

  • [x] Step 1: Write the file
# QA Check Categories

The QA sub-agent works through these five categories for every diff.

---

## Category 1: Test Completeness

For every new class or method in `models/`, `services/`, `repositories/`, `routers/`:

- Does a corresponding test file exist (`tests/test_<name>.py`)?
- Does every public method have at least one test?
- Are all four layers present?
  - Domain test (no mocks, no external systems)
  - Service test (with FakeRepository, no Supabase)
  - Repository test (`@pytest.mark.integration`, real database)
  - Router test (via `TestClient` or `AsyncClient`)

**Checklist per new class:**
- [ ] `test_<classname>_domain.py` or entry in `test_<module>.py` — Domain
- [ ] `test_<name>_service.py` — Service with FakeRepository
- [ ] `test_<name>_repository.py` with `@pytest.mark.integration` — Repository
- [ ] `test_<name>_router.py` with health test — Router

---

## Category 2: Edge and Error Cases

For every service and domain method, check:

- **Not Found:** if a method can fail to find a resource, is `XNotFoundError` raised and tested?
- **Invalid input:** are invalid inputs (empty string, None, malformed ID) tested at the router (422) and domain (DomainError)?
- **Empty collections:** does the code handle an empty list as input? Is it tested?
- **Duplicate detection:** if uniqueness is enforced, is the duplicate error path tested?
- **Error propagation:** is the error path tested alongside the happy path, not just listed?

**Red flags — these cases are almost always missing:**
- No test for the `XNotFoundError` case
- Router tests only test 200, never 404 or 422
- Service tests only test success, never the failure branches

---

## Category 3: Infrastructure Tests

- Every new router must have a `GET /<resource>/health` endpoint returning `{"status": "ok"}`.
- Every new router test file must have a test for this endpoint.
- Every new `SupabaseXRepository` method that uses the database client must have an
  `@pytest.mark.integration` test in `tests/test_<name>_repository.py`.
- Query methods with JOINs, PostgREST embedded counts (`table(count)`), or
  multi-table lookups **must** have integration tests — fake repositories cannot
  verify these queries work.

**Pattern for router health test (copy exactly):**
```python
@pytest.mark.asyncio
async def test_<resource>_health_returns_200() -> None:
    """Expects GET /<resource>/health to return HTTP 200 with status ok."""
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
        response = await client.get("/<resource>/health")
    assert response.status_code == 200
    assert response.json()["status"] == "ok"

Category 4: Fake Contract Completeness

  • Every Fake* class must implement the full interface (all abstract methods).
  • Methods must not return silent placeholder values as their only statement:
  • return 0 — hides that count is never tested
  • return [] — hides that the caller never verifies list contents
  • return None — hides that None handling is untested
  • return False — hides boolean logic gaps
  • For computed fields (counts derived from related objects), provide a test helper:
    def set_claim_count(self, narrative_id: str, count: int) -> None:
        """Sets the claim count for a narrative. Used in tests."""
        self._claim_counts[narrative_id] = count
    
  • Methods the fake cannot meaningfully implement must raise NotImplementedError explicitly — never silently return a default.

Note: return [] inside an if not items: branch is fine — it's conditional, not a silent default. Only flag standalone methods whose entire body is a silent return.


Category 5: Domain Composition Tests

Triggered when any of these appear in the diff: - models/causal_model*.py - models/slot*.py - models/causal_relation*.py - models/scope*.py - Any method on CausalModel, Slot, CausalRelation, or CausalModelScope

What to check: - Are there tests that assemble multiple domain objects and verify their interaction? - Example: create a CausalModel, add Slots and Relations, then verify scope resolution - Is scope behavior tested under different object combinations? - Empty model, single node, chain, fork, merge - Are composition edge cases covered? - Empty model → resolve() returns [] not None - Component in multiple containers simultaneously (CausalMixin) - Circular reference guard (if applicable) - Scope boundary conditions (node at edge of scope, node outside scope)

Important: Composition tests live at the domain level — no Supabase, no FakeRepository. They test CausalModel, Slot, and CausalModelScope directly.

- [x] **Step 2: Verify the file was created**

```bash
cat ~/.claude/skills/qa-review/qa-categories.md | head -5
Expected: the file header appears.

  • [x] Step 3: Commit (combined with Tasks 2-4)
git add ~/.claude/skills/qa-review/qa-categories.md
git commit -m "feat(qa): add qa-categories.md — the 5 QA check categories"

Task 2: Create domain-composition-rules.md

Detailed rules for when and how to write domain composition tests for the Wirkgefüge model.

Files: - Create: ~/.claude/skills/qa-review/domain-composition-rules.md

  • [x] Step 1: Write the file
# Domain Composition Rules

Rules for testing complex domain object networks. Applied by the QA sub-agent
whenever Wirkgefüge-related objects appear in the diff.

## When These Rules Apply

Apply these rules whenever the diff touches:
- `models/causal_model.py` or `models/causal_model_*.py`
- `models/slot.py`
- `models/causal_relation.py`
- `models/causal_model_scope.py`
- Any method on `CausalModel`, `Slot`, `CausalRelation`, `CausalModelScope`

**Important:** Also apply when only `CausalModel` methods change — not only
when Slot or CausalRelation appear in the diff. CausalModel changes can affect
scope behavior without touching those files directly.

## Rule 1: Null Return Guard

Every method that returns a collection must return an empty collection, not None,
when there are no results.

```python
# Always test this case
def test_scope_resolve_returns_empty_list_for_empty_model() -> None:
    """Expects resolve() to return [] not None for an empty CausalModel."""
    model = CausalModel.create(CreateCausalModelRequest(narrative_id="n1", label="test"))
    scope = CausalModelScope(model)
    assert scope.resolve("anything") == []

Rule 2: Assembled Network Tests

Any new method that operates on multiple domain objects (not just one) needs a test that assembles the full network and verifies the interaction.

For every new method on CausalModel that involves Slots or Relations, write: 1. A test with a minimal network (1–2 nodes, 1 relation) 2. A test with an empty network 3. A test with the specific edge case the method is designed to handle

Rule 3: Top-Down Operations Only

All semantic operations (namespace resolution, scope checking, completeness verification) start at CausalModel and traverse downward. Never call resolve/validate on a component directly. Tests must reflect this:

# Correct — operation on the model
result = model.resolve("component_id")

# Wrong — never test this
result = slot.resolve("component_id")  # Slots are context-free

Rule 4: CausalMixin Shared Components

When a component (Slot, Relation) is shared between multiple models via CausalMixin, test that: - Adding it to model A does not affect model B's resolution - Removing it from model A does not remove it from model B - Scope boundaries are enforced independently per model

Composition Test Template

class TestCausalModelComposition:
    """Tests for CausalModel behavior when components are assembled."""

    def _build_minimal_model(self) -> CausalModel:
        """Builds a CausalModel with one slot and one relation for testing."""
        model = CausalModel.create(
            CreateCausalModelRequest(narrative_id="n-001", label="test model")
        )
        slot_a = model.add_slot(SlotRequest(label="A", description="first"))
        slot_b = model.add_slot(SlotRequest(label="B", description="second"))
        model.add_relation(RelationRequest(source_id=slot_a.id, target_id=slot_b.id))
        return model

    def test_resolve_returns_all_slots(self) -> None:
        """Expects resolve() to return all slots in the model."""
        model = self._build_minimal_model()
        result = model.resolve_all_slots()
        assert len(result) == 2

    def test_resolve_empty_model_returns_empty_list(self) -> None:
        """Expects resolve() to return [] (not None) for an empty model."""
        model = CausalModel.create(
            CreateCausalModelRequest(narrative_id="n-001", label="empty")
        )
        assert model.resolve_all_slots() == []
- [x] **Step 2: Verify the file exists**

```bash
wc -l ~/.claude/skills/qa-review/domain-composition-rules.md
Expected: more than 50 lines.

  • [x] Step 3: Commit (combined with Tasks 1, 3-4)

Task 3: Create report-format.md

Defines the output format the QA sub-agent must produce.

Files: - Create: ~/.claude/skills/qa-review/report-format.md

  • [x] Step 1: Write the file
# QA Review Report Format

Every QA sub-agent run ends with a report in exactly this format.

---

## QA Review Report

### ✅ Complete
List each checked category and what was found to be complete.
Be specific: name the class, method, or test that was checked.

Example:
- Domain tests: `UserDomain` — all 3 public methods have tests
- Infrastructure: `/users/health` endpoint exists and is tested
- Fake contract: `FakeUserRepository` implements full interface

### ⚠️ Gaps found — RED tests written

For each gap: state the test file, the missing test name, and mark [WRITTEN] if
the test was written, or [NEEDS MANUAL ACTION] if it requires human input.

Example:
**test_user_service.py** — missing error cases:
→ `test_get_by_id_raises_for_inactive_user` [WRITTEN]
→ `test_change_email_raises_for_duplicate_email` [WRITTEN]

**test_users_router.py** — missing health endpoint test:
→ `test_users_health_returns_200` [WRITTEN]

### ❌ Requires manual decision

List anything the sub-agent cannot resolve automatically, with a specific reason.

Example:
- Integration test for `find_by_email` missing.
  Reason: query contains PostgREST filter — fake cannot verify this.
  Action needed: write `@pytest.mark.integration` test against real database.

---

## Rules for the sub-agent

1. Write [WRITTEN] tests directly into the appropriate test file — do not just describe them.
2. Written tests must be syntactically valid and fail when run (RED).
3. Never mark a gap as [WRITTEN] without actually writing the code.
4. If a test file does not exist yet, create it with the correct imports first.
5. Always run the written tests to confirm they are RED before reporting.
  • [x] Step 2: Commit (combined with Tasks 1-2, 4)

Task 4: Create qa-review/SKILL.md

The main skill file. Describes when to use it and how to dispatch the sub-agent.

Files: - Create: ~/.claude/skills/qa-review/SKILL.md

  • [x] Step 1: Write the file
---
name: qa-review
description: Use after every implementation session, before marking work complete. Dispatches a QA sub-agent that checks test coverage, edge cases, infrastructure tests, fake contract completeness, and domain composition tests. The tdd skill calls this automatically as Step 3.
---

# QA Review

After every implementation, dispatch a fresh QA sub-agent to review the diff with clean eyes.
The sub-agent has no context from the implementation session — this is intentional.

## When to Use

Mandatory after every implementation session:
- After completing a feature via the `tdd` skill (called automatically as Step 3)
- After any bug fix
- Before declaring work done and switching context

## Step 1: Collect the diff

```bash
git diff HEAD

If changes are staged but not committed yet:

git diff --staged

Step 2: Read the support files

Read these files to understand your review criteria: - ~/.claude/skills/qa-review/qa-categories.md — the 5 check categories - ~/.claude/skills/qa-review/domain-composition-rules.md — applies when Wirkgefüge objects are in the diff - ~/.claude/skills/qa-review/report-format.md — required output format

Step 3: Dispatch the QA sub-agent

Use the Agent tool to dispatch a fresh sub-agent with this prompt (fill in the diff):


You are a QA reviewer for the klartext project. Your only job is to find missing tests in the diff below and write them.

You have no context about how this code was written. Review it fresh.

Project: FastAPI + Supabase, Python 3.12
Test layers: 1. Domain — pure unit tests, no mocks, no external systems 2. Service — unit tests with FakeRepository (no Supabase) 3. Repository — @pytest.mark.integration against real database 4. Router — via TestClient or AsyncClient

Your task: 1. Read the diff 2. Check all 5 categories from the QA categories doc (provided below) 3. If Wirkgefüge objects are in the diff: apply domain composition rules (provided below) 4. Write missing tests as RED (failing) tests directly into the test files 5. Produce a report in the required format (provided below)

Key rules: - Never mark a test as [WRITTEN] without actually writing the code - Tests must fail when run — confirm RED before reporting - If a test file does not exist yet, create it with correct imports - Fake repositories: FakeUserRepository pattern, in api/tests/fakes/ - Router tests: use AsyncClient(transport=ASGITransport(app=app), base_url="http://test") - Integration tests: mark with @pytest.mark.integration and @pytest.mark.asyncio

[QA CATEGORIES]

[DOMAIN COMPOSITION RULES]

[REPORT FORMAT]

[DIFF]


Step 4: Act on the report

  • If RED tests were written: run pytest api/tests/ -m "not integration" -v to confirm they fail
  • Make all RED tests GREEN before declaring work done
  • If [NEEDS MANUAL ACTION] items remain: resolve them or document why they are deferred

What good looks like

Every implementation session ends with: - All 5 categories checked - No unresolved [NEEDS MANUAL ACTION] items (or documented reason for deferral) - All tests GREEN

- [x] **Step 2: Verify the skill is accessible**

```bash
ls ~/.claude/skills/qa-review/
Expected: SKILL.md qa-categories.md domain-composition-rules.md report-format.md

  • [x] Step 3: Commit (combined with Tasks 1-3)

Task 5: Create qa-retro/SKILL.md

Structured retrospective skill for bugs that slip through despite all checks.

Files: - Create: ~/.claude/skills/qa-retro/SKILL.md

  • [ ] Step 1: Write the file

---
name: qa-retro
description: Use when a bug is found that should have been caught by tests. Guides a structured retrospective, writes the missing test, identifies the blind spot, and documents a learning entry. Called automatically from systematic-debugging and the tdd bug-fix flow.
---

# QA Retrospective

A bug reached manual testing or production despite all checks passing.
This means the QA agent has a systematic blind spot. Make it visible and fix it.

## When to Use

- Automatically: at the end of a `systematic-debugging` session when a bug is fixed
- Automatically: at the end of a `tdd` bug-fix when a bug should have been caught earlier
- Manually (`/qa-retro`): when a bug is reported by a user or observed in production

## Step 1: Describe what happened

Answer these questions briefly:
1. What failed? (behavior, not implementation — "scope returned None instead of []")
2. When was it discovered? (manual test / user report / production)
3. Which test should have caught it? (category: Domain / Service / Repository / Router / Composition)

## Step 2: Write the missing test (RED)

Write the test that would have caught this bug. Follow TDD — the test must fail now.

```bash
pytest api/tests/test_<relevant_file>.py::test_<name> -v
Confirm: FAILED. Do not proceed until the test fails for the right reason.

Step 3: Fix the code (GREEN)

Make the minimal change to pass the test. Do not add unrelated changes.

pytest api/tests/ -m "not integration" -v
Confirm: all tests PASS.

Step 4: Identify the blind spot

Answer: why did the QA agent not write this test during the original implementation?

Choose one: - Unknown category — the QA agent's 5 categories don't cover this type of test - Known category, wrong trigger — the category exists but the trigger condition missed this case (example: composition tests only triggered on Slot/Relation diffs, not on CausalModel-only diffs) - Known category, agent failure — the trigger was correct but the agent missed the case

Step 5: Update the QA system

Based on the blind spot category:

Blind spot type Action
Unknown category Add new category to ~/.claude/skills/qa-review/qa-categories.md
Wrong trigger condition Fix trigger in qa-categories.md or domain-composition-rules.md
Agent failure (repeated) After 3+ failures in same category: sharpen the rule wording
Statically checkable pattern Add new Semgrep rule to .semgrep/rules/

Step 6: Write the learning entry

Save to docs/superpowers/qa-learnings/YYYY-MM-DD-<short-description>.md:

# QA Gap: YYYY-MM-DD — <short description>

## What happened
<1-2 sentences: what failed, when discovered>

## Missing test
`<test function name>`
→ Category: <which of the 5 categories>

## Why did qa-review miss this?
<specific reason — which trigger condition was wrong or missing>

## Consequence
→ <what was changed: file name + what was updated>
→ Semgrep: <new rule if applicable, or "not applicable (semantic pattern)">

Pattern recognition

After writing the entry, check docs/superpowers/qa-learnings/ for the same category appearing 3 or more times. If yes: the rule wording needs to be stronger, or a new Semgrep rule is needed. Do not defer this — fix it now.

- [ ] **Step 2: Commit**

```bash
git add ~/.claude/skills/qa-retro/SKILL.md
git commit -m "feat(qa): add qa-retro skill — structured retrospective for escaped bugs"


Task 6: Create systematic-debugging/SKILL.md wrapper

Wrapper that loads superpowers:systematic-debugging and appends the qa-retro step. Same pattern as tdd wraps superpowers:test-driven-development.

Files: - Create: ~/.claude/skills/systematic-debugging/SKILL.md

  • [ ] Step 1: Write the file
---
name: systematic-debugging
description: Use when debugging any bug or unexpected behavior. Loads superpowers:systematic-debugging and appends a qa-retro step to capture any test gaps discovered during debugging.
---

# Systematic Debugging

## Step 1: Load superpowers debugging skill

Before proceeding, invoke the `superpowers:systematic-debugging` skill.
All rules defined there apply without exception.

## Step 2: QA Retrospective (after the fix)

After the bug is fixed and the fix test is green:

**Ask:** should the QA agent have written a test for this during the original implementation?

- **Yes:** invoke `qa-retro` to document the blind spot and update the QA system.
- **No (e.g. environment issue, data issue, not a code gap):** no action needed.

The `qa-retro` step is not optional when the answer is yes — it is how the QA system
learns. A bug fixed without updating the QA system means the same bug can happen again.
  • [ ] Step 2: Commit
git add ~/.claude/skills/systematic-debugging/SKILL.md
git commit -m "feat(qa): add systematic-debugging wrapper — appends qa-retro step after fix"

Task 7: Extend tdd/SKILL.md with Step 3

Adds the mandatory qa-review call as Step 3 of the tdd skill.

Files: - Modify: ~/.claude/skills/tdd/SKILL.md

  • [ ] Step 1: Read the current file
cat ~/.claude/skills/tdd/SKILL.md
  • [ ] Step 2: Append Step 3 to the file

Add this section at the end of ~/.claude/skills/tdd/SKILL.md:

## Step 3: QA Review

Before marking work complete, invoke the `qa-review` skill.

The QA agent reviews the diff with fresh eyes — no context from this session.

**For bug fixes specifically:** after the fix is green, also invoke `qa-retro` if the
bug should have been caught during the original implementation.

This step is not optional. "All tests green" is necessary but not sufficient.
The qa-review step verifies that the right tests exist, not just that the existing
tests pass.
  • [ ] Step 3: Verify the file now has 3 steps

grep "^## Step" ~/.claude/skills/tdd/SKILL.md
Expected:
## Step 1: Load superpowers TDD skill
## Step 2: Apply project-specific standards
## Step 3: QA Review

  • [ ] Step 4: Commit
git add ~/.claude/skills/tdd/SKILL.md
git commit -m "feat(qa): extend tdd skill with mandatory qa-review step"

Task 8: Write scripts/check_test_coverage.py (TDD)

Structural coverage checker: 3 invariants, deterministic, used in CI.

Files: - Create: scripts/check_test_coverage.py - Create: api/tests/test_check_test_coverage.py

  • [ ] Step 1: Write the failing tests first

Create api/tests/test_check_test_coverage.py:

"""Tests for scripts/check_test_coverage.py.

Tests use a temporary directory that mimics the klartext API structure.
"""
from __future__ import annotations

from pathlib import Path

import pytest

# Add scripts/ to path so we can import the module
import sys
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "scripts"))

from check_test_coverage import (
    check_router_health_tests,
    check_supabase_integration_markers,
    check_test_files_exist,
)


@pytest.fixture()
def api_tree(tmp_path: Path) -> Path:
    """Creates a temporary directory tree that mimics the klartext API structure."""
    (tmp_path / "api" / "models").mkdir(parents=True)
    (tmp_path / "api" / "services").mkdir(parents=True)
    (tmp_path / "api" / "repositories").mkdir(parents=True)
    (tmp_path / "api" / "routers").mkdir(parents=True)
    (tmp_path / "api" / "tests").mkdir(parents=True)
    return tmp_path


class TestCheckTestFilesExist:
    def test_returns_empty_when_all_source_files_have_tests(self, api_tree: Path) -> None:
        """Expects no missing files when every source file has a test counterpart."""
        (api_tree / "api" / "models" / "user.py").touch()
        (api_tree / "api" / "tests" / "test_user.py").touch()
        missing = check_test_files_exist(root=api_tree)
        assert missing == []

    def test_returns_missing_when_test_file_absent(self, api_tree: Path) -> None:
        """Expects the source file path when no test file exists."""
        (api_tree / "api" / "models" / "user.py").touch()
        missing = check_test_files_exist(root=api_tree)
        assert len(missing) == 1
        assert "user.py" in missing[0]

    def test_excludes_init_and_main_files(self, api_tree: Path) -> None:
        """Expects __init__.py, main.py, dependencies.py, cli.py, seeddata.py to be excluded."""
        for name in ["__init__.py", "main.py", "dependencies.py", "cli.py", "seeddata.py"]:
            (api_tree / "api" / "routers" / name).touch()
        missing = check_test_files_exist(root=api_tree)
        assert missing == []


class TestCheckRouterHealthTests:
    def test_returns_empty_when_health_test_present(self, api_tree: Path) -> None:
        """Expects no missing files when the router test has a health test."""
        test_file = api_tree / "api" / "tests" / "test_users_router.py"
        test_file.write_text("def test_users_health_returns_200(): pass\n")
        missing = check_router_health_tests(root=api_tree)
        assert missing == []

    def test_returns_file_when_health_test_absent(self, api_tree: Path) -> None:
        """Expects the test file path when no health test is found."""
        test_file = api_tree / "api" / "tests" / "test_users_router.py"
        test_file.write_text("def test_create_user(): pass\n")
        missing = check_router_health_tests(root=api_tree)
        assert len(missing) == 1
        assert "test_users_router.py" in missing[0]

    def test_only_checks_router_test_files(self, api_tree: Path) -> None:
        """Expects non-router test files to be ignored."""
        test_file = api_tree / "api" / "tests" / "test_user_service.py"
        test_file.write_text("def test_something(): pass\n")
        missing = check_router_health_tests(root=api_tree)
        assert missing == []


class TestCheckSupabaseIntegrationMarkers:
    def test_returns_empty_when_integration_marker_present(self, api_tree: Path) -> None:
        """Expects no missing files when the Supabase repo test has @pytest.mark.integration."""
        (api_tree / "api" / "repositories" / "supabase_user_repository.py").touch()
        test_file = api_tree / "api" / "tests" / "test_supabase_user_repository.py"
        test_file.write_text("@pytest.mark.integration\nasync def test_save(): pass\n")
        missing = check_supabase_integration_markers(root=api_tree)
        assert missing == []

    def test_returns_file_when_integration_marker_absent(self, api_tree: Path) -> None:
        """Expects the test file path when @pytest.mark.integration is missing."""
        (api_tree / "api" / "repositories" / "supabase_user_repository.py").touch()
        test_file = api_tree / "api" / "tests" / "test_supabase_user_repository.py"
        test_file.write_text("async def test_save(): pass\n")
        missing = check_supabase_integration_markers(root=api_tree)
        assert len(missing) == 1
        assert "test_supabase_user_repository.py" in missing[0]

    def test_skips_repo_if_test_file_missing(self, api_tree: Path) -> None:
        """Expects no error if the test file does not exist — that is caught by check_test_files_exist."""
        (api_tree / "api" / "repositories" / "supabase_user_repository.py").touch()
        missing = check_supabase_integration_markers(root=api_tree)
        assert missing == []

    def test_only_checks_supabase_repositories(self, api_tree: Path) -> None:
        """Expects non-Supabase repository test files to be ignored."""
        (api_tree / "api" / "repositories" / "user_repository.py").touch()
        test_file = api_tree / "api" / "tests" / "test_user_repository.py"
        test_file.write_text("def test_something(): pass\n")
        missing = check_supabase_integration_markers(root=api_tree)
        assert missing == []
  • [ ] Step 2: Run tests — confirm they all fail

cd /Users/thormar/klartext && python -m pytest api/tests/test_check_test_coverage.py -v
Expected: all tests FAIL (ImportError: No module named 'check_test_coverage').

  • [ ] Step 3: Write the implementation

Create scripts/check_test_coverage.py:

#!/usr/bin/env python3
"""Structural test coverage checker for klartext API.

Three invariants:
1. Every source file in models/services/repositories/routers has a test file.
2. Every router test file contains a health endpoint test (function with 'health' in name).
3. Every Supabase repository test file has at least one @pytest.mark.integration marker.

Exits with code 1 if any check fails. Used in CI (qa.yml).

Usage (from repo root):
    python scripts/check_test_coverage.py
"""
from __future__ import annotations

import sys
from pathlib import Path

SOURCE_DIRS = ["models", "services", "repositories", "routers"]
EXCLUDED_FILES = {"__init__.py", "dependencies.py", "main.py", "cli.py", "seeddata.py"}


def check_test_files_exist(root: Path | None = None) -> list[str]:
    """Returns source files that have no corresponding test file.

    Checks every .py file in models/, services/, repositories/, routers/
    against tests/test_<name>.py. Excluded files are skipped.
    """
    if root is None:
        root = Path(__file__).parent.parent
    api_dir = root / "api"
    tests_dir = api_dir / "tests"
    missing: list[str] = []
    for source_dir in SOURCE_DIRS:
        dir_path = api_dir / source_dir
        if not dir_path.exists():
            continue
        for source_file in sorted(dir_path.glob("*.py")):
            if source_file.name in EXCLUDED_FILES:
                continue
            test_file = tests_dir / f"test_{source_file.name}"
            if not test_file.exists():
                missing.append(
                    f"  {source_file.relative_to(root)}"
                    f"  →  api/tests/test_{source_file.name}"
                )
    return missing


def check_router_health_tests(root: Path | None = None) -> list[str]:
    """Returns router test files that contain no health endpoint test.

    Every file matching tests/test_*_router.py must have a function
    whose name contains 'health'.
    """
    if root is None:
        root = Path(__file__).parent.parent
    tests_dir = root / "api" / "tests"
    missing: list[str] = []
    for test_file in sorted(tests_dir.glob("test_*_router.py")):
        content = test_file.read_text()
        if "health" not in content.lower():
            missing.append(
                f"  {test_file.relative_to(root)}"
                f"  →  add test_*_health_* function"
            )
    return missing


def check_supabase_integration_markers(root: Path | None = None) -> list[str]:
    """Returns Supabase repository test files missing @pytest.mark.integration.

    Every supabase_*.py in repositories/ must have a test file that
    contains at least one @pytest.mark.integration marker.
    """
    if root is None:
        root = Path(__file__).parent.parent
    api_dir = root / "api"
    tests_dir = api_dir / "tests"
    missing: list[str] = []
    for repo_file in sorted((api_dir / "repositories").glob("supabase_*.py")):
        test_file = tests_dir / f"test_{repo_file.name}"
        if not test_file.exists():
            continue  # caught by check_test_files_exist
        content = test_file.read_text()
        if "@pytest.mark.integration" not in content:
            missing.append(
                f"  {test_file.relative_to(root)}"
                f"  →  add @pytest.mark.integration test"
            )
    return missing


def main() -> None:
    """Runs all three checks and exits with code 1 if any fail."""
    errors: list[tuple[str, list[str]]] = []

    missing_files = check_test_files_exist()
    if missing_files:
        errors.append(("Source files without test files", missing_files))

    missing_health = check_router_health_tests()
    if missing_health:
        errors.append(("Router test files without health test", missing_health))

    missing_integration = check_supabase_integration_markers()
    if missing_integration:
        errors.append((
            "Supabase repository tests without @pytest.mark.integration",
            missing_integration,
        ))

    if errors:
        print("ERROR: test coverage checks failed:\n")
        for title, items in errors:
            print(f"{title}:")
            for item in items:
                print(item)
            print()
        sys.exit(1)

    print("OK: all structural test coverage checks passed.")


if __name__ == "__main__":
    main()
  • [ ] Step 4: Run tests — confirm they pass

cd /Users/thormar/klartext && python -m pytest api/tests/test_check_test_coverage.py -v
Expected: all tests PASS.

  • [ ] Step 5: Run the script against the real codebase

python scripts/check_test_coverage.py
Expected: either "OK" or a list of existing gaps. If gaps are listed, note them — they are pre-existing issues, not introduced by this task. Do not fix them here.

  • [ ] Step 6: Commit
git add scripts/check_test_coverage.py api/tests/test_check_test_coverage.py
git commit -m "feat(qa): add check_test_coverage.py — structural CI coverage check"

Task 9: Write Semgrep rule — fake silent constants

Flags Fake* class methods whose entire body is a silent placeholder return value.

Files: - Create: .semgrep/rules/klartext-fake-silent-constant.yaml

  • [ ] Step 1: Write the rule
rules:
  - id: klartext-fake-silent-constant
    # Fake repository methods must not return silent placeholder values.
    # A method whose entire body is 'return 0', 'return []', 'return None',
    # 'return False', or 'return ""' hides missing functionality — tests pass
    # even when the code under test ignores the returned value.
    #
    # Use a test-controllable helper (set_claim_count()) or raise NotImplementedError.
    # Conditional returns (inside if/else) are fine — only standalone single-statement
    # bodies are flagged.
    #
    # To suppress a legitimate case: add  # nosemgrep: klartext-fake-silent-constant
    patterns:
      - pattern-inside: |
          class Fake$REPO(...):
              ...
      - pattern: |
          def $METHOD(self, ...):
              return $VALUE
      - metavariable-pattern:
          metavariable: $VALUE
          patterns:
            - pattern-either:
                - pattern: "0"
                - pattern: "[]"
                - pattern: '""'
                - pattern: "False"
                - pattern: "None"
    message: >
      Fake.$METHOD returns silent placeholder '$VALUE' as its entire body.
      This hides a test gap — the calling test can never verify this value is wrong.
      Use a test-controllable helper (e.g. set_$METHOD_result()) or raise NotImplementedError.
      To suppress a legitimate case: # nosemgrep: klartext-fake-silent-constant
    severity: ERROR
    languages: [python]
    paths:
      include:
        - "**/tests/fakes/*.py"
    metadata:
      category: correctness
      references:
        - CLAUDE.md (Fake contract completeness)
        - docs/superpowers/specs/2026-06-06-qa-agent-design.md
  • [ ] Step 2: Test the rule against the existing fakes

cd /Users/thormar/klartext && api/.venv/bin/semgrep scan --config=.semgrep/rules/klartext-fake-silent-constant.yaml api/tests/fakes/ --metrics=off
Expected: zero findings (the existing return [] in fake_claim_repository.py is inside an if not claims: branch — not a bare single-statement body, so it is not flagged).

If findings appear: either suppress with # nosemgrep on the specific line, or fix the fake.

  • [ ] Step 3: Commit
git add .semgrep/rules/klartext-fake-silent-constant.yaml
git commit -m "feat(qa): add Semgrep rule — fake silent constant detection"

Task 10: Write Semgrep rule — no try/except in routers

Flags try/except blocks in router files. Routers must delegate all error handling to central exception handlers — catching exceptions in the router bypasses the handler chain.

Files: - Create: .semgrep/rules/klartext-router-no-try-except.yaml

  • [ ] Step 1: Write the rule
rules:
  - id: klartext-router-no-try-except
    # Router functions must not catch exceptions.
    # All error handling is delegated to central exception handlers registered in main.py.
    # Catching in the router bypasses the handler chain and can return unexpected
    # response shapes or swallow errors silently.
    #
    # If you need conditional logic based on a service result, use return values or
    # check the domain object state — do not use exceptions for flow control.
    #
    # To suppress a legitimate case: # nosemgrep: klartext-router-no-try-except
    pattern: |
      try:
          ...
      except ...:
          ...
    message: >
      Router function contains a try/except block. Routers must not catch exceptions
      — let them propagate to the central exception handlers in main.py, which translate
      them to the correct HTTP response. To suppress: # nosemgrep: klartext-router-no-try-except
    severity: ERROR
    languages: [python]
    paths:
      include:
        - "**/routers/*.py"
    metadata:
      category: correctness
      references:
        - CLAUDE.md (Error Handling — Router: no try/except)
        - docs/superpowers/specs/2026-06-06-qa-agent-design.md
  • [ ] Step 2: Test against existing router files

cd /Users/thormar/klartext && api/.venv/bin/semgrep scan --config=.semgrep/rules/klartext-router-no-try-except.yaml api/routers/ --metrics=off
Expected: zero findings. If findings appear, they are pre-existing violations — add # nosemgrep: klartext-router-no-try-except to suppress them and open a separate task to fix them properly.

  • [ ] Step 3: Commit
git add .semgrep/rules/klartext-router-no-try-except.yaml
git commit -m "feat(qa): add Semgrep rule — no try/except in router files"

Task 11: Create qa.yml CI workflow

New GitHub Actions workflow that runs the structural coverage check and the two new Semgrep QA rules on every push and pull request.

Files: - Create: .github/workflows/qa.yml

  • [ ] Step 1: Write the workflow
name: QA

# Runs structural test coverage checks and QA-specific Semgrep rules.
# Complements lint.yml (which runs existing Semgrep rules) with QA-specific invariants.

on:
  push:
  pull_request:

jobs:
  qa:
    name: QA Checks
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip
          cache-dependency-path: api/pyproject.toml

      - name: Install dependencies
        run: pip install -e '.[dev]'
        working-directory: api

      - name: Structural test coverage check
        # Checks three invariants:
        # 1. Every source file has a test file
        # 2. Every router test has a health test
        # 3. Every Supabase repository test has @pytest.mark.integration
        run: python scripts/check_test_coverage.py

      - name: Semgrep QA rules
        # Runs only the QA-specific Semgrep rules (fake constants + router try/except).
        # The full Semgrep rule set (including existing rules) runs in lint.yml.
        run: |
          semgrep scan \
            --config=.semgrep/rules/klartext-fake-silent-constant.yaml \
            --config=.semgrep/rules/klartext-router-no-try-except.yaml \
            --error \
            --metrics=off \
            api/
        working-directory: ${{ github.workspace }}
  • [ ] Step 2: Verify the workflow file is valid YAML

python -c "import yaml; yaml.safe_load(open('.github/workflows/qa.yml'))" && echo "Valid YAML"
Expected: Valid YAML

  • [ ] Step 3: Commit
git add .github/workflows/qa.yml
git commit -m "feat(qa): add qa.yml CI workflow — structural coverage + Semgrep QA rules"

Task 12: Create qa-learnings/ folder and smoke-test the full system

Creates the learning archive folder and verifies the complete QA system works end-to-end.

Files: - Create: docs/superpowers/qa-learnings/.gitkeep

  • [ ] Step 1: Create the learnings folder
mkdir -p /Users/thormar/klartext/docs/superpowers/qa-learnings
touch /Users/thormar/klartext/docs/superpowers/qa-learnings/.gitkeep
  • [ ] Step 2: Verify all CI checks pass locally

# Structural coverage check
python scripts/check_test_coverage.py

# QA Semgrep rules
api/.venv/bin/semgrep scan \
  --config=.semgrep/rules/klartext-fake-silent-constant.yaml \
  --config=.semgrep/rules/klartext-router-no-try-except.yaml \
  --error --metrics=off api/

# Unit tests for the coverage script
python -m pytest api/tests/test_check_test_coverage.py -v
Expected: all three commands exit with code 0.

  • [ ] Step 3: Verify all new skills are present

ls ~/.claude/skills/qa-review/
ls ~/.claude/skills/qa-retro/
ls ~/.claude/skills/systematic-debugging/
grep "Step 3" ~/.claude/skills/tdd/SKILL.md
Expected:
SKILL.md  domain-composition-rules.md  qa-categories.md  report-format.md
SKILL.md
SKILL.md
## Step 3: QA Review

  • [ ] Step 4: Final commit
git add docs/superpowers/qa-learnings/.gitkeep
git commit -m "feat(qa): create qa-learnings folder — learning archive for escaped bugs"
  • [ ] Step 5: Verify CI pipeline

Push the branch or check the Actions tab on GitHub to confirm qa.yml runs and passes. All five CI workflows should be green: - QA (new) - Test - Integration Tests - Lint - Setup Smoke Test (only if setup files changed)