agentleFS
harshadmadayeharshadmadaye/OPM/skills/tdd-workflow/SKILL.md

tdd-workflow

Skill4 starsChanged 57 days agoMITView on GitHub

Drives test-driven development through a strict RED-GREEN-REFACTOR cycle with test-runner detection, a "fails for the right reason" gate, checkpoint commits, and a short evidence report. Use when implementing a feature, fixing a bug, or refactoring logic where the expected behaviour can be written as a test before the code exists.

148 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use orch-pipeline, ralphinho-rfc-pipeline and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • renepfSkill

    orch-pipeline

    Shared orchestration engine for the orch-* skill family. Defines the gated Research-Plan-TDD-Review-Commit pipeline, the size classifier, the agent map, and the two human gates that the orch-* operation skills delegate to. Not usually invoked directly.

    Also in 5 projects that use this

  • junimnjwSkill

    ralphinho-rfc-pipeline

    RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.

    Also in 18 projects that use this

  • loulanyueSkill

    nuxt4-patterns

    Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.

    Also in 14 projects that use this

  • RojiosSkill

    dart-flutter-patterns

    Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.

    Also in 10 projects that use this

  • royaluniondesign-sysSkill

    content-hash-cache-pattern

    Cache expensive file processing results using SHA-256 content hashes — path-independent, auto-invalidating, with service layer separation.

    Also in 23 projects that use this

  • HABUBUSSSkill

    project-guidelines-example

    Also in 20 projects that use this

The file

Show its rules and text

We split this skill into the rules it gives an agent

14 rules. 0 are common, 7 are distinctive, and 7 are very specific to this project.

  • 0

    Common

    Most of the 136 edited versions we read keep these.

  • 7

    Distinctive

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Never assume npm test. Resolve the commands once, before writing any test.

    line 25
  2. Distinctive:

    Write the guarantee in one sentence before writing code or tests:

    line 48
  3. Very specific:

    Write one test (or one small group) for one behaviour.

    line 61
  4. Distinctive:

    Read the failure message and confirm it names the right thing.

    line 72
  5. Distinctive:

    If the test passes immediately, stop: either the behaviour already exists, or the test does not test what you think.

    line 74
  6. Distinctive:

    Write the smallest change that makes the failing test pass.

    line 82
  7. Very specific:

    Run <test-one> again and confirm it passes.

    line 85
  8. Distinctive:

    Do not squash or rewrite them until the workflow is complete and the evidence report exists.

    line 103
  9. Very specific:

    If commits are later squashed, copy the RED/GREEN/refactor summary into the PR body or the evidence report so a reviewer can still answer …

    line 106
  10. Very specific:

    After the last GREEN, produce a short report.

    line 111
  11. Very specific:

    Test observable behaviour, not internals (screen.getByText("Count: 5"), not component.state.count).

    line 235
  12. Distinctive:

    Prefer semantic selectors and public APIs over CSS classes and private members.

    line 239
  13. Distinctive:

    Keep unit tests fast; slow suites get skipped, and skipped suites rot.

    line 240
  14. Very specific:

    Never leave .skip, .only, xit, or @pytest.mark.skip in a commit without a linked reason.

    line 241

“Common” is measured: kept by at least 6 in 10 of the 136 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

TDD Workflow

Tests come first. The failing test is the specification; the passing test is the proof. This skill gives the cycle enough structure that "I wrote tests" always means "a test failed, then passed, and here is the evidence".

When to use

  • New behaviour with definable inputs and outputs (business logic, parsers, API handlers, validators, state machines).
  • Bug fixes: the reproducer test is the first artefact, always.
  • Refactors of logic that already has tests (the tests are the safety net) or should have them.
  • A task in a plan produced by opm:writing-plans whose verify step names a test.

Skip TDD (write tests afterwards, or not at all) for: pure layout and styling, throwaway prototypes, one-off scripts, configuration edits, glue with no logic. The heuristic: can you write expect(fn(input)).toBe(output) before writing fn? If yes, use this skill.

Step 0: Detect the test runner

Never assume npm test. Resolve the commands once, before writing any test.

Node / TypeScript. Package manager comes from the lockfile or package.json packageManager: pnpm-lock.yaml -> pnpm, yarn.lock -> yarn, bun.lock/bun.lockb -> bun, otherwise npm. The runner comes from package.json scripts.test and the test imports (vitest, jest, bun:test). The package manager and the runner are different things: a bun-installed project may still run vitest.

Stack<test><test-one><coverage>
vitest<pm> test or npx vitest runnpx vitest run path/to/file.test.tsnpx vitest run --coverage
jest<pm> test or npx jestnpx jest path/to/file.test.tsnpx jest --coverage
bun native (bun:test)bun testbun test path/to/file.test.tsbun test --coverage
pytestuv run pytest or pytestpytest tests/test_x.py::test_namepytest --cov=<pkg>
flutterflutter testflutter test test/x_test.dartflutter test --coverage
dart (no Flutter)dart testdart test test/x_test.dartdart test --coverage=coverage

bun test (native runner) and bun run test (runs the package script) are not interchangeable. Confirm which one the project expects before the RED gate.

Substitute the resolved commands wherever <test>, <test-one>, <coverage> appear below.

Step 1: State the behaviour

Write the guarantee in one sentence before writing code or tests:

As a <role>, I want <action>, so that <benefit>.

Turn each guarantee into named test cases: happy path, at least one edge (empty, null, boundary), at least one error path. If the work comes from a plan, reuse its acceptance criteria rather than inventing new ones. Keep a running map of behaviour -> test -> RED evidence -> GREEN evidence; it becomes the evidence report in Step 5.

Step 2: RED - write the test and watch it fail correctly

Write one test (or one small group) for one behaviour. Run <test-one>.

The RED gate. Production code may only be touched once one of these holds:

  • Runtime RED: the test file compiles/imports, the new test actually executes, and it fails on the assertion or on the missing behaviour.
  • Compile-time RED: the new test references a symbol or code path that does not yet exist, and that missing symbol is exactly the thing you are about to build.

In both cases the failure must be caused by the missing or wrong behaviour, not by: a typo in the test, a missing import, broken fixtures, a missing dependency, or an unrelated regression. Read the failure message and confirm it names the right thing. A test that was written but never run is not RED.

If the test passes immediately, stop: either the behaviour already exists, or the test does not test what you think. Fix the test before proceeding.

Checkpoint commit (when the repo is under git): test: add failing test for <behaviour>.

Step 3: GREEN - minimal code to pass

Write the smallest change that makes the failing test pass. Hardcoding is allowed when it is the simplest thing; the next test will force generalisation. Do not add behaviour no test asked for.

Run <test-one> again and confirm it passes. Then run <test> for the whole relevant target to confirm nothing else broke. Only a GREEN run of the same test that was RED counts.

Checkpoint commit: feat: <behaviour> or fix: <bug>.

Step 4: REFACTOR - clean up under a green bar

With tests passing, improve the code: remove duplication, rename for clarity, extract functions, simplify conditionals. Run <test> after each meaningful change. Do not add behaviour during refactor; if you discover a missing case, write it down and go back to Step 2 for it.

Checkpoint commit (only if something changed): refactor: <what was cleaned up>.

Repeat Steps 2-4 for the next behaviour in the map.

Checkpoint commit rules

  • One commit per stage, on the current branch, in sequence: test -> feat/fix -> refactor.
  • Do not squash or rewrite them until the workflow is complete and the evidence report exists.
  • The RED commit is valid evidence only if the test was compiled, run, and failed for the intended reason.
  • The GREEN commit is valid evidence only if the same test target was rerun and passed.
  • If commits are later squashed, copy the RED/GREEN/refactor summary into the PR body or the evidence report so a reviewer can still answer "what was verified and how".

Step 5: Evidence report

After the last GREEN, produce a short report. Put it in the PR description, the task summary, or a project doc location if one is established (for example docs/tdd/<task>.md). Include:

  1. Behaviours - the sentences from Step 1.
  2. Test table:
| # | Guarantee | Test | RED evidence | GREEN evidence |
|---|-----------|------|--------------|----------------|
| 1 | Empty query returns [] without throwing | src/search.test.ts > "returns [] for empty query" | `npx vitest run src/search.test.ts` -> FAIL: searchItems is not a function | same command -> 1 passed |
| 2 | Limit above 100 is rejected with 400 | tests/test_api.py::test_limit_rejected | `pytest tests/test_api.py::test_limit_rejected` -> AssertionError 200 != 400 | same -> 1 passed |
  1. Coverage (if the project measures it): command and the resulting number, plus any intentional gaps.
  2. Commits: the checkpoint hashes in order.

Quote real commands and real output excerpts. Never record PASS for a test that was not run. The final claim of "done" then goes through opm:verification-before-completion.

Examples

TypeScript (vitest)

// src/slugify.test.ts  -- RED: slugify does not exist yet
import { describe, it, expect } from "vitest";
import { slugify } from "./slugify";

describe("slugify", () => {
  it("lowercases and hyphenates words", () => {
    expect(slugify("Hello World")).toBe("hello-world");
  });
  it("collapses repeated separators", () => {
    expect(slugify("a  --  b")).toBe("a-b");
  });
  it("returns empty string for blank input", () => {
    expect(slugify("   ")).toBe("");
  });
});
// src/slugify.ts  -- GREEN: minimal implementation
export function slugify(input: string): string {
  return input
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

RED run: npx vitest run src/slugify.test.ts -> Error: Failed to resolve import "./slugify" (compile-time RED, correct reason). GREEN run: same command -> 3 passed.

Python (pytest)

# tests/test_pagination.py  -- RED
import pytest
from app.pagination import clamp_limit

def test_default_limit_when_none():
    assert clamp_limit(None) == 20

def test_limit_is_capped():
    assert clamp_limit(500) == 100

def test_negative_limit_rejected():
    with pytest.raises(ValueError):
        clamp_limit(-1)
# app/pagination.py  -- GREEN
DEFAULT_LIMIT = 20
MAX_LIMIT = 100

def clamp_limit(limit: int | None) -> int:
    if limit is None:
        return DEFAULT_LIMIT
    if limit < 0:
        raise ValueError("limit must be non-negative")
    return min(limit, MAX_LIMIT)

RED run: uv run pytest tests/test_pagination.py -> ModuleNotFoundError: No module named 'app.pagination'. GREEN run: same -> 3 passed.

Dart (flutter test)

// test/cart_total_test.dart  -- RED
import 'package:flutter_test/flutter_test.dart';
import 'package:shop/cart.dart';

void main() {
  test('empty cart totals zero', () {
    expect(cartTotal(const []), 0);
  });
  test('sums price times quantity', () {
    const items = [CartItem(price: 250, quantity: 2), CartItem(price: 100, quantity: 1)];
    expect(cartTotal(items), 600);
  });
}
// lib/cart.dart  -- GREEN
class CartItem {
  const CartItem({required this.price, required this.quantity});
  final int price;
  final int quantity;
}

int cartTotal(List<CartItem> items) =>
    items.fold(0, (sum, item) => sum + item.price * item.quantity);

RED run: flutter test test/cart_total_test.dart -> Error: Method not found: 'cartTotal'. GREEN run: same -> All tests passed!.

Testing habits that keep the cycle honest

  • Test observable behaviour, not internals (screen.getByText("Count: 5"), not component.state.count).
  • One behaviour per test; the test name states the guarantee.
  • Each test creates its own data; no ordering dependencies between tests.
  • Mock only at true boundaries (network, clock, filesystem, third-party SDKs). Mocking your own modules hides bugs.
  • Prefer semantic selectors and public APIs over CSS classes and private members.
  • Keep unit tests fast; slow suites get skipped, and skipped suites rot.
  • Never leave .skip, .only, xit, or @pytest.mark.skip in a commit without a linked reason.

Common failure modes

SymptomWhat went wrongFix
Test passes on first runBehaviour already exists or the assertion is vacuousStrengthen the assertion or delete the redundant test
RED caused by import typoNot a valid REDFix the test, rerun, confirm failure names the missing behaviour
Wrote three functions to pass one testSkipped "minimal"Revert to the smallest change; let the next test drive the rest
Refactor changed behaviourRefactor and feature mixedSplit: commit the refactor under green first, then a new RED
Evidence report says PASS for an unrun testFabricated evidenceRerun and paste the real output, or mark it "not run"

Related skills

  • opm:verification-before-completion - the final gate before claiming the work is done.
  • opm:executing-plans - how TDD tasks fit inside a plan's task loop.
  • opm:compound-learnings - capture a surprising root cause after the bug is fixed.
<!-- Adapted from affaan-m/ecc (MIT) -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.