openspec-plus-tdd

openspec-plus-tdd 是在实现 OpenSpec 变更任务时必须激活的技能。触发条件包括 openspec-plus-apply 处于活动状态、/opsx-apply 正在运行、用户正在实现 OpenSpec 变更任务、由 openspec-plus-apply 派发的实现子代理开始工作,或用户发起与为变更进行 TDD、实现变更任务或为规范场景编写测试等相关的调用。该技能要求在为实现 OpenSpec 变更编写任何生产代码之前加载,并对每个测试(验收测试、单元测试、边缘情况测试和辅助测试)强制执行严格的 RED-GREEN-REFACTOR 流程,且不允许在没有失败测试的情况下编写生产代码;spec.md 中的 Gherkin 场景为验收测试的权威来源,每个场景至少对应一个测试,鼓励编写额外的单元和边缘情况测试并遵循相同流程。

仓库最近推送
GitHub Stars
219
Forks
13
Issues / PRs
2

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "openspec-plus-tdd":https://skillpi.com/zh/skills/deepskill-9e2762250a16dad3e48417a72361947b09da3df352d7b4009804fbf11e549642。安装前核对上游来源和版本:https://github.com/sudokar/openspec-plus。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

openspec-plus-tdd 是在实现 OpenSpec 变更任务时必须激活的技能。触发条件包括 openspec-plus-apply 处于活动状态、/opsx-apply 正在运行、用户正在实现 OpenSpec 变更任务、由 openspec-plus-apply 派发的实现子代理开始工作,或用户发起与为变更进行 TDD、实现变更任务或为规范场景编写测试等相关的调用。该技能要求在为实现 OpenSpec 变更编写任何生产代码之前加载,并对每个测试(验收测试、单元测试、边缘情况测试和辅助测试)强制执行严格的 RED-GREEN-REFACTOR 流程,且不允许在没有失败测试的情况下编写生产代码;spec.md 中的 Gherkin 场景为验收测试的权威来源,每个场景至少对应一个测试,鼓励编写额外的单元和边缘情况测试并遵循相同流程。

0 下载

介绍来源: third_party · sudokar · 1.6.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: openspec-plus-tdd
description: "MANDATORY skill that activates whenever code is written to implement an OpenSpec change task. Triggers: openspec-plus-apply is active, /opsx-apply is running, the user is implementing tasks from an OpenSpec change, an implementer subagent dispatched by openspec-plus-apply is starting work, or the user invokes phrases like 'TDD for the change', 'implementing change tasks', or 'writing tests for spec scenarios'. Load before any production code is written for an OpenSpec change. Enforces strict RED-GREEN-REFACTOR per test (any test — acceptance, unit, edge case, helper). Iron Law: NO PRODUCTION CODE WITHOUT A FAILING TEST. Gherkin scenarios in spec.md are the canonical source for acceptance tests (every scenario MUST become at least one test); additional unit, edge-case, and helper tests are encouraged and follow the same per-test cycle."
metadata:
  version: 1.6.1
  priority: high
  disable-user-invocation: true

OpenSpec Plus TDD

Mission

Strict RED-GREEN-REFACTOR per test for OpenSpec change implementation. Every test — whether derived from a Gherkin scenario relevant to the slice in spec.md, written for a unit, edge case, helper, or error path — goes through its own atomic cycle before the next test begins. Production code exists only to make a previously-failing test pass. Surgical changes, simplicity first, no speculative abstractions, every changed line traces to a slice task.

Gherkin scenarios in spec.md are the canonical source for acceptance tests: every scenario relevant to the slice MUST become at least one test. The implementer is encouraged to add additional tests — unit tests for individual functions, edge-case tests, helper tests, error-path tests — when fast-feedback granularity is valuable. Every test follows the same cycle.

Loaded by openspec-plus-apply (subagent prompt + inline mode) before any code is written.


RIGID. NEVER write production code before a test fails for the right reason. NEVER write tests for multiple cases before the first one is GREEN. NEVER skip the REFACTOR assessment. NEVER mark a task [x] while a relevant test is failing or skipped. NEVER add comments for non-complex logic. NEVER refactor code outside the slice. NEVER write any code (test or production) before reading the project's referenced coding/testing standards. NEVER ship without covering every Gherkin scenario in spec.md with at least one test. Letter and spirit are the same.

Red flags — STOP, you are about to violate this skill:

  • "I'll write the test after, it's faster"
  • "Too simple to need a test"
  • "Manually verified, that's enough"
  • "Gherkin scenario is vague, generic test is fine"
  • "Skip this failing test, circle back later"
  • "Mark .skip to unblock the slice"
  • "While I'm here, clean up the adjacent code"
  • "Add an interface in case we swap implementations"
  • "Short comment explains the obvious"
  • "Error handling for cases that can't happen"
  • "Test passed first run, must be right"
  • "Let me write tests for all the cases first, then implement"
  • "Test 1 done — I have a clear picture, let me write all the rest at once"
  • "I have a clear picture of all 5 cases — let me write them all"
  • "Writing one test at a time is slower"
  • "These cases are related, I'll batch them"
  • "The code I'm about to write covers test 2 anyway, no need to write its test separately first"
  • "Acceptance tests cover the happy path — skip the unit/edge tests"
  • "Scenarios covered, no need to add granular tests even though the helper has edge cases"
  • "Nothing to refactor, skip the assessment"
  • "I know the project conventions, no need to re-read AGENTS.md"
  • "AGENTS.md has many rules — I'll apply the ones that feel relevant"

None justify production code without a red test, ignored failures, speculative abstractions, comments on obvious code, or scope expansion.


The Iron Law

NO PRODUCTION CODE WITHOUT A FAILING TEST

Every test — acceptance, unit, edge case, helper, error path — must be observed to fail for the right reason before the production code that makes it pass is written. Test not observed to fail = test proves nothing. Code written first = delete it, start over. No exceptions without explicit user permission.

Mandatory Acceptance Coverage

Every Gherkin scenario relevant to the slice in spec.md MUST become at least one test. The scenario IS the acceptance contract; the test IS the verification. A slice cannot ship with an uncovered scenario, even if all other tests pass.

Encouraged Granular Coverage

Beyond acceptance tests, add unit/edge/helper/error tests when valuable (non-trivial branches, null/empty inputs, boundary values, error paths). Same RED-GREEN-REFACTOR cycle — no special handling regardless of test origin.


Inputs

  • Slice tasks (tasks.md)
  • Slice spec requirements + Gherkin scenarios (spec.md)
  • Slice design decisions (design.md)
  • Project standards (AGENTS.md / CLAUDE.md / GEMINI.md if in context)
  • Existing code in slice's affected files

NEVER read source outside the slice's affected files.


Workflow

Phase 0: Pre-RED — read project's coding/testing conventions; follow strictly

Phase 1+: Plan the test set for the slice:
  Mandatory:  one test per Gherkin scenario relevant to the slice in spec.md
  Encouraged: additional unit / edge-case / helper / error-path tests
              when fast-feedback granularity is valuable

Phase 2+: For each test, ONE AT A TIME (any test, in any order):
  Follow the Per-Test State Machine (digraph below) atomically.
  Do NOT begin the next test until the current one terminates at
  "Test Complete".

After all tests complete AND every Gherkin scenario relevant to the slice is covered, run
the slice's pre-mark gate.

Per-Test State Machine (MANDATORY)

Every test traverses this cycle end-to-end before work begins on the next. Atomic per test — no shortcuts, no batching, no skipping nodes. Applies to all test types (acceptance and granular).

Per-test cycle: START → RECORD STATE BEFORE (file path + count + names) → RED (write ONE failing test K) → VERIFY-RED (fails for expected reason? no → fix test, retry) → GREEN (minimum production code for K only) → VERIFY-GREEN (K passes, others green, output pristine? no → fix production code, retry) → REFACTOR ASSESS (needed? yes → act, verify green, revert if broken; no → record "not needed — reason") → RECORD STATE AFTER (count = previous + 1) → TEST K COMPLETE → return to START for K+1 (or end if all done AND all Gherkin scenarios covered).

The cycle forbids:

  • Starting test K+1 before K reaches COMPLETE
  • Skipping REFACTOR assessment — every test passes through it
  • Skipping state recording — audit trail is mandatory
  • Ending slice with uncovered Gherkin scenarios

Concrete Pattern: WRONG vs RIGHT

This is the single most-violated rule. Read both examples carefully.

WRONG — Batching (the model's training default)

Implementer opens empty test file.
Writes test 1, test 2, test 3, test 4, test 5 in one pass.
Runs tests — all 5 fail.
Writes production code covering all 5 cases in one pass.
Runs tests — all 5 pass.
Reports DONE.

This is NOT TDD. Each test passed immediately when production code arrived. You never observed test 1 failing in isolation. You never refactored after each green. You wrote the whole solution in your head and dumped it onto disk.

The end state (5 tests, 5 features) is identical to RIGHT — but the discipline is absent. The reviewer cannot tell from end state alone, but YOU know you batched.

RIGHT — One Test At A Time

State: 0 tests.

Test 1 (acceptance — Gherkin "valid login"):
  Write test 1 (1 test, 1 failing). RED: "expected `Email required`, got undefined" ✓
  Write minimum production. GREEN: 1 passing, pristine ✓
  Refactor: no duplication, names clear → "not needed."

Test 2 (acceptance — Gherkin "invalid password"):
  Write test 2 (2 tests, 1 failing). RED: "expected `Invalid password`, got `Internal error`" ✓
  Write minimum production. GREEN: 2 passing ✓
  Refactor: extracted `mapAuthError` helper. Tests green.

Test 3 (unit — edge case for `mapAuthError(null)`):
  Write test 3 (3 tests, 1 failing). RED: "expected `Invalid input`, got TypeError" ✓
  Add null guard. GREEN: 3 passing ✓. Refactor: not needed.

[repeat for each test...]

Tests 1-2: Gherkin scenarios (mandatory acceptance). Test 3: implementer-initiated edge case (granular). All follow the same per-test cycle.

If you find yourself thinking "I know all 5 cases, let me write them all at once" — STOP. That is the violation. Delete what you just wrote. Restart from test 1.

Why "I'll write all the tests, then implement" is wrong

  • Test 2 might pass immediately when you implement test 1 — you'd never know if test 2 actually tests what you think.
  • No checkpoint forces you to confront edge cases per test. Edge cases get glossed.
  • You miss refactor opportunities that emerge between tests.
  • The discipline is the value, not the end state.

Phase 0: Pre-RED — Read Referenced Conventions

Before ANY code (mandatory, once per slice):

  1. AGENTS.md / CLAUDE.md / GEMINI.md (or equivalents at project root, .claude/, .opencode/, docs/)
  2. Follow references inside those files to other docs (coding standards, testing conventions, patterns)
  3. Slice's affected files — absorb local style

These files are the contract — follow every documented rule strictly, end-to-end (no cherry-picking). Re-read per slice (files may have been updated). Do NOT proceed to Phase 1 before reading is done.


Phase 1: RED — Failing Test (One At A Time)

The test you write at this phase is one of two kinds:

1. Acceptance test — translated from a Gherkin scenario.

A Gherkin scenario in spec.md:

#### Scenario: User logs in with valid credentials
GIVEN a user account exists with email `alice@example.com` and password `correct-pw`
WHEN the user submits the login form with those credentials
THEN the response sets a session cookie
AND the user is redirected to `/dashboard`

Translate directly into one minimal acceptance test:

test('logs in with valid credentials', async () => {
  await createUser({ email: 'alice@example.com', password: 'correct-pw' });

  const response = await submitLogin({ email: 'alice@example.com', password: 'correct-pw' });

  expect(response.headers['set-cookie']).toMatch(/session=/);
  expect(response.status).toBe(302);
  expect(response.headers.location).toBe('/dashboard');
});

2. Granular test — implementer-initiated for a unit, edge case, helper, or error path

Example: while implementing the login above, the implementer factors out a mapAuthError helper. They add a unit test for it:

test('mapAuthError handles null input', () => {
  expect(() => mapAuthError(null)).toThrow('Invalid input');
});

This test was not derived from a Gherkin scenario — it was added because the helper's null case needs fast-feedback coverage. It follows the same cycle.

Rules (both kinds):

  • One test at a time — never batch. Test name describes behavior, not implementation.
  • Real code paths; mocks ONLY when dependency unavailable. Test the OUTCOME, not call sequence.
  • Acceptance: translate Gherkin faithfully. Granular: state the unit's contract explicitly.

Phase 2: VERIFY-RED — Watch It Fail Correctly

MANDATORY. NEVER SKIP.

Run the test. Confirm:

  1. Test FAILS (not errors, not passes).
  2. Failure message matches what scenario implies.
  3. Failure is because feature is missing — not typo, not missing import, not setup bug.

Test passes immediately → feature exists or test is wrong. Fix the test. Test errors → fix error, re-run until it fails for the expected reason.


Phase 3: GREEN — Minimum Production Code

Simplest code that passes the test.

  • No features beyond what the failing scenario requires
  • No abstractions for single-use code
  • No flexibility/configuration the scenario didn't ask for
  • No error handling for impossible cases
  • Match existing patterns

If 200 lines and 50 would do — rewrite.


Phase 4: VERIFY-GREEN — Watch It Pass

MANDATORY.

  1. Test passes.
  2. Other tests in the file still pass.
  3. Tests for slice's other scenarios still pass.
  4. Output pristine — no warnings, errors, deprecations.

Test fails → fix production code, NOT the test. Test is the source of truth. Unrelated tests fail → fix now, before next test.


Phase 5: REFACTOR — Mandatory Assessment, Conditional Action

REFACTOR is NOT optional. After every GREEN, you MUST perform an explicit refactor assessment.

5.1 Assessment (always)

Apply clean code principles, project conventions (from Phase 0 reading), and look for common code smells in the code introduced by this test's GREEN phase (within the slice's files only).

Answer in the report: Is refactoring needed? (yes/no with one-sentence reason)

If no → state explicitly: "Refactor assessment: no refactoring needed — code is minimal, clear, and non-duplicative." Then move to NEXT.

If yes → proceed to 5.2.

5.2 Action (only if assessment = yes)

Refactor respecting project conventions. Tests must stay green — run after every edit. NEVER add behavior, touch outside slice, or reformat adjacent code. If tests break → revert.

Record outcome (e.g., "Extracted parseAuthHeader helper; tests green" or "No refactoring needed — minimal, clear, non-duplicative").


Phase 6: NEXT — Only Now

Only after the current test's REFACTOR assessment is recorded, move to the next test. Return to Phase 1 RED with the next test (the next uncovered Gherkin scenario, OR the next implementer-initiated unit/edge/helper/error test).

NEVER skip ahead. NEVER write the next test while the current one is still in GREEN or REFACTOR phase.

The slice is done when:

  • Every Gherkin scenario in spec.md has at least one passing test (mandatory acceptance coverage), AND
  • Every test the implementer added (unit, edge, helper, error) is passing, AND
  • All tests went through the per-test cycle individually.

Implementation Principles (apply throughout)

Principle TDD application
Think Before Coding Read scenario or unit contract carefully. State assumptions. Ambiguous → ASK before writing the test.
Simplicity First One test at a time (acceptance OR granular). Minimum production change. No speculative abstractions.
Surgical Changes Every changed line traces to a slice task. Don't refactor adjacent code. Match existing style.
Goal-Driven Execution The current test (Gherkin scenario OR unit contract) IS the verifiable goal. Loop independently until the test passes.

Code Style Rules — Code As Documentation

Code explains itself through good names, small focused functions, and clear structure.

  • Self-documenting. Names describe intent. Functions do one thing. Structure makes flow obvious.
  • Comments only when: genuinely non-obvious algorithm, external-constraint workaround, or counter-intuitive tradeoff. Refactor before commenting — if better naming/structure removes the need, do that first.
  • Never: describe obvious behavior in comments; leave commented-out code, TODO, FIXME.
  • Testable (hard to test = hard to use), readable (one mental load per function), maintainable (one responsibility per file).

Verification Gates

Per-test: Pre-RED done ✓ RED observed ✓ GREEN passes + others green + pristine ✓ Minimum code ✓ No unnecessary comments ✓ No adjacent code touched ✓ REFACTOR assessed ✓ — Cannot check all? Restart from RED.

Per-slice: Every Gherkin scenario covered ✓ All tests pass ✓ Each test went through its own cycle (no batching) ✓


When Stuck

Symptom Cause Fix
Hard to write test Interface hard to use Simplify interface before writing test
Need to mock half the world Code too coupled Dependency injection or split unit
Test setup huge Coupling Extract helpers; still huge → simplify design
Scenario ambiguous Spec gap STOP. Ask user. Don't invent
Don't know what granular tests to add Just-write-tests trap Add tests for: non-trivial branches, null/empty inputs, boundary values, error paths the scenario doesn't cover. Skip if behavior is fully covered by acceptance test.
Test passes immediately Feature exists or test wrong Investigate; rewrite test
Can't make test fail right Test wrong Rewrite before any production code
Production code keeps growing Over-engineering What's the minimum that passes?

Anti-Patterns

NEVER: skip Pre-RED reading | batch tests | move to next test before current REFACTOR | skip REFACTOR assessment | production code before failing test | test after code works ("for coverage") | .skip/.todo/xtest/comment-out | suppress output | add comments on non-complex logic | leave TODO/FIXME/commented-out code | refactor adjacent code | features the test didn't request | abstractions for single use | error handling for untested cases | skip scenario tests | skip granular tests when edge cases exist | continue with failing tests | commit code.

"Just this once" → STOP. Restart from RED.


Integration With openspec-plus-apply

  • Subagent mode: implementer subagent uses skill tool to load this skill before any code; if unavailable, reads this SKILL.md directly from the skills directory. Each subagent loads fresh in isolated context.
  • Inline mode: main agent uses skill tool once at Phase 2 start; if unavailable, reads this SKILL.md directly from the skills directory. If already loaded in main agent context, reference instead of reload.

The slice's pre-mark gate (lint + format + tests + other on affected files) runs AFTER the TDD cycle completes for all tests AND every Gherkin scenario is covered. Gate failure → return to failing test's TDD cycle. Never bypass.


Success Criteria

Succeeds: Pre-RED done, every Gherkin scenario has a passing test, every test observed to fail before passing, full per-test cycle completed before starting next, REFACTOR assessed and recorded for each, minimal production code, pristine output, no unnecessary comments, no adjacent refactoring, gate clean.

Fails: Pre-RED skipped, batching, next test before current REFACTOR complete, REFACTOR assessment skipped, production code without red-then-green test, tests skipped/commented, comments on obvious code, adjacent code touched, speculative abstractions, scenario paraphrased instead of translated, uncovered scenarios.

版本历史

  1. v1.6.1 GitHub ↗
    原版更新说明

    ### Fixed - `openspec-plus-apply`: dispatch templates leaked the envelope wrapper (description/prompt framing) into the subagent's actual prompt text, which could cause a worker to attempt spawning its own subagent and fall back to a visible task-creation tool instead. Fixed by keeping only the literal prompt content inside the fence and adding an explicit "do this yourself, don't delegate" instruction to each template.

  2. v1.6.0 GitHub ↗
    原版更新说明

    ### Changed - Skills frontmatter restructured: `version`, `priority`, and `disable-user-invocation` moved under `metadata` section per [agentskills.io specification](https://agentskills.io/specification#skill-md-format) - All skill versions unified to `1.6.0` (release version) - Proposal skill auto-update check now uses GitHub Releases API (`/releases/latest`) instead of fetching the VERSION file — removes dependency on VERSION file location

  3. v1.5.0 GitHub ↗
    原版更新说明

    ### Added - New `openspec/.plus/config.yaml` — optional, project-level settings file, separate from `openspec/config.yaml`, installed/merged automatically by the install/update prompt. - `settings.questionMode: batch` — `openspec-plus-proposal`/`-design`/`-spec`/`-tasks` group each phase's discovery questions into as few question-tool rounds as possible instead of one at a time. Same real answers, no assumptions — fewer round trips for per-prompt-priced model providers, especially premium/high-tier models where round trips are expensive. Config-only, no conversational trigger. - `settings.autoUpdateCheck: false` — lets `openspec-plus-proposal` skip its weekly network version check + upgrade question entirely. - `settings.apply.executionMode` / `settings.apply.parallelism` — let `openspec-plus-apply` skip its Subagent-vs-Inline and parallel-dispatch questions when set.

当前收录版本

1.6.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • 为 OpenSpec 变更实现提供严格的 TDD 流程,确保每个测试都经过 RED-GREEN-REFACTOR 循环
  • 强制要求每个 Gherkin 场景至少对应一个验收测试,保障需求覆盖完整性
  • 适用于高频刚需场景:代码实现前的测试驱动开发,显著提升交付质量
触发精准85/100

待提升项

  • 触发词依赖平台特定术语 原报告严重程度:轻微

    触发条件中包含 openspec-plus-apply、/opsx-apply 等平台内部标识,可能限制通用性

    改进建议:可补充更通用的触发短语如 'start TDD cycle'、'begin test-driven development' 以扩大适用范围

亮点

  • 触发条件覆盖全面:包括子代理启动、用户显式调用、特定命令运行等多种场景
  • 明确列出了典型调用短语如 '为变更进行 TDD'、'实现变更任务',便于用户识别使用时机
结构规范90/100

待提升项

  • 文档长度接近上限 原报告严重程度:轻微

    SKILL.md 内容详实但篇幅较长,可能影响快速查阅效率

    改进建议:可考虑将部分详细说明(如反模式列表)移至独立文档并通过链接引用

亮点

  • Phase 划分清晰,包含 Pre-RED、RED、GREEN、REFACTOR 等完整阶段
  • 提供了具体的状态机图和 RIGHT/WRONG 对比示例,极大增强可操作性
  • frontmatter 完整,包含版本号、优先级等元数据
执行可靠80/100

待提升项

  • 依赖外部文件未做存在性校验 原报告严重程度:轻微

    流程强依赖 spec.md、tasks.md、AGENTS.md 等文件,但未说明缺失时的处理策略

    改进建议:建议增加文件缺失时的明确报错指引或默认行为说明

亮点

  • 每个测试都有完整的验证门控(VERIFY-RED、VERIFY-GREEN)
  • REFACTOR 阶段强制评估并记录结果,避免遗漏重构机会
  • 输出要求 'pristine',确保无警告/错误,提升交付质量
证据可验 (前四项均值)88/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。