360 Secure SkillHub
360 安全技能中心

Spec Coding

提供小型/中型/大型三档 spec-first 开发流程:澄清需求并撰写 requirements/design/tasks/特性规格,按任务从规格生成代码与测试,做静态审查并运行测试验证,处理 [SPEC-GAP],最后在改代码前先更新规格以保持规格与代码同步。

xhuaustc
xhuaustc
热度 22.58
最近更新 2026-03-19 10:51:53
分类:开发依赖:代码执行 / 读写文件 / 内部调用大模型应用场景:代码生成 / 代码审查 / 工作流 / 任务管理

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add speccoding
Metadata
name
spec-coding
description
Structured spec-first development workflow: clarify requirements, author spec documents (requirements/design/tasks), generate code from spec, verify with real tests, and iterate while keeping spec and code in sync. Use when user wants to build a feature or system with a spec-first approach, mentions "spec coding", "spec-driven development", or asks to write specs before coding.

Spec Coding Workflow

Write specs first, then generate code. 5 phases, each producing artifacts that feed the next.

When to Use

Trigger conditions:

  • User mentions "spec coding", "spec-first", "spec-driven development"
  • User asks to write specs / requirements / design docs before implementation
  • User mentions phase keywords: "clarify requirements", "write a spec", "generate from spec"

Complexity triage — choose the right track:

Track When Phases Artifacts
Small Single endpoint, field addition, < 1 hr Spec (lite) → Generate → Verify spec_xxx.md only
Medium Single feature, 1–4 hrs, 1–3 modules Clarify (brief) → Spec → Generate → Verify spec_xxx.md + tasks.md
Large Multi-module, > 4 hrs, or new system Full 5-phase workflow All spec files

Ask the user which track fits, or infer from the scope of their request.

Full workflow phases (Large track):

  1. Clarify & Scope — requirements clarification + structured decomposition
  2. Spec — author spec documents (requirements.md / design.md / tasks.md / spec_xxx.md)
  3. Generate — produce code and tests from spec
  4. Verify — static review + run tests against spec
  5. Iterate — evolve spec and code together

Small track shortcut: Skip Phase 1. Write a single spec_xxx.md (Interface + Business Rules + Test Points only), then go straight to Generate → Verify.

Medium track shortcut: Phase 1 is a brief bullet-point confirmation (no full requirements.md). Phase 2 produces tasks.md + spec_xxx.md only (skip design.md unless architecture decisions are needed).

Mid-project entry: If the user already has spec files or an existing codebase, read them first. Validate existing artifacts against the expected format, then confirm which phase to start from.

File Organization

All spec artifacts go in a specs/ directory at the project root:

specs/
├── requirements.md
├── design.md
├── tasks.md
└── spec_<feature_name>.md   (one per feature)

Phase 0 (Optional): Codebase Scan

For existing codebases, run before Phase 1:

  1. Read dependency files (package.json, requirements.txt, go.mod, etc.) to detect tech stack.
  2. List directory tree to understand project structure.
  3. Identify existing interfaces, data models, and conventions.
  4. Summarize findings — this becomes context for all subsequent phases.

Phase 1: Clarify & Scope

Goal: Turn informal requirements into a confirmed, structured requirements.md.

Constraints: Do NOT write any code. Only ask questions and produce documents.

Step 1: Interactive Clarification

Ask the user to dump raw requirements. Then engage in Q&A:

  • Summarize understood goals (3–5 bullet points).
  • List ambiguities with suggested options for each.
  • Suggest constraints the user may not have considered.

Iterate until the user confirms understanding is accurate.

Step 2: Structured Requirements

Once clarified, produce specs/requirements.md containing:

  • Background & Objectives
  • User Roles & Use Cases
  • Functional Requirements (grouped by module, numbered FR-001, FR-002, ...)
  • Non-Functional Requirements (performance, availability, security, observability)
  • Out of Scope (explicitly list what will NOT be built)
  • Existing Architecture (if Phase 0 was run — what exists, what's new, what's modified)

Exit condition: User approves requirements.md.

Phase 2: Spec

Goal: Produce spec documents that directly drive code generation.

The "spec trio" + per-feature specs:

2a: Technical Design → specs/design.md

Based on requirements.md, produce:

  1. Architecture overview (tech stack, layers, services)
  2. Core module breakdown with responsibilities and dependency directions
  3. Key data models (domain objects only)
  4. Key interfaces & interaction flows
  5. Cross-cutting concerns:
    • Error handling strategy (classification, propagation, retry)
    • Authentication & authorization model
    • Observability (logging, metrics, tracing)
    • Deployment & configuration (topology, env management, data migration)
  6. NFR fulfillment matrix — how each NFR from requirements is satisfied by design
  7. Key architecture decisions (ADR format: context → options → decision → consequences)

For existing codebases: include an "Existing Architecture" section marking what's new vs. modified.

Skip items 5–7 on the Small track. On Medium track, include only the items relevant to the feature.

Exit condition: User approves design.md.

2b: Task Breakdown → specs/tasks.md

Based on design.md, produce a task table:

Task ID Name Module Dependencies Related Spec Acceptance Criteria AI-Automatable
TASK-001 ... ... — spec_xxx.md ... Yes/No
  • Target granularity: 30–90 minutes per task.
  • Related Spec column links each task to its spec_xxx.md.

Exit condition: User approves tasks.md.

2c: Feature Spec → specs/spec_<feature>.md

For each feature or module, produce a feature spec:

  1. Feature Description & Use Cases
  2. Interface Definition — path, method, params (with types & constraints), response structure, error codes
  3. Data Model & Persistence — tables / collections / fields
  4. Business Rules & Edge Cases — including error scenarios
  5. Test Points — use this format:
TP-ID Category Input Expected Output Notes
TP-001 Normal valid input example expected result
TP-002 Error invalid input example error response
TP-003 Boundary edge case input expected behavior

Aim for 5–10 test points per feature covering normal / error / boundary.

Exit condition: User approves all spec files.

Phase 3: Generate

Goal: Produce implementation code + tests strictly based on the spec.

Spec adherence — tiered rules:

Tier Scope Rule
Strict Interfaces, data models, business rules Follow spec exactly. Do not change signatures, field names, or behavior.
Flexible Internal implementation (function names, code organization, logging, error messages) AI decides, but must note deviations in Human-review points.
SPEC-GAP Scenarios the spec doesn't cover (discovered during coding) Implement a reasonable solution, tag it [SPEC-GAP], and continue. Collect all gaps for batch review in Phase 4.

Never silently deviate from Strict-tier items. If a Strict item is wrong or incomplete, flag it and ask the user — but do not block on every minor gap.

Steps

  1. Scan project structure and tech stack (or use Phase 0 results).
  2. For each task in tasks.md, take its linked spec_xxx.md as input.
  3. Output per task:
    • File list (create vs. modify, with paths)
    • Implementation code
    • Tests derived from spec Test Points (TP-001 → test function)
    • Human-review points — Flexible-tier deviations + all [SPEC-GAP] items
  4. Tag generated code with task IDs in commit messages: feat(TASK-001): ...

For existing codebases: clearly distinguish "new file" vs. "modify existing file" and show diffs for modifications.

Phase 4: Verify

Goal: Confirm generated code satisfies the spec through both review and execution.

4a: Static Verification

Compare code against spec_xxx.md:

  • All business rules and edge cases covered?
  • Input/output matches spec interface definition?
  • Unhandled exception scenarios?

4b: Dynamic Verification

Run actual tests and checks:

  1. Execute test suite (e.g., pytest, npm test, go test)
  2. Run linter / type checker if available
  3. Compare test results against spec Test Points

4c: SPEC-GAP Review

Collect all [SPEC-GAP] items from Phase 3. For each gap:

  • Accept — the implementation is correct; update the spec to match.
  • Reject — the implementation is wrong; fix the code.
  • Defer — not critical now; add to backlog.

Output

  • Passed — items that satisfy the spec
  • Failed — items that deviate, with recommendation: fix spec or fix code
  • SPEC-GAP resolutions — accepted / rejected / deferred for each gap

Phase Transitions

  • All passed → proceed to next task or Phase 5 for iteration
  • Failed items → update spec (Phase 2) or fix code (Phase 3) → re-verify

Exit condition: All items pass, or user acknowledges remaining gaps.

Phase 5: Iterate / Refactor

Goal: Evolve the feature while keeping spec and code in sync.

Key rule: Always update the spec BEFORE updating the code.

Steps

  1. Take current spec, code overview, and new change request as input.
  2. Output:
    • Impact Analysis — which interfaces / data structures / modules are affected
    • Updated Spec — mark additions ([NEW]), modifications ([MODIFIED]), deprecations ([DEPRECATED])
    • Code Change List — files and locations to modify, with suggestions
    • Refactoring Advice — if original design cannot support the new requirement
  3. After spec update is approved, execute code changes (→ Phase 3) and verify (→ Phase 4).

Maintain a changelog at the top of each spec file:

## Changelog
| Date | Change | Reason |
|------|--------|--------|
| YYYY-MM-DD | Added field X to User model | FR-012 |

Cross-Phase Guidelines

  • No phase skipping: Do not generate code without a confirmed spec. Ask user for confirmation before advancing phases.
  • Spec-code traceability: Every code change traces to a spec item (TASK-ID + TP-ID); every spec item has corresponding code and tests.
  • Phase status: At each phase end, summarize completion and suggest next entry point.
  • Context management: Keep each spec file under ~300 lines. In Phase 3, feed only the relevant spec_xxx.md + related design.md sections — not all spec files at once. For large projects, start each new session with a brief context summary of completed phases.

Spec Quality Checklist

Before leaving Phase 2, verify specs meet "good enough" standard:

  • Every interface has explicit input/output types
  • Every business rule has at least one corresponding test point
  • Specs describe what, not how (no implementation details)
  • Each spec file is self-contained enough to drive code generation independently
  • Edge cases and error scenarios are explicitly listed, not implied

Templates

For spec file templates and example outputs, see templates.md.