From a4cb93993530dc45e4e4d2685e43e7f2169571c5 Mon Sep 17 00:00:00 2001 From: echoVic <137844255@qq.com> Date: Sun, 4 Jan 2026 21:02:27 +0800 Subject: [PATCH] feat: add spec-flow skill for structured development workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add spec-flow to .experimental folder - a structured development workflow that guides through four phases: Proposal → Requirements → Design → Tasks. Features: - Phase-by-phase confirmation workflow - EARS format for requirements - Multiple execution modes (Step/Batch/Phase) - Living documentation in .spec-flow/ directory Includes: - SKILL.md: Main skill instructions - LICENSE.txt: Apache 2.0 - references/: EARS format guide, workflow docs, task decomposition, examples - scripts/: init-spec-flow.sh, execute-task.sh, validate-spec-flow.py - templates/: proposal, requirements, design, tasks templates - templates/steering/: constitution, product, tech, structure templates Trigger phrases: 'spec-flow', 'spec mode', 'need a plan' --- skills/.experimental/spec-flow/LICENSE.txt | 202 +++++++++ skills/.experimental/spec-flow/SKILL.md | 386 ++++++++++++++++++ .../spec-flow/references/ears-format.md | 222 ++++++++++ .../references/examples/feature-example.md | 357 ++++++++++++++++ .../references/task-decomposition.md | 328 +++++++++++++++ .../spec-flow/references/workflow.md | 258 ++++++++++++ .../spec-flow/scripts/execute-task.sh | 249 +++++++++++ .../spec-flow/scripts/init-spec-flow.sh | 172 ++++++++ .../spec-flow/scripts/validate-spec-flow.py | 322 +++++++++++++++ .../spec-flow/templates/design.md.template | 268 ++++++++++++ .../spec-flow/templates/proposal.md.template | 89 ++++ .../templates/requirements.md.template | 126 ++++++ .../steering/constitution.md.template | 90 ++++ .../templates/steering/product.md.template | 105 +++++ .../templates/steering/structure.md.template | 200 +++++++++ .../templates/steering/tech.md.template | 151 +++++++ .../spec-flow/templates/tasks.md.template | 192 +++++++++ 17 files changed, 3717 insertions(+) create mode 100644 skills/.experimental/spec-flow/LICENSE.txt create mode 100644 skills/.experimental/spec-flow/SKILL.md create mode 100644 skills/.experimental/spec-flow/references/ears-format.md create mode 100644 skills/.experimental/spec-flow/references/examples/feature-example.md create mode 100644 skills/.experimental/spec-flow/references/task-decomposition.md create mode 100644 skills/.experimental/spec-flow/references/workflow.md create mode 100755 skills/.experimental/spec-flow/scripts/execute-task.sh create mode 100755 skills/.experimental/spec-flow/scripts/init-spec-flow.sh create mode 100755 skills/.experimental/spec-flow/scripts/validate-spec-flow.py create mode 100644 skills/.experimental/spec-flow/templates/design.md.template create mode 100644 skills/.experimental/spec-flow/templates/proposal.md.template create mode 100644 skills/.experimental/spec-flow/templates/requirements.md.template create mode 100644 skills/.experimental/spec-flow/templates/steering/constitution.md.template create mode 100644 skills/.experimental/spec-flow/templates/steering/product.md.template create mode 100644 skills/.experimental/spec-flow/templates/steering/structure.md.template create mode 100644 skills/.experimental/spec-flow/templates/steering/tech.md.template create mode 100644 skills/.experimental/spec-flow/templates/tasks.md.template diff --git a/skills/.experimental/spec-flow/LICENSE.txt b/skills/.experimental/spec-flow/LICENSE.txt new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/skills/.experimental/spec-flow/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/skills/.experimental/spec-flow/SKILL.md b/skills/.experimental/spec-flow/SKILL.md new file mode 100644 index 0000000..498106a --- /dev/null +++ b/skills/.experimental/spec-flow/SKILL.md @@ -0,0 +1,386 @@ +--- +name: spec-flow +description: Interactive spec-driven development workflow with phase-by-phase confirmation. Each phase waits for user confirmation before proceeding. Trigger phrases include "spec-flow", "spec mode", "need a plan", or "structured development". Creates .spec-flow/ directory with proposal, requirements, design, and tasks documents. +--- + +# Spec-Flow - Structured Development Workflow + +Structured workflow for complex feature development. Creates living documentation that guides implementation and serves as team reference. + +## ⚠️ Interaction Rules (MUST Follow) + +This skill uses a **phase-by-phase confirmation** workflow, ensuring users can review and adjust at each stage. + +### Core Principles + +1. **One phase at a time**: Only work on the current phase. NEVER generate documents for subsequent phases in advance. +2. **Mandatory confirmation**: After completing each phase, you MUST stop and wait for user confirmation. +3. **User-driven progression**: Only proceed to the next phase when user explicitly says "continue", "ok", "next", "looks good", "继续", "好", "下一步", etc. + +### Confirmation Template + +After completing each phase, you MUST use this format to request confirmation: + +``` +📋 **[Phase Name] Complete** + +Created `.spec-flow/active//.md` containing: +- [Key content summary] + +**Please review**: +1. [Review question]? +2. [Review question]? + +✅ Say "continue" to proceed to next phase +✏️ Tell me what to modify if needed +``` + +### ❌ Prohibited Behaviors + +- Generating multiple phase documents after user describes a feature +- Automatically proceeding to next phase without user confirmation +- Creating both proposal.md and requirements.md in one response +- Assuming user wants to skip confirmation for speed + +### ✅ Correct Flow Example + +``` +User: I want to implement user authentication +AI: [Creates only proposal.md] + confirmation prompt + +User: continue +AI: [Creates only requirements.md] + confirmation prompt + +User: looks good, next +AI: [Creates only design.md] + confirmation prompt + +User: continue +AI: [Creates only tasks.md] + confirmation prompt +``` + +### Fast Mode (Optional) + +If user explicitly requests to skip phase-by-phase confirmation: +- "generate all documents at once" +- "fast mode" +- "skip confirmations" + +Then you may generate all documents consecutively, but still request final overall confirmation. + +## Quick Start + +1. Initialize spec directory: Run `scripts/init-spec-flow.sh ` or manually create `.spec-flow/active//` +2. Copy templates from this skill's `templates/` directory +3. Follow four-phase workflow below +4. Archive completed specs to `.spec-flow/archive/` when done + +## Four-Phase Workflow + +### Phase 1: Proposal + +**Goal**: Define WHY this change is needed + +Create `.spec-flow/active//proposal.md` using `templates/proposal.md.template`: + +- **Background**: Context and motivation for the change +- **Goals**: What we want to achieve (with checkboxes) +- **Non-Goals**: What we explicitly won't do (reduces scope creep) +- **Scope**: In-scope vs out-of-scope boundaries +- **Risks**: Potential issues and mitigations +- **Open Questions**: Items needing clarification before proceeding + +**Exit Criteria**: Proposal reviewed, open questions resolved, scope agreed. + +**⏸️ Phase Checkpoint**: After creating proposal.md, ask user: +- Is the background accurate? +- Are goals clear and measurable? +- Is the scope boundary reasonable? +- Is risk assessment complete? + +→ Wait for user confirmation before proceeding to Requirements phase + +### Phase 2: Requirements + +**Goal**: Define WHAT the system should do + +Create `.spec-flow/active//requirements.md` using `templates/requirements.md.template`: + +**Use EARS Format** (see `references/ears-format.md`): +- **Ubiquitous**: "The system shall..." +- **Event-Driven**: "When [trigger], the system shall..." +- **State-Driven**: "While [state], the system shall..." +- **Unwanted Behavior**: "If [condition], then the system shall NOT..." + +**Include**: +- Functional requirements (FR-001, FR-002, ...) +- Non-functional requirements: Performance, Security, Reliability (NFR-001, ...) +- Acceptance criteria (AC-001, AC-002, ...) + +**Exit Criteria**: All requirements testable, acceptance criteria clear. + +**⏸️ Phase Checkpoint**: After creating requirements.md, ask user: +- Do functional requirements cover all use cases? +- Are non-functional requirements (performance/security/reliability) sufficient? +- Are acceptance criteria testable? + +→ Wait for user confirmation before proceeding to Design phase + +### Phase 3: Design + +**Goal**: Define HOW to implement + +Create `.spec-flow/active//design.md` using `templates/design.md.template`: + +- **Architecture Overview**: High-level component diagram (use Mermaid) +- **Component Design**: Responsibilities and interfaces for each component +- **API Design**: Endpoints, request/response schemas +- **Data Model**: Entity relationships (use Mermaid erDiagram) +- **Error Handling**: Error codes, descriptions, resolutions +- **Migration Plan**: Steps for data/schema migrations (if applicable) + +**Exit Criteria**: Design addresses all requirements, trade-offs documented. + +**⏸️ Phase Checkpoint**: After creating design.md, ask user: +- Does the architecture meet all requirements? +- Is the API design clear? +- Are there any missing edge cases? + +→ Wait for user confirmation before proceeding to Tasks phase + +### Phase 4: Tasks + +**Goal**: Break down into EXECUTABLE steps + +Create `.spec-flow/active//tasks.md` using `templates/tasks.md.template`: + +**Task Guidelines** (see `references/task-decomposition.md`): +- Each task completable in 1-2 tool calls +- Include complexity estimate: Low/Medium/High +- List affected files +- Define dependencies between tasks +- Group into phases: Setup → Implementation → Testing → Documentation + +**Progress Tracking**: +- ⏳ Pending → 🔄 In Progress → ✅ Done +- ❌ Blocked (add notes explaining blocker) + +**Exit Criteria**: All tasks completed, tests passing, documentation updated. + +**⏸️ Phase Checkpoint**: After creating tasks.md, ask user: +- Is the task granularity appropriate? +- Are dependencies correct? +- Ready to start implementation? + +→ Wait for user confirmation before starting implementation + +## ⚠️ Phase 5: Implementation + +**Goal**: Execute tasks according to tasks.md + +### 🎛️ Execution Modes + +Implementation supports **three execution modes**. Default is **Step Mode** unless user specifies otherwise. + +| Mode | Trigger Phrases | Behavior | +|------|-----------------|----------| +| **Step Mode** (Default) | "start implementation", "开始执行" | Execute ONE task, wait for confirmation, repeat | +| **Batch Mode** | "execute all", "一口气执行", "全部执行", "batch mode" | Execute ALL tasks consecutively, report at end | +| **Phase Mode** | "execute phase 1", "执行第一阶段", "execute setup" | Execute all tasks in ONE phase, then wait | + +### 📋 Step Mode (Default) + +Execute tasks one at a time with user confirmation between each. + +**When to use**: Complex tasks, need careful review, first time using spec-flow + +**Flow**: +``` +User: start implementation + +AI: 🔄 **Task T-001**: [description] + [Executes task] + ✅ Completed (1/10) + 👉 Say "continue" for next task + +User: continue + +AI: 🔄 **Task T-002**: [description] + ... +``` + +### ⚡ Batch Mode + +Execute all remaining tasks consecutively without waiting. + +**When to use**: Simple tasks, trusted plan, want speed + +**Trigger phrases**: +- "execute all tasks" / "全部执行" +- "batch mode" / "批量执行" +- "一口气执行完" +- "run all remaining tasks" + +**Flow**: +``` +User: execute all tasks + +AI: ⚡ **Batch Mode Activated** + + 🔄 T-001: [description] → ✅ + 🔄 T-002: [description] → ✅ + 🔄 T-003: [description] → ✅ + ... + + 📊 **Batch Complete**: 10/10 tasks done + + **Summary**: + - Files created: [list] + - Files modified: [list] + + ⚠️ Stopped early? Check error above. +``` + +**Batch Mode Rules**: +1. Still update tasks.md after each task +2. Stop immediately if any task fails or has error +3. Provide summary at the end +4. User can interrupt with "stop" or "暂停" + +### 📦 Phase Mode + +Execute all tasks within a specific phase, then wait for confirmation. + +**When to use**: Want to review after each phase (Setup → Core → Testing → Docs) + +**Trigger phrases**: +- "execute phase 1" / "执行第一阶段" +- "execute setup phase" / "执行 Setup" +- "run all setup tasks" + +**Flow**: +``` +User: execute setup phase + +AI: 📦 **Phase Mode: Setup** + + 🔄 T-001: [description] → ✅ + 🔄 T-002: [description] → ✅ + + ✅ **Setup Phase Complete** (2/10 total) + + **Next phase**: Core Implementation (T-010 to T-015) + 👉 Say "continue" or "execute next phase" +``` + +### 🚨 BEFORE Starting Any Task (All Modes) + +You MUST do these steps before executing: + +1. **Read tasks.md** - Get current task list and statuses +2. **Identify target tasks** - Based on mode (one task / all tasks / phase tasks) +3. **Check dependencies** - Ensure dependency tasks are completed (`- [x]`) +4. **Read design.md** - Review relevant design sections + +### ✅ REQUIRED Behaviors (All Modes) + +| Action | Step Mode | Batch Mode | Phase Mode | +|--------|-----------|------------|------------| +| Read tasks.md before starting | ✅ | ✅ | ✅ | +| Check dependencies | ✅ | ✅ | ✅ | +| Update `- [ ]` to `- [x]` after each task | ✅ | ✅ | ✅ | +| Show progress | After each | After each | After each | +| Wait for confirmation | After each task | After all done | After phase done | +| Stop on error | ✅ | ✅ | ✅ | + +### ❌ PROHIBITED Behaviors (All Modes) + +| Prohibited Action | Why It's Wrong | +|-------------------|----------------| +| Skip a task | Breaks dependency chain | +| Execute tasks out of order | Dependencies may not be met | +| Do work not in tasks.md | Scope creep, untracked changes | +| Forget to update tasks.md | Progress tracking inaccurate | +| Continue after error without user approval | May cause cascading failures | + +### 🛑 When to STOP (All Modes) + +Stop and ask user for guidance when: +- A task fails or produces errors +- Design is incomplete for current task +- A dependency is missing or blocked +- Task description is ambiguous +- Need a decision not covered in design.md + +## Directory Structure + +``` +project-root/ +└── .spec-flow/ + ├── steering/ # Global project context (optional) + │ ├── constitution.md # Project governance principles + │ ├── product.md # Product vision and goals + │ ├── tech.md # Technology constraints + │ └── structure.md # Code organization patterns + ├── active/ # Work in progress + │ └── / + │ ├── proposal.md + │ ├── requirements.md + │ ├── design.md + │ ├── tasks.md + │ └── .meta.json # Status, timestamps, owner + └── archive/ # Completed features (for reference) + └── / + └── ... +``` + +## Steering Documents (Optional) + +For larger projects, create `.spec-flow/steering/` documents to provide consistent context across all specs: + +| Document | Purpose | Template | +|----------|---------|----------| +| `constitution.md` | Project governance, decision-making principles | `templates/steering/constitution.md.template` | +| `product.md` | Product vision, target users, key metrics | `templates/steering/product.md.template` | +| `tech.md` | Tech stack, constraints, dependencies | `templates/steering/tech.md.template` | +| `structure.md` | Code organization, naming conventions | `templates/steering/structure.md.template` | + +## Workflow Tips + +### Phase Transitions + +| From | To | Condition | +|------|-----|-----------| +| Proposal | Requirements | Proposal approved, questions resolved | +| Requirements | Design | Requirements complete, testable | +| Requirements | Tasks | Simple feature, design implicit | +| Design | Tasks | Design approved | +| Tasks | Done | All tasks complete, archived | + +### When to Skip Phases + +- **Skip Design**: For simple features where architecture is obvious +- **Never Skip**: Proposal and Tasks (always clarify intent and break down work) + +### Best Practices + +1. **Keep specs updated**: Update status as work progresses +2. **Link to code**: Reference commits, PRs, file paths in tasks +3. **Archive completed specs**: Move to `.spec-flow/archive/` when done +4. **Review steering docs**: Reference them when writing new specs +5. **Validate completeness**: Run `scripts/validate-spec-flow.py` before implementation + +## References + +- **Complete workflow guide**: See `references/workflow.md` +- **EARS requirement format**: See `references/ears-format.md` +- **Task decomposition patterns**: See `references/task-decomposition.md` +- **Real-world examples**: See `references/examples/` + +## Compatibility + +This skill works with any AI agent that supports the Skills format: +- Claude Code (`~/.claude/skills/`) +- Blade (`~/.blade/skills/`) +- Other compatible agents + +The `.spec-flow/` directory is Git-friendly and can be committed with your project for team collaboration. diff --git a/skills/.experimental/spec-flow/references/ears-format.md b/skills/.experimental/spec-flow/references/ears-format.md new file mode 100644 index 0000000..7cd9c3e --- /dev/null +++ b/skills/.experimental/spec-flow/references/ears-format.md @@ -0,0 +1,222 @@ +# EARS Requirements Format + +EARS (Easy Approach to Requirements Syntax) is a structured template system for writing clear, unambiguous requirements. + +## Why EARS? + +Traditional requirements often suffer from: + +- Ambiguity ("the system should be fast") +- Incompleteness (missing edge cases) +- Untestability (no clear pass/fail criteria) + +EARS provides templates that force precision and completeness. + +## The Five EARS Patterns + +### 1. Ubiquitous Requirements + +**Template**: `The shall .` + +**Use When**: The requirement is always true, regardless of state or event. + +**Examples**: + +``` +✅ The system shall encrypt all passwords using bcrypt with cost factor 12. +✅ The API shall return JSON responses with Content-Type: application/json. +✅ The database shall maintain referential integrity. + +❌ The system should be secure. (too vague) +❌ The system shall be fast. (not measurable) +``` + +**Characteristics**: +- Always active +- No triggering event +- No precondition + +### 2. Event-Driven Requirements + +**Template**: `When , the shall .` + +**Use When**: The requirement responds to a specific event or trigger. + +**Examples**: + +``` +✅ When the user submits the login form, the system shall validate credentials within 200ms. +✅ When a payment fails, the system shall retry up to 3 times with exponential backoff. +✅ When file upload exceeds 10MB, the system shall reject with error code FILE_TOO_LARGE. + +❌ When the user clicks submit, validate the form. (missing system subject) +❌ When needed, the system shall scale. (vague trigger) +``` + +**Characteristics**: +- Triggered by specific event +- Clear cause-effect relationship +- Event should be observable + +### 3. State-Driven Requirements + +**Template**: `While , the shall .` + +**Use When**: The requirement is active only during a specific state. + +**Examples**: + +``` +✅ While the user is authenticated, the system shall include auth token in API headers. +✅ While maintenance mode is active, the system shall return 503 for all requests. +✅ While the cart contains items, the system shall display the checkout button. + +❌ While running, the system shall work correctly. (tautology) +❌ While active, send data. (vague state, missing system) +``` + +**Characteristics**: +- Active during a condition +- Continuous behavior +- State should be verifiable + +### 4. Unwanted Behavior (Negative Requirements) + +**Template**: `If , then the shall NOT .` + +**Use When**: Specifying what the system must prevent. + +**Examples**: + +``` +✅ If the session has expired, then the system shall NOT process the request. +✅ If the user lacks admin role, then the system shall NOT display admin controls. +✅ If the rate limit is exceeded, then the system shall NOT process additional requests. + +❌ The system shall not crash. (too broad) +❌ If something goes wrong, handle it. (vague) +``` + +**Characteristics**: +- Prevents undesired behavior +- Explicit condition +- Security/safety critical + +### 5. Optional Features + +**Template**: `Where , the shall .` + +**Use When**: The requirement depends on configuration or feature flags. + +**Examples**: + +``` +✅ Where dark mode is enabled, the system shall use the dark color palette. +✅ Where two-factor authentication is configured, the system shall require OTP. +✅ Where the enterprise plan is active, the system shall enable SSO integration. + +❌ Optionally support dark mode. (missing specific behavior) +❌ Where needed, do extra stuff. (vague) +``` + +**Characteristics**: +- Configuration-dependent +- Clear feature flag or option +- Behavior when enabled AND when disabled + +## Writing Good Requirements + +### Do's + +1. **Be Specific**: Include exact values, thresholds, timeouts +2. **Be Measurable**: Define how to verify the requirement +3. **One Action Per Requirement**: Don't combine multiple behaviors +4. **Use Active Voice**: "The system shall" not "It should be" +5. **Reference Standards**: Link to external specs when applicable + +### Don'ts + +1. **Avoid Ambiguous Words**: + - ❌ fast, quick, responsive → ✅ within 200ms + - ❌ user-friendly, intuitive → ✅ require no more than 3 clicks + - ❌ secure → ✅ encrypt with AES-256 + - ❌ reliable → ✅ 99.9% uptime + +2. **Avoid Compound Requirements**: + - ❌ "The system shall validate input AND store in database" + - ✅ Split into FR-001 (validate) and FR-002 (store) + +3. **Avoid Implementation Details**: + - ❌ "Using React, display the form" + - ✅ "The system shall display a form with fields: name, email, password" + +## Requirement Numbering + +### Functional Requirements + +``` +FR-001: Core feature 1 +FR-002: Core feature 2 +... +FR-010: Secondary feature 1 +FR-011: Secondary feature 2 +... +FR-100: Edge case handling +``` + +### Non-Functional Requirements + +``` +NFR-001: Performance requirement 1 +NFR-010: Security requirement 1 +NFR-020: Reliability requirement 1 +NFR-030: Scalability requirement 1 +``` + +## Traceability + +Every requirement should be traceable to: + +1. **Source**: Why does this requirement exist? +2. **Acceptance Criteria**: How do we verify it? +3. **Test Case**: What test validates it? +4. **Implementation**: Which code implements it? + +### Example Traceability Matrix + +| Req ID | Description | AC | Test | Code | +|--------|-------------|-----|------|------| +| FR-001 | Login validation | AC-001 | TC-001 | `auth/login.ts` | +| FR-002 | Session management | AC-002 | TC-002 | `auth/session.ts` | +| NFR-001 | Response time | AC-010 | TC-010 | N/A (infra) | + +## Acceptance Criteria Format + +Use Given-When-Then format: + +``` +AC-001: Login Validation +Given a user with valid credentials +When they submit the login form +Then the system returns a valid session token within 200ms +``` + +## Common Mistakes and Fixes + +| Mistake | Example | Fix | +|---------|---------|-----| +| Vague | "Handle errors gracefully" | "When API returns 500, display error message and retry button" | +| Compound | "Validate and save data" | Split into two requirements | +| Implementation | "Use PostgreSQL" | "Store data persistently with ACID guarantees" | +| Untestable | "Be user-friendly" | "Complete checkout in ≤3 steps" | +| Missing subject | "Should validate input" | "The system shall validate input" | + +## Templates Quick Reference + +``` +UBIQUITOUS: The shall . +EVENT-DRIVEN: When , the shall . +STATE-DRIVEN: While , the shall . +UNWANTED: If , then the shall NOT . +OPTIONAL: Where , the shall . +``` diff --git a/skills/.experimental/spec-flow/references/examples/feature-example.md b/skills/.experimental/spec-flow/references/examples/feature-example.md new file mode 100644 index 0000000..bff44f8 --- /dev/null +++ b/skills/.experimental/spec-flow/references/examples/feature-example.md @@ -0,0 +1,357 @@ +# Example: User Authentication Feature + +This example demonstrates a complete spec for adding user authentication. + +--- + +## Proposal (proposal.md) + +```markdown +# User Authentication - Proposal + +> **Status**: Approved +> **Author**: Alice Chen +> **Created**: 2024-01-10 +> **Last Updated**: 2024-01-12 + +## Background + +Currently, our application has no user authentication. All features are +publicly accessible. As we add user-specific features (saved preferences, +personal data), we need a way to identify and authenticate users. + +## Goals + +- [ ] Users can create accounts with email/password +- [ ] Users can log in and maintain sessions +- [ ] Protected routes require authentication +- [ ] Sessions persist across browser restarts + +## Non-Goals + +- Social login (Google, GitHub) - future iteration +- Two-factor authentication - future iteration +- Password-less login - not planned +- Enterprise SSO - separate project + +## Scope + +### In Scope + +- User registration with email/password +- Login/logout functionality +- Session management with JWT +- Password reset via email +- Protected route middleware + +### Out of Scope + +- User profile management +- Role-based access control +- Admin user management + +## Risks and Mitigations + +| Risk | Likelihood | Impact | Mitigation | +|------|------------|--------|------------| +| Security vulnerabilities | Medium | High | Use battle-tested libraries, security review | +| Password data breach | Low | High | Bcrypt hashing, secure storage | +| Session hijacking | Low | Medium | HTTP-only cookies, short expiry | + +## Open Questions + +- [x] Which JWT library? → Resolved: jose +- [x] Session duration? → Resolved: 7 days, refresh on activity +``` + +--- + +## Requirements (requirements.md) + +```markdown +# User Authentication - Requirements + +> **Status**: Approved +> **Proposal**: [proposal.md](./proposal.md) + +## Functional Requirements + +### Registration + +- **FR-001**: When a user submits the registration form with valid email and + password, the system shall create a new user account. +- **FR-002**: When registration email already exists, the system shall reject + with error code EMAIL_EXISTS. +- **FR-003**: The system shall validate passwords have minimum 8 characters, + 1 uppercase, 1 lowercase, and 1 number. + +### Login + +- **FR-010**: When a user submits valid credentials, the system shall return + a JWT access token and set HTTP-only refresh cookie. +- **FR-011**: When credentials are invalid, the system shall return 401 with + error code INVALID_CREDENTIALS. +- **FR-012**: If account is locked, then the system shall NOT authenticate + and return error code ACCOUNT_LOCKED. + +### Session + +- **FR-020**: While user has valid session, the system shall include user ID + in request context. +- **FR-021**: When access token expires but refresh token is valid, the + system shall issue new access token automatically. + +### Logout + +- **FR-030**: When user requests logout, the system shall invalidate the + refresh token and clear cookies. + +## Non-Functional Requirements + +### Performance + +- **NFR-001**: The login endpoint shall respond within 500ms for p99. +- **NFR-002**: Token validation shall complete within 10ms. + +### Security + +- **NFR-010**: The system shall hash passwords with bcrypt cost factor 12. +- **NFR-011**: The system shall NOT log passwords or tokens in any logs. +- **NFR-012**: Access tokens shall expire after 15 minutes. +- **NFR-013**: Refresh tokens shall expire after 7 days. + +## Acceptance Criteria + +- [ ] **AC-001**: Given valid email/password, when registering, then account + is created and user can log in. +- [ ] **AC-002**: Given existing email, when registering, then receive 409 + with EMAIL_EXISTS error. +- [ ] **AC-010**: Given valid credentials, when logging in, then receive JWT + and can access protected routes. +- [ ] **AC-011**: Given invalid credentials, when logging in, then receive + 401 error. +- [ ] **AC-020**: Given expired access token with valid refresh, when + accessing protected route, then token refreshes automatically. +``` + +--- + +## Design (design.md) + +```markdown +# User Authentication - Design + +> **Status**: Approved +> **Requirements**: [requirements.md](./requirements.md) + +## Architecture Overview + +```mermaid +graph TD + Client[Client] --> API[API Gateway] + API --> AuthService[Auth Service] + AuthService --> UserDB[(User DB)] + AuthService --> TokenStore[(Token Store)] +``` + +## API Design + +### POST /api/auth/register + +**Request**: +```json +{ + "email": "user@example.com", + "password": "SecurePass123" +} +``` + +**Response (201)**: +```json +{ + "user": { "id": "uuid", "email": "user@example.com" }, + "accessToken": "jwt..." +} +``` + +### POST /api/auth/login + +**Request**: +```json +{ + "email": "user@example.com", + "password": "SecurePass123" +} +``` + +**Response (200)**: +```json +{ + "user": { "id": "uuid", "email": "user@example.com" }, + "accessToken": "jwt..." +} +``` ++ Set-Cookie: refreshToken=...; HttpOnly; Secure + +### POST /api/auth/logout + +**Response (200)**: Empty + Clear-Cookie + +## Data Model + +```mermaid +erDiagram + User { + uuid id PK + string email UK + string password_hash + boolean is_locked + datetime created_at + datetime updated_at + } + RefreshToken { + uuid id PK + uuid user_id FK + string token_hash + datetime expires_at + datetime created_at + } + User ||--o{ RefreshToken : has +``` + +## Error Codes + +| Code | HTTP | Description | +|------|------|-------------| +| EMAIL_EXISTS | 409 | Email already registered | +| INVALID_CREDENTIALS | 401 | Wrong email or password | +| ACCOUNT_LOCKED | 403 | Account is locked | +| TOKEN_EXPIRED | 401 | Token has expired | +| INVALID_TOKEN | 401 | Token is malformed | +``` + +--- + +## Tasks (tasks.md) + +```markdown +# User Authentication - Tasks + +> **Status**: In Progress +> **Started**: 2024-01-15 +> **Target**: 2024-01-22 + +## Summary + +| Phase | Tasks | Completed | Progress | +|-------|-------|-----------|----------| +| Setup | 3 | 3 | 100% | +| Implementation | 5 | 2 | 40% | +| Testing | 3 | 0 | 0% | +| Documentation | 2 | 0 | 0% | +| **Total** | **13** | **5** | **38%** | + +## Task Breakdown + +### Phase 1: Setup + +- [x] **T-001**: Add auth dependencies (bcrypt, jose) + - Complexity: Low + - Files: package.json + - Dependencies: None + +- [x] **T-002**: Create User model and migration + - Complexity: Medium + - Files: src/models/user.ts, migrations/ + - Dependencies: T-001 + +- [x] **T-003**: Create RefreshToken model + - Complexity: Low + - Files: src/models/refreshToken.ts + - Dependencies: T-002 + +### Phase 2: Implementation + +- [x] **T-010**: Implement password hashing service + - Complexity: Low + - Files: src/services/passwordService.ts + - Dependencies: T-001 + +- [x] **T-011**: Implement JWT service + - Complexity: Medium + - Files: src/services/tokenService.ts + - Dependencies: T-001 + +- [ ] **T-012**: Implement auth service (register/login/logout) + - Complexity: High + - Files: src/services/authService.ts + - Dependencies: T-010, T-011 + - **Status**: 🔄 In Progress + +- [ ] **T-013**: Implement auth routes + - Complexity: Medium + - Files: src/routes/auth.ts + - Dependencies: T-012 + +- [ ] **T-014**: Implement auth middleware + - Complexity: Medium + - Files: src/middleware/auth.ts + - Dependencies: T-011 + +### Phase 3: Testing + +- [ ] **T-030**: Unit tests for services + - Complexity: Medium + - Files: tests/unit/auth/ + - Dependencies: T-012 + +- [ ] **T-031**: Integration tests for auth flow + - Complexity: Medium + - Files: tests/integration/auth.test.ts + - Dependencies: T-013, T-014 + +- [ ] **T-032**: Security testing + - Complexity: High + - Files: tests/security/auth.test.ts + - Dependencies: T-031 + +### Phase 4: Documentation + +- [ ] **T-040**: API documentation + - Complexity: Low + - Files: docs/api/auth.md + - Dependencies: T-013 + +- [ ] **T-041**: Update security docs + - Complexity: Low + - Files: docs/security.md + - Dependencies: T-032 + +## Progress Tracking + +| Task | Status | Started | Completed | +|------|--------|---------|-----------| +| T-001 | ✅ Done | 2024-01-15 | 2024-01-15 | +| T-002 | ✅ Done | 2024-01-15 | 2024-01-15 | +| T-003 | ✅ Done | 2024-01-15 | 2024-01-15 | +| T-010 | ✅ Done | 2024-01-16 | 2024-01-16 | +| T-011 | ✅ Done | 2024-01-16 | 2024-01-16 | +| T-012 | 🔄 In Progress | 2024-01-17 | | +| T-013 | ⏳ Pending | | | +| T-014 | ⏳ Pending | | | +| T-030 | ⏳ Pending | | | +| T-031 | ⏳ Pending | | | +| T-032 | ⏳ Pending | | | +| T-040 | ⏳ Pending | | | +| T-041 | ⏳ Pending | | | +``` + +--- + +This example demonstrates: + +1. **Clear progression** from proposal → requirements → design → tasks +2. **Traceability** between documents (links, requirement IDs) +3. **EARS format** for requirements +4. **Mermaid diagrams** for visual design +5. **Task tracking** with status and progress diff --git a/skills/.experimental/spec-flow/references/task-decomposition.md b/skills/.experimental/spec-flow/references/task-decomposition.md new file mode 100644 index 0000000..49ea00d --- /dev/null +++ b/skills/.experimental/spec-flow/references/task-decomposition.md @@ -0,0 +1,328 @@ +# Task Decomposition Best Practices + +This guide covers how to break down work into effective, executable tasks. + +## Why Decompose Tasks? + +1. **Clarity**: Each task has a single, clear objective +2. **Progress Tracking**: Visible progress motivates and informs +3. **Parallelization**: Independent tasks can be done concurrently +4. **Risk Management**: Smaller tasks fail faster, recover easier +5. **AI Compatibility**: Smaller tasks are easier for AI agents to execute + +## The INVEST Criteria + +Good tasks follow INVEST: + +| Criteria | Description | Example | +|----------|-------------|---------| +| **I**ndependent | Minimize dependencies | "Add User model" not "Add all models" | +| **N**egotiable | Details can be discussed | "Display user info" vs "Use Card component at 320px" | +| **V**aluable | Delivers value | "Add login endpoint" not "Rename internal variable" | +| **E**stimable | Can estimate effort | "Add form validation" not "Improve UX" | +| **S**mall | Completable quickly | "Add name field" not "Build entire form" | +| **T**estable | Has verification | "Returns 200 with user data" | + +## Task Size Guidelines + +### Ideal Task Size + +- **Time**: 15-60 minutes of focused work +- **Tool Calls**: 1-3 tool invocations +- **Changes**: 1-3 files modified +- **Complexity**: Single concept or change + +### Signs Task is Too Large + +- ❌ Estimate says "High" complexity +- ❌ Affects 5+ files +- ❌ Contains "and" in description +- ❌ Multiple acceptance criteria +- ❌ Can't explain in one sentence + +### Signs Task is Too Small + +- ❌ Takes <5 minutes +- ❌ Just renaming/moving +- ❌ No testable outcome +- ❌ Could be combined with related task + +## Task Phases + +Organize tasks into logical phases: + +### Phase 1: Setup + +Foundation work that enables other tasks. + +``` +T-001: Create directory structure + - Complexity: Low + - Files: N/A (new directories) + - Dependencies: None + +T-002: Add required dependencies + - Complexity: Low + - Files: package.json + - Dependencies: T-001 + +T-003: Configure environment + - Complexity: Low + - Files: .env.example, config.ts + - Dependencies: T-002 +``` + +### Phase 2: Core Implementation + +Main feature development. + +``` +T-010: Implement data model + - Complexity: Medium + - Files: src/models/user.ts + - Dependencies: T-002 + +T-011: Implement service layer + - Complexity: Medium + - Files: src/services/userService.ts + - Dependencies: T-010 + +T-012: Implement API endpoints + - Complexity: Medium + - Files: src/routes/users.ts + - Dependencies: T-011 +``` + +### Phase 3: Integration + +Connecting components together. + +``` +T-020: Wire service to routes + - Complexity: Low + - Files: src/app.ts + - Dependencies: T-011, T-012 + +T-021: Add middleware + - Complexity: Medium + - Files: src/middleware/auth.ts + - Dependencies: T-020 +``` + +### Phase 4: Testing + +Verification and validation. + +``` +T-030: Write unit tests + - Complexity: Medium + - Files: tests/unit/userService.test.ts + - Dependencies: T-011 + +T-031: Write integration tests + - Complexity: Medium + - Files: tests/integration/users.test.ts + - Dependencies: T-020 + +T-032: Manual QA testing + - Complexity: Low + - Files: N/A + - Dependencies: T-031 +``` + +### Phase 5: Documentation + +Finishing touches. + +``` +T-040: Update API docs + - Complexity: Low + - Files: docs/api/users.md + - Dependencies: T-012 + +T-041: Update changelog + - Complexity: Low + - Files: CHANGELOG.md + - Dependencies: T-040 +``` + +## Dependency Management + +### Dependency Types + +1. **Hard Dependency**: Must complete before starting + - T-011 requires T-010 (service needs model) + +2. **Soft Dependency**: Preferred order, but can parallel + - T-030 and T-031 (can write tests simultaneously) + +3. **No Dependency**: Fully independent + - T-040 and T-041 (different docs, same phase) + +### Minimizing Dependencies + +- **Interface First**: Define interfaces before implementations +- **Mock Dependencies**: Use stubs to unblock parallel work +- **Vertical Slices**: Complete one feature end-to-end + +### Dependency Graph + +```mermaid +graph TD + T001[T-001: Setup] --> T002[T-002: Dependencies] + T002 --> T010[T-010: Data Model] + T010 --> T011[T-011: Service] + T010 --> T030[T-030: Unit Tests] + T011 --> T012[T-012: API] + T011 --> T020[T-020: Integration] + T012 --> T020 + T020 --> T031[T-031: Integration Tests] + T031 --> T032[T-032: QA] + T012 --> T040[T-040: API Docs] + T040 --> T041[T-041: Changelog] +``` + +## Complexity Estimation + +### Low Complexity + +- Single file change +- Well-understood pattern +- No external dependencies +- <30 minutes + +**Examples**: +- Add a field to existing model +- Create configuration file +- Write simple unit test + +### Medium Complexity + +- 2-4 file changes +- Some decision-making +- Minor external dependencies +- 30-60 minutes + +**Examples**: +- Implement new API endpoint +- Add validation logic +- Write integration test + +### High Complexity + +- 5+ file changes +- Significant decision-making +- External dependencies +- >60 minutes + +**Examples**: +- Implement authentication flow +- Add new database table with migrations +- Complex business logic + +**Note**: If a task is "High" complexity, consider breaking it down further. + +## Task Description Format + +### Good Task Description + +``` +T-010: Implement User data model with TypeScript types and validation + +Complexity: Medium +Files: + - src/models/user.ts (create) + - src/types/user.ts (create) +Dependencies: T-002 + +Acceptance Criteria: +- User model has id, email, name, createdAt, updatedAt fields +- Email field has format validation +- TypeScript types exported for use by services + +Notes: +- Follow existing model patterns in src/models/ +- Use Zod for runtime validation +``` + +### Poor Task Description + +``` +T-010: Add user stuff + +Complexity: High +Files: ??? +Dependencies: ??? +``` + +## Handling Blockers + +### When Blocked + +1. **Document immediately**: Add to blocker table in tasks.md +2. **Identify resolution owner**: Who can unblock? +3. **Set deadline**: When do we need resolution? +4. **Find alternatives**: Can we work around it? + +### Blocker Table + +| Blocker | Blocking | Raised | Owner | Status | Resolution | +|---------|----------|--------|-------|--------|------------| +| API spec unclear | T-012 | 2024-01-15 | @bob | Open | Meeting scheduled | +| Dependency issue | T-002 | 2024-01-14 | @alice | Resolved | Used alternative lib | + +## Progress Updates + +### Update Frequency + +- **Pending → In Progress**: When starting task +- **In Progress → Done**: When complete and verified +- **Any → Blocked**: As soon as blocked +- **End of day**: Update all active tasks + +### Status Transitions + +``` +⏳ Pending + ↓ start +🔄 In Progress + ↓ complete ↓ block +✅ Done ❌ Blocked + ↓ unblock + 🔄 In Progress +``` + +## AI Agent Integration + +### Effective Task Prompts + +``` +Task: T-011 - Implement UserService + +Context: +- User model exists at src/models/user.ts +- Need CRUD operations +- Use existing patterns from src/services/ + +Acceptance: +- createUser(data) → User +- getUserById(id) → User | null +- updateUser(id, data) → User +- deleteUser(id) → boolean +- Proper error handling + +Constraints: +- Use existing database connection +- Follow service patterns in codebase +- Add proper TypeScript types +``` + +### Task Verification Checklist + +After AI completes a task: + +- [ ] Code compiles without errors +- [ ] Tests pass +- [ ] Follows existing code patterns +- [ ] Meets acceptance criteria +- [ ] No unrelated changes diff --git a/skills/.experimental/spec-flow/references/workflow.md b/skills/.experimental/spec-flow/references/workflow.md new file mode 100644 index 0000000..9322853 --- /dev/null +++ b/skills/.experimental/spec-flow/references/workflow.md @@ -0,0 +1,258 @@ +# Spec-Driven Development Workflow + +This document provides detailed guidance on the four-phase SDD workflow. + +## Why Spec-Driven Development? + +Research shows that structured specifications significantly improve AI-assisted development: + +> "1 iteration with structure was of similar accuracy to 8 iterations with unstructured prompts" +> — AI Native Dev + +### Benefits + +1. **Clarity**: Forces upfront thinking before coding +2. **Alignment**: Ensures shared understanding across team/AI +3. **Traceability**: Links requirements → design → implementation +4. **Documentation**: Creates living documentation as a byproduct +5. **Quality**: Reduces rework through early validation + +## Four Phases Overview + +``` +┌─────────────┐ ┌──────────────┐ ┌──────────┐ ┌─────────┐ +│ PROPOSAL │ → │ REQUIREMENTS │ → │ DESIGN │ → │ TASKS │ +│ (Why?) │ │ (What?) │ │ (How?) │ │ (Steps) │ +└─────────────┘ └──────────────┘ └──────────┘ └─────────┘ +``` + +## Phase 1: Proposal + +### Purpose + +Define **why** this change is needed and establish scope boundaries. + +### Key Activities + +1. **Identify the Problem**: What pain point or opportunity exists? +2. **Define Goals**: What measurable outcomes do we want? +3. **Set Boundaries**: What's in scope vs. out of scope? +4. **Assess Risks**: What could go wrong? How do we mitigate? + +### Exit Criteria + +- [ ] Background clearly explained +- [ ] Goals are specific and measurable +- [ ] Non-goals explicitly stated +- [ ] Risks identified with mitigations +- [ ] Open questions resolved +- [ ] Stakeholder approval obtained + +### Common Mistakes + +- ❌ Starting with solution instead of problem +- ❌ Vague goals ("make it better") +- ❌ Missing non-goals (leads to scope creep) +- ❌ Ignoring risks + +## Phase 2: Requirements + +### Purpose + +Define **what** the system should do using structured requirements. + +### EARS Format + +EARS (Easy Approach to Requirements Syntax) provides templates for different requirement types: + +| Type | Template | Example | +|------|----------|---------| +| Ubiquitous | The system shall... | The system shall log all API requests | +| Event-Driven | When X, the system shall... | When user clicks submit, the system shall validate inputs | +| State-Driven | While X, the system shall... | While user is authenticated, the system shall refresh tokens | +| Unwanted | If X, the system shall NOT... | If payment fails, the system shall NOT create order | +| Optional | Where X, the system shall... | Where dark mode is enabled, the system shall use dark theme | + +### Requirement Categories + +1. **Functional Requirements (FR)**: What the system does +2. **Non-Functional Requirements (NFR)**: How the system behaves + - Performance + - Security + - Reliability + - Scalability + - Usability + - Maintainability + +### Exit Criteria + +- [ ] All requirements use EARS format +- [ ] Each requirement is testable +- [ ] Acceptance criteria defined +- [ ] No ambiguous language +- [ ] Traceability matrix complete + +### Common Mistakes + +- ❌ Ambiguous requirements ("fast", "user-friendly") +- ❌ Missing non-functional requirements +- ❌ Requirements without acceptance criteria +- ❌ Too many requirements per item (combine into one) + +## Phase 3: Design + +### Purpose + +Define **how** to implement the requirements. + +### Key Artifacts + +1. **Architecture Diagram**: High-level component view +2. **API Specifications**: Endpoints, request/response schemas +3. **Data Models**: Entity relationships +4. **Sequence Diagrams**: Interaction flows +5. **Error Handling**: Error codes and resolutions + +### Design Considerations + +- **Simplicity**: Favor simple solutions over complex ones +- **Extensibility**: Design for future needs, but don't over-engineer +- **Consistency**: Follow existing patterns in the codebase +- **Testability**: Design for easy testing + +### Exit Criteria + +- [ ] Architecture addresses all requirements +- [ ] APIs fully specified +- [ ] Data models defined +- [ ] Error handling documented +- [ ] Migration plan (if needed) +- [ ] Design approved by reviewers + +### Common Mistakes + +- ❌ Over-engineering for hypothetical future needs +- ❌ Ignoring existing patterns in codebase +- ❌ Missing error handling design +- ❌ No migration plan for schema changes + +## Phase 4: Tasks + +### Purpose + +Break down the design into **executable steps**. + +### Task Decomposition Principles + +1. **Atomic**: Each task completable in 1-2 tool calls +2. **Independent**: Minimize dependencies when possible +3. **Testable**: Each task has verifiable outcome +4. **Estimated**: Include complexity (Low/Medium/High) + +### Task Organization + +``` +Phase 1: Setup + T-001: Create directory structure + T-002: Add dependencies + +Phase 2: Core Implementation + T-010: Implement data model + T-011: Implement service layer + T-012: Implement API endpoints + +Phase 3: Integration + T-020: Wire components together + T-021: Add error handling + +Phase 4: Testing + T-030: Unit tests + T-031: Integration tests + T-032: E2E tests + +Phase 5: Documentation + T-040: API documentation + T-041: Update README +``` + +### Progress Tracking + +| Status | Symbol | Meaning | +|--------|--------|---------| +| Pending | ⏳ | Not started | +| In Progress | 🔄 | Currently working | +| Done | ✅ | Completed | +| Blocked | ❌ | Waiting on dependency | +| On Hold | ⏸️ | Paused intentionally | + +### Exit Criteria + +- [ ] All tasks completed +- [ ] All tests passing +- [ ] Code reviewed +- [ ] Documentation updated +- [ ] Spec archived + +## Phase Transitions + +### Skip Conditions + +| Phase | Can Skip When | +|-------|---------------| +| Proposal | Never (always clarify intent) | +| Requirements | Never for new features | +| Design | Simple feature, architecture obvious | +| Tasks | Never (always break down work) | + +### Rollback Conditions + +| Situation | Action | +|-----------|--------| +| New requirements discovered | Return to Requirements phase | +| Design flaw found | Return to Design phase | +| Scope change requested | Return to Proposal phase | + +## Best Practices + +### During Development + +1. **Update status regularly**: Keep tasks.md current +2. **Link to code**: Reference commits, PRs, file paths +3. **Document decisions**: Note why alternatives were rejected +4. **Raise blockers early**: Don't wait until deadline + +### After Completion + +1. **Archive spec**: Move to `.spec-flow/archive/` +2. **Retrospective**: What worked? What didn't? +3. **Update templates**: Improve based on learnings +4. **Update steering docs**: If project patterns changed + +## Integration with AI Agents + +### Providing Context + +When working with AI agents, provide: + +1. The full spec (proposal + requirements + design) +2. Current task being worked on +3. Relevant steering documents +4. Any blockers or constraints + +### Effective Prompts + +``` +I'm implementing [feature] based on the spec in .spec-flow/active/[feature]/. +Currently working on task T-010: [task description]. +The design specifies [relevant design detail]. +Please help me implement [specific request]. +``` + +### Validation + +After AI generates code: + +1. Verify against acceptance criteria +2. Run tests +3. Update task status +4. Move to next task diff --git a/skills/.experimental/spec-flow/scripts/execute-task.sh b/skills/.experimental/spec-flow/scripts/execute-task.sh new file mode 100755 index 0000000..c622bca --- /dev/null +++ b/skills/.experimental/spec-flow/scripts/execute-task.sh @@ -0,0 +1,249 @@ +#!/bin/bash +# +# execute-task.sh - Execute spec-flow tasks with full context +# +# Usage: +# ./execute-task.sh # Show next pending task +# ./execute-task.sh # Execute specific task +# ./execute-task.sh --status # Show progress summary +# +# Examples: +# ./execute-task.sh user-auth +# ./execute-task.sh user-auth T-003 +# ./execute-task.sh user-auth --status +# + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +CYAN='\033[0;36m' +BOLD='\033[1m' +NC='\033[0m' + +FEATURE_NAME=$1 +TASK_ID=$2 + +# Help +if [ -z "$FEATURE_NAME" ] || [ "$FEATURE_NAME" = "-h" ] || [ "$FEATURE_NAME" = "--help" ]; then + echo "Usage: execute-task.sh [task-id|--status]" + echo "" + echo "Commands:" + echo " Show next pending task with context" + echo " Execute specific task (e.g., T-003)" + echo " --status Show progress summary" + echo "" + echo "Examples:" + echo " ./execute-task.sh user-auth" + echo " ./execute-task.sh user-auth T-003" + echo " ./execute-task.sh user-auth --status" + exit 0 +fi + +SPEC_DIR=".spec-flow/active/$FEATURE_NAME" + +if [ ! -d "$SPEC_DIR" ]; then + echo -e "${RED}Error: Spec directory not found: $SPEC_DIR${NC}" + echo "Available specs:" + ls -1 .spec-flow/active/ 2>/dev/null || echo " (none)" + exit 1 +fi + +TASKS_FILE="$SPEC_DIR/tasks.md" + +if [ ! -f "$TASKS_FILE" ]; then + echo -e "${RED}Error: tasks.md not found in $SPEC_DIR${NC}" + exit 1 +fi + +# Function: Parse tasks from tasks.md +parse_tasks() { + # Extract task lines: matches patterns like "- [ ] **T-001**:" or "- [x] **T-001**:" + grep -E "^[[:space:]]*-[[:space:]]*\[[ x]\][[:space:]]*\*\*T-[0-9]+\*\*" "$TASKS_FILE" 2>/dev/null || true +} + +# Function: Count tasks by status +count_tasks() { + local total=$(parse_tasks | wc -l | tr -d ' ') + local completed=$(parse_tasks | grep -E "\[x\]" | wc -l | tr -d ' ') + local pending=$((total - completed)) + echo "$completed $total $pending" +} + +# Function: Get next pending task +get_next_pending_task() { + parse_tasks | grep -E "\[ \]" | head -1 | sed -E 's/.*\*\*(T-[0-9]+)\*\*.*/\1/' +} + +# Function: Get task description +get_task_description() { + local task_id=$1 + parse_tasks | grep "$task_id" | sed -E 's/.*\*\*T-[0-9]+\*\*:[[:space:]]*//' | sed 's/[[:space:]]*$//' +} + +# Function: Get task details (complexity, files, dependencies) +get_task_details() { + local task_id=$1 + local in_task=false + local details="" + + while IFS= read -r line; do + if [[ "$line" =~ \*\*$task_id\*\* ]]; then + in_task=true + continue + fi + if $in_task; then + # Stop at next task or section + if [[ "$line" =~ ^\*\*T-[0-9]+\*\* ]] || [[ "$line" =~ ^##\ ]] || [[ "$line" =~ ^-\ \[.\]\ \*\*T- ]]; then + break + fi + # Capture indented content (task details) + if [[ "$line" =~ ^[[:space:]]+-[[:space:]] ]] || [[ "$line" =~ ^[[:space:]]+[A-Za-z] ]]; then + details+="$line"$'\n' + fi + fi + done < "$TASKS_FILE" + + echo "$details" +} + +# Function: Show progress summary +show_status() { + echo -e "${BOLD}${BLUE}=== SPEC-FLOW PROGRESS: $FEATURE_NAME ===${NC}" + echo "" + + read -r completed total pending <<< $(count_tasks) + + if [ "$total" -eq 0 ]; then + echo -e "${YELLOW}No tasks found in tasks.md${NC}" + return + fi + + local percent=$((completed * 100 / total)) + + # Progress bar + local bar_width=30 + local filled=$((percent * bar_width / 100)) + local empty=$((bar_width - filled)) + + printf "${BOLD}Progress: ${NC}[" + printf "${GREEN}%0.s█${NC}" $(seq 1 $filled 2>/dev/null) || true + printf "%0.s░" $(seq 1 $empty 2>/dev/null) || true + printf "] ${BOLD}%d%%${NC} (%d/%d)\n" "$percent" "$completed" "$total" + echo "" + + # Task list + echo -e "${BOLD}Tasks:${NC}" + parse_tasks | while read -r line; do + if [[ "$line" =~ \[x\] ]]; then + echo -e " ${GREEN}✅${NC} $line" | sed 's/- \[x\] //' | sed 's/\*\*//g' + else + echo -e " ${YELLOW}⏳${NC} $line" | sed 's/- \[ \] //' | sed 's/\*\*//g' + fi + done + + echo "" + if [ "$pending" -gt 0 ]; then + local next_task=$(get_next_pending_task) + echo -e "${CYAN}Next task: ${BOLD}$next_task${NC}" + else + echo -e "${GREEN}${BOLD}All tasks completed! 🎉${NC}" + fi +} + +# Function: Show execution context for a task +show_task_context() { + local task_id=$1 + local task_desc=$(get_task_description "$task_id") + local task_details=$(get_task_details "$task_id") + + echo -e "${BOLD}${BLUE}╔════════════════════════════════════════════════════════════════╗${NC}" + echo -e "${BOLD}${BLUE}║ SPEC-FLOW TASK EXECUTION CONTEXT ║${NC}" + echo -e "${BOLD}${BLUE}╚════════════════════════════════════════════════════════════════╝${NC}" + echo "" + + # Progress + read -r completed total pending <<< $(count_tasks) + echo -e "${BOLD}Feature:${NC} $FEATURE_NAME" + echo -e "${BOLD}Progress:${NC} $completed/$total completed" + echo "" + + # Current task + echo -e "${BOLD}${CYAN}┌─ CURRENT TASK ─────────────────────────────────────────────────┐${NC}" + echo -e "${BOLD}│ $task_id: $task_desc${NC}" + echo -e "${CYAN}└────────────────────────────────────────────────────────────────┘${NC}" + + if [ -n "$task_details" ]; then + echo "" + echo -e "${BOLD}Task Details:${NC}" + echo "$task_details" | sed 's/^/ /' + fi + echo "" + + # Relevant design section + if [ -f "$SPEC_DIR/design.md" ]; then + echo -e "${BOLD}${YELLOW}┌─ RELEVANT DESIGN ──────────────────────────────────────────────┐${NC}" + # Try to find relevant section in design.md based on task keywords + local keywords=$(echo "$task_desc" | tr ' ' '\n' | grep -E '^[A-Z]' | head -3 | tr '\n' '|' | sed 's/|$//') + if [ -n "$keywords" ]; then + grep -i -A 10 -E "$keywords" "$SPEC_DIR/design.md" 2>/dev/null | head -20 || echo "(No matching design section found)" + else + echo "(Review design.md for implementation details)" + fi + echo -e "${YELLOW}└────────────────────────────────────────────────────────────────┘${NC}" + echo "" + fi + + # Relevant requirements + if [ -f "$SPEC_DIR/requirements.md" ]; then + echo -e "${BOLD}${GREEN}┌─ RELEVANT REQUIREMENTS ────────────────────────────────────────┐${NC}" + # Extract FR/NFR/AC references from task + local refs=$(echo "$task_desc $task_details" | grep -oE "(FR|NFR|AC)-[0-9]+" | sort -u | tr '\n' ' ') + if [ -n "$refs" ]; then + for ref in $refs; do + grep -A 2 "$ref" "$SPEC_DIR/requirements.md" 2>/dev/null || true + done + else + echo "(No specific requirement references found in task)" + fi + echo -e "${GREEN}└────────────────────────────────────────────────────────────────┘${NC}" + echo "" + fi + + # Instructions + echo -e "${BOLD}${RED}┌─ EXECUTION INSTRUCTIONS ───────────────────────────────────────┐${NC}" + echo -e "│ 1. Execute ONLY this task: ${BOLD}$task_id${NC}" + echo -e "│ 2. Follow the design specifications above" + echo -e "│ 3. After completion, update tasks.md: [ ] → [x]" + echo -e "│ 4. Report what was done and ask for confirmation" + echo -e "│ 5. Do NOT proceed to next task without user saying 'continue'" + echo -e "${RED}└────────────────────────────────────────────────────────────────┘${NC}" +} + +# Main logic +if [ "$TASK_ID" = "--status" ]; then + show_status +elif [ -n "$TASK_ID" ]; then + # Specific task requested + if ! parse_tasks | grep -q "$TASK_ID"; then + echo -e "${RED}Error: Task $TASK_ID not found in tasks.md${NC}" + echo "" + echo "Available tasks:" + parse_tasks | sed 's/^/ /' + exit 1 + fi + show_task_context "$TASK_ID" +else + # Show next pending task + NEXT_TASK=$(get_next_pending_task) + if [ -z "$NEXT_TASK" ]; then + echo -e "${GREEN}${BOLD}All tasks completed! 🎉${NC}" + echo "" + show_status + else + show_task_context "$NEXT_TASK" + fi +fi diff --git a/skills/.experimental/spec-flow/scripts/init-spec-flow.sh b/skills/.experimental/spec-flow/scripts/init-spec-flow.sh new file mode 100755 index 0000000..5bab973 --- /dev/null +++ b/skills/.experimental/spec-flow/scripts/init-spec-flow.sh @@ -0,0 +1,172 @@ +#!/bin/bash +# +# init-spec-flow.sh - Initialize a new spec-flow directory structure +# +# Usage: +# ./init-spec-flow.sh [--steering] +# +# Examples: +# ./init-spec-flow.sh user-authentication +# ./init-spec-flow.sh payment-integration --steering +# + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Get the directory where this script is located +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SKILL_DIR="$(dirname "$SCRIPT_DIR")" +TEMPLATES_DIR="$SKILL_DIR/templates" + +# Parse arguments +FEATURE_NAME="" +INIT_STEERING=false + +while [[ $# -gt 0 ]]; do + case $1 in + --steering) + INIT_STEERING=true + shift + ;; + -h|--help) + echo "Usage: $0 [--steering]" + echo "" + echo "Arguments:" + echo " feature-name Name of the feature (lowercase, hyphens allowed)" + echo "" + echo "Options:" + echo " --steering Also initialize steering documents" + echo " -h, --help Show this help message" + echo "" + echo "Examples:" + echo " $0 user-authentication" + echo " $0 payment-integration --steering" + exit 0 + ;; + *) + if [[ -z "$FEATURE_NAME" ]]; then + FEATURE_NAME="$1" + else + echo -e "${RED}Error: Unknown argument: $1${NC}" + exit 1 + fi + shift + ;; + esac +done + +# Validate feature name +if [[ -z "$FEATURE_NAME" ]]; then + echo -e "${RED}Error: Feature name is required${NC}" + echo "Usage: $0 [--steering]" + exit 1 +fi + +# Validate feature name format +if [[ ! "$FEATURE_NAME" =~ ^[a-z0-9-]+$ ]]; then + echo -e "${RED}Error: Feature name must be lowercase with hyphens only${NC}" + echo "Example: user-authentication, payment-integration" + exit 1 +fi + +# Get current date +CURRENT_DATE=$(date +%Y-%m-%d) + +# Create spec-flow directory structure +SPEC_DIR=".spec-flow" +ACTIVE_DIR="$SPEC_DIR/active/$FEATURE_NAME" +STEERING_DIR="$SPEC_DIR/steering" +ARCHIVE_DIR="$SPEC_DIR/archive" + +echo -e "${BLUE}Initializing spec-flow for: ${GREEN}$FEATURE_NAME${NC}" +echo "" + +# Create directories +mkdir -p "$ACTIVE_DIR" +mkdir -p "$ARCHIVE_DIR" + +echo -e "${GREEN}✓${NC} Created $ACTIVE_DIR" +echo -e "${GREEN}✓${NC} Created $ARCHIVE_DIR" + +# Function to copy and customize template +copy_template() { + local template_file="$1" + local output_file="$2" + local feature_name="$3" + local date="$4" + + if [[ -f "$template_file" ]]; then + # Copy template and replace placeholders + sed -e "s/{{FEATURE_NAME}}/$feature_name/g" \ + -e "s/{{DATE}}/$date/g" \ + -e "s/{{AUTHOR}}/$(whoami)/g" \ + -e "s/{{PROJECT_NAME}}/$(basename "$(pwd)")/g" \ + "$template_file" > "$output_file" + echo -e "${GREEN}✓${NC} Created $output_file" + else + echo -e "${YELLOW}⚠${NC} Template not found: $template_file" + fi +} + +# Copy spec templates +copy_template "$TEMPLATES_DIR/proposal.md.template" "$ACTIVE_DIR/proposal.md" "$FEATURE_NAME" "$CURRENT_DATE" +copy_template "$TEMPLATES_DIR/requirements.md.template" "$ACTIVE_DIR/requirements.md" "$FEATURE_NAME" "$CURRENT_DATE" +copy_template "$TEMPLATES_DIR/design.md.template" "$ACTIVE_DIR/design.md" "$FEATURE_NAME" "$CURRENT_DATE" +copy_template "$TEMPLATES_DIR/tasks.md.template" "$ACTIVE_DIR/tasks.md" "$FEATURE_NAME" "$CURRENT_DATE" + +# Create metadata file +cat > "$ACTIVE_DIR/.meta.json" << EOF +{ + "feature": "$FEATURE_NAME", + "status": "proposal", + "created": "$CURRENT_DATE", + "updated": "$CURRENT_DATE", + "author": "$(whoami)", + "phase": "proposal" +} +EOF +echo -e "${GREEN}✓${NC} Created $ACTIVE_DIR/.meta.json" + +# Initialize steering documents if requested +if [[ "$INIT_STEERING" == true ]]; then + echo "" + echo -e "${BLUE}Initializing steering documents...${NC}" + mkdir -p "$STEERING_DIR" + + copy_template "$TEMPLATES_DIR/steering/constitution.md.template" "$STEERING_DIR/constitution.md" "$FEATURE_NAME" "$CURRENT_DATE" + copy_template "$TEMPLATES_DIR/steering/product.md.template" "$STEERING_DIR/product.md" "$FEATURE_NAME" "$CURRENT_DATE" + copy_template "$TEMPLATES_DIR/steering/tech.md.template" "$STEERING_DIR/tech.md" "$FEATURE_NAME" "$CURRENT_DATE" + copy_template "$TEMPLATES_DIR/steering/structure.md.template" "$STEERING_DIR/structure.md" "$FEATURE_NAME" "$CURRENT_DATE" +fi + +# Create .gitignore if it doesn't exist +if [[ ! -f "$SPEC_DIR/.gitignore" ]]; then + cat > "$SPEC_DIR/.gitignore" << EOF +# Ignore backup files +*.bak +*.backup + +# Keep archive in git but ignore empty directories +!archive/ +archive/**/.gitkeep +EOF + echo -e "${GREEN}✓${NC} Created $SPEC_DIR/.gitignore" +fi + +echo "" +echo -e "${GREEN}✅ Spec-flow initialized successfully!${NC}" +echo "" +echo -e "${BLUE}Next steps:${NC}" +echo " 1. Edit ${YELLOW}$ACTIVE_DIR/proposal.md${NC} to define the feature" +echo " 2. Get proposal approved" +echo " 3. Fill in requirements, design, and tasks" +echo " 4. Use tasks.md to track implementation progress" +echo "" +echo -e "${BLUE}Workflow:${NC}" +echo " Proposal → Requirements → Design → Tasks → Implementation → Archive" diff --git a/skills/.experimental/spec-flow/scripts/validate-spec-flow.py b/skills/.experimental/spec-flow/scripts/validate-spec-flow.py new file mode 100755 index 0000000..8969718 --- /dev/null +++ b/skills/.experimental/spec-flow/scripts/validate-spec-flow.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +""" +validate-spec-flow.py - Validate spec-flow completeness and consistency + +Usage: + python validate-spec-flow.py + python validate-spec-flow.py .spec-flow/active/user-authentication + +Exit codes: + 0 - All validations passed + 1 - Validation errors found + 2 - Invalid arguments or spec-flow not found +""" + +import json +import os +import re +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import List, Optional + + +@dataclass +class ValidationResult: + """Result of a single validation check.""" + passed: bool + message: str + severity: str = "error" # error, warning, info + + +@dataclass +class SpecValidation: + """Complete validation results for a spec.""" + spec_path: Path + results: List[ValidationResult] + + @property + def has_errors(self) -> bool: + return any(r.severity == "error" and not r.passed for r in self.results) + + @property + def has_warnings(self) -> bool: + return any(r.severity == "warning" and not r.passed for r in self.results) + + +def read_file(path: Path) -> Optional[str]: + """Read file contents, return None if not found.""" + try: + return path.read_text(encoding="utf-8") + except FileNotFoundError: + return None + except Exception as e: + print(f"Error reading {path}: {e}", file=sys.stderr) + return None + + +def validate_file_exists(spec_path: Path, filename: str) -> ValidationResult: + """Check if a required file exists.""" + file_path = spec_path / filename + if file_path.exists(): + return ValidationResult(True, f"✓ {filename} exists") + return ValidationResult(False, f"✗ {filename} is missing", "error") + + +def validate_not_empty(spec_path: Path, filename: str) -> ValidationResult: + """Check if a file has content beyond template placeholders.""" + file_path = spec_path / filename + content = read_file(file_path) + + if content is None: + return ValidationResult(False, f"✗ {filename} cannot be read", "error") + + # Remove comments and whitespace + clean = re.sub(r'', '', content, flags=re.DOTALL) + clean = re.sub(r'{{.*?}}', '', clean) # Remove template placeholders + clean = clean.strip() + + # Check if there's substantial content + lines = [l for l in clean.split('\n') if l.strip() and not l.strip().startswith('#')] + + if len(lines) < 3: + return ValidationResult(False, f"⚠ {filename} appears to have only template content", "warning") + + return ValidationResult(True, f"✓ {filename} has content") + + +def validate_proposal_sections(spec_path: Path) -> List[ValidationResult]: + """Validate proposal.md has required sections.""" + results = [] + content = read_file(spec_path / "proposal.md") + + if content is None: + return [ValidationResult(False, "✗ proposal.md cannot be read", "error")] + + required_sections = ["Background", "Goals", "Non-Goals", "Scope", "Risks"] + + for section in required_sections: + if f"## {section}" in content or f"# {section}" in content: + results.append(ValidationResult(True, f"✓ Proposal has {section} section")) + else: + results.append(ValidationResult(False, f"✗ Proposal missing {section} section", "error")) + + return results + + +def validate_requirements_format(spec_path: Path) -> List[ValidationResult]: + """Validate requirements.md uses EARS format.""" + results = [] + content = read_file(spec_path / "requirements.md") + + if content is None: + return [ValidationResult(False, "✗ requirements.md cannot be read", "error")] + + # Check for requirement IDs + fr_pattern = r'FR-\d+' + nfr_pattern = r'NFR-\d+' + ac_pattern = r'AC-\d+' + + fr_count = len(re.findall(fr_pattern, content)) + nfr_count = len(re.findall(nfr_pattern, content)) + ac_count = len(re.findall(ac_pattern, content)) + + if fr_count > 0: + results.append(ValidationResult(True, f"✓ Found {fr_count} functional requirements")) + else: + results.append(ValidationResult(False, "✗ No functional requirements (FR-XXX) found", "warning")) + + if nfr_count > 0: + results.append(ValidationResult(True, f"✓ Found {nfr_count} non-functional requirements")) + else: + results.append(ValidationResult(False, "⚠ No non-functional requirements (NFR-XXX) found", "warning")) + + if ac_count > 0: + results.append(ValidationResult(True, f"✓ Found {ac_count} acceptance criteria")) + else: + results.append(ValidationResult(False, "✗ No acceptance criteria (AC-XXX) found", "error")) + + # Check for EARS keywords + ears_keywords = ["shall", "When", "While", "If"] + found_ears = any(kw in content for kw in ears_keywords) + + if found_ears: + results.append(ValidationResult(True, "✓ Requirements use EARS format keywords")) + else: + results.append(ValidationResult(False, "⚠ Requirements may not follow EARS format", "warning")) + + return results + + +def validate_design_diagrams(spec_path: Path) -> List[ValidationResult]: + """Validate design.md has diagrams.""" + results = [] + content = read_file(spec_path / "design.md") + + if content is None: + return [ValidationResult(False, "✗ design.md cannot be read", "error")] + + # Check for Mermaid diagrams + if "```mermaid" in content: + mermaid_count = content.count("```mermaid") + results.append(ValidationResult(True, f"✓ Found {mermaid_count} Mermaid diagram(s)")) + else: + results.append(ValidationResult(False, "⚠ No Mermaid diagrams found", "warning")) + + # Check for API section + if "## API" in content or "### API" in content: + results.append(ValidationResult(True, "✓ Design has API section")) + else: + results.append(ValidationResult(False, "⚠ Design may be missing API section", "warning")) + + return results + + +def validate_tasks_format(spec_path: Path) -> List[ValidationResult]: + """Validate tasks.md has proper task format.""" + results = [] + content = read_file(spec_path / "tasks.md") + + if content is None: + return [ValidationResult(False, "✗ tasks.md cannot be read", "error")] + + # Check for task IDs + task_pattern = r'T-\d+' + tasks = re.findall(task_pattern, content) + + if len(tasks) > 0: + results.append(ValidationResult(True, f"✓ Found {len(tasks)} tasks")) + else: + results.append(ValidationResult(False, "✗ No tasks (T-XXX) found", "error")) + + # Check for complexity markers + if "Complexity:" in content: + results.append(ValidationResult(True, "✓ Tasks include complexity estimates")) + else: + results.append(ValidationResult(False, "⚠ Tasks may be missing complexity estimates", "warning")) + + # Check for dependencies + if "Dependencies:" in content: + results.append(ValidationResult(True, "✓ Tasks include dependency information")) + else: + results.append(ValidationResult(False, "⚠ Tasks may be missing dependencies", "warning")) + + # Check for progress tracking + status_markers = ["⏳", "🔄", "✅", "❌", "Pending", "In Progress", "Done", "Blocked"] + has_status = any(marker in content for marker in status_markers) + + if has_status: + results.append(ValidationResult(True, "✓ Tasks have status markers")) + else: + results.append(ValidationResult(False, "⚠ Tasks may be missing status markers", "warning")) + + return results + + +def validate_meta_json(spec_path: Path) -> List[ValidationResult]: + """Validate .meta.json file.""" + results = [] + meta_path = spec_path / ".meta.json" + + if not meta_path.exists(): + return [ValidationResult(False, "⚠ .meta.json not found (optional)", "info")] + + try: + with open(meta_path) as f: + meta = json.load(f) + + required_fields = ["feature", "status", "created", "phase"] + for field in required_fields: + if field in meta: + results.append(ValidationResult(True, f"✓ .meta.json has {field}")) + else: + results.append(ValidationResult(False, f"⚠ .meta.json missing {field}", "warning")) + + except json.JSONDecodeError as e: + results.append(ValidationResult(False, f"✗ .meta.json is invalid JSON: {e}", "error")) + + return results + + +def validate_spec(spec_path: Path) -> SpecValidation: + """Run all validations on a spec directory.""" + results = [] + + # Required files + required_files = ["proposal.md", "requirements.md", "design.md", "tasks.md"] + for filename in required_files: + results.append(validate_file_exists(spec_path, filename)) + + # Content checks + for filename in required_files: + results.append(validate_not_empty(spec_path, filename)) + + # Structure checks + results.extend(validate_proposal_sections(spec_path)) + results.extend(validate_requirements_format(spec_path)) + results.extend(validate_design_diagrams(spec_path)) + results.extend(validate_tasks_format(spec_path)) + results.extend(validate_meta_json(spec_path)) + + return SpecValidation(spec_path, results) + + +def print_results(validation: SpecValidation) -> None: + """Print validation results with colors.""" + # ANSI colors + RED = "\033[0;31m" + GREEN = "\033[0;32m" + YELLOW = "\033[1;33m" + BLUE = "\033[0;34m" + NC = "\033[0m" + + print(f"\n{BLUE}Validating spec: {validation.spec_path}{NC}\n") + + errors = 0 + warnings = 0 + + for result in validation.results: + if result.passed: + print(f" {GREEN}{result.message}{NC}") + elif result.severity == "error": + print(f" {RED}{result.message}{NC}") + errors += 1 + elif result.severity == "warning": + print(f" {YELLOW}{result.message}{NC}") + warnings += 1 + else: + print(f" {result.message}") + + print() + if errors == 0 and warnings == 0: + print(f"{GREEN}✅ All validations passed!{NC}") + elif errors == 0: + print(f"{YELLOW}⚠ Passed with {warnings} warning(s){NC}") + else: + print(f"{RED}❌ Failed with {errors} error(s) and {warnings} warning(s){NC}") + + +def main(): + if len(sys.argv) < 2: + print("Usage: python validate-spec-flow.py ") + print("Example: python validate-spec-flow.py .spec-flow/active/user-authentication") + sys.exit(2) + + spec_path = Path(sys.argv[1]) + + if not spec_path.exists(): + print(f"Error: Spec-flow directory not found: {spec_path}", file=sys.stderr) + sys.exit(2) + + if not spec_path.is_dir(): + print(f"Error: Not a directory: {spec_path}", file=sys.stderr) + sys.exit(2) + + validation = validate_spec(spec_path) + print_results(validation) + + sys.exit(1 if validation.has_errors else 0) + + +if __name__ == "__main__": + main() diff --git a/skills/.experimental/spec-flow/templates/design.md.template b/skills/.experimental/spec-flow/templates/design.md.template new file mode 100644 index 0000000..0bd1483 --- /dev/null +++ b/skills/.experimental/spec-flow/templates/design.md.template @@ -0,0 +1,268 @@ +# {{FEATURE_NAME}} - Design + +> **Status**: Draft | In Review | Approved +> **Requirements**: [requirements.md](./requirements.md) +> **Last Updated**: {{DATE}} + +## Overview + + + +## Architecture Overview + + + +```mermaid +graph TD + subgraph "External" + Client[Client Application] + end + + subgraph "System Boundary" + API[API Gateway] + Service[{{Feature}} Service] + DB[(Database)] + end + + Client --> API + API --> Service + Service --> DB +``` + +## Component Design + +### {{Component Name}} + +**Purpose**: {{brief description}} + +**Responsibilities**: +- {{responsibility 1}} +- {{responsibility 2}} + +**Dependencies**: +- {{dependency 1}} +- {{dependency 2}} + +**Interfaces**: + +```typescript +interface {{ComponentName}} { + // Input + {{methodName}}(input: {{InputType}}): {{OutputType}}; +} +``` + +### {{Another Component}} + +**Purpose**: {{brief description}} + + + +## API Design + +### {{Endpoint Name}} + +**Endpoint**: `{{METHOD}} /api/v1/{{resource}}` + +**Description**: {{what this endpoint does}} + +**Request**: + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| {{param}} | {{type}} | Yes/No | {{description}} | + +```json +{ + "field": "value" +} +``` + +**Response**: + +| Status | Description | +|--------|-------------| +| 200 | Success | +| 400 | Bad Request | +| 401 | Unauthorized | +| 500 | Internal Error | + +**Success Response (200)**: +```json +{ + "data": { + "id": "string", + "field": "value" + } +} +``` + +**Error Response (4xx/5xx)**: +```json +{ + "error": { + "code": "ERROR_CODE", + "message": "Human readable message" + } +} +``` + +## Data Model + +### Entity Relationship Diagram + +```mermaid +erDiagram + {{Entity1}} ||--o{ {{Entity2}} : "has many" + {{Entity1}} { + string id PK + string name + datetime created_at + datetime updated_at + } + {{Entity2}} { + string id PK + string entity1_id FK + string field + } +``` + +### {{Entity}} Schema + +| Field | Type | Constraints | Description | +|-------|------|-------------|-------------| +| id | UUID | PK, NOT NULL | Primary key | +| {{field}} | {{type}} | {{constraints}} | {{description}} | +| created_at | TIMESTAMP | NOT NULL | Creation timestamp | +| updated_at | TIMESTAMP | NOT NULL | Last update timestamp | + +## State Machine + + + +```mermaid +stateDiagram-v2 + [*] --> Created + Created --> Active: activate + Active --> Paused: pause + Paused --> Active: resume + Active --> Completed: complete + Completed --> [*] +``` + +## Sequence Diagrams + +### {{Use Case Name}} + +```mermaid +sequenceDiagram + participant C as Client + participant A as API + participant S as Service + participant D as Database + + C->>A: Request + A->>S: Process + S->>D: Query + D-->>S: Result + S-->>A: Response + A-->>C: Response +``` + +## Error Handling + +| Error Code | HTTP Status | Description | Resolution | +|------------|-------------|-------------|------------| +| {{CODE}} | {{status}} | {{description}} | {{how to resolve}} | + +### Error Response Format + +```json +{ + "error": { + "code": "UNIQUE_ERROR_CODE", + "message": "User-friendly message", + "details": { + "field": "Additional context" + }, + "trace_id": "For debugging" + } +} +``` + +## Security Considerations + +### Authentication + + + +### Authorization + + + +### Data Protection + + + +## Performance Considerations + +### Caching Strategy + + + +### Optimization Techniques + + + +### Scalability + + + +## Migration Plan + + + +### Pre-Migration + +- [ ] {{step}} + +### Migration Steps + +1. {{step 1}} +2. {{step 2}} + +### Rollback Plan + +1. {{rollback step 1}} +2. {{rollback step 2}} + +### Post-Migration Verification + +- [ ] {{verification step}} + +## Testing Strategy + +### Unit Tests + +- {{what to unit test}} + +### Integration Tests + +- {{what to integration test}} + +### E2E Tests + +- {{what to e2e test}} + +## Open Design Questions + + + +- [ ] {{question 1}} +- [ ] {{question 2}} + +## References + +- [Requirements](./requirements.md) +- [Proposal](./proposal.md) +- {{external reference}} diff --git a/skills/.experimental/spec-flow/templates/proposal.md.template b/skills/.experimental/spec-flow/templates/proposal.md.template new file mode 100644 index 0000000..f4409fd --- /dev/null +++ b/skills/.experimental/spec-flow/templates/proposal.md.template @@ -0,0 +1,89 @@ +# {{FEATURE_NAME}} - Proposal + +> **Status**: Draft | In Review | Approved +> **Author**: {{AUTHOR}} +> **Created**: {{DATE}} +> **Last Updated**: {{DATE}} + +## Background + + + +## Goals + + + +- [ ] Goal 1: {{description}} +- [ ] Goal 2: {{description}} + +## Non-Goals + + + +- {{non-goal 1}} +- {{non-goal 2}} + +## Scope + +### In Scope + + + +- {{scope item 1}} +- {{scope item 2}} + +### Out of Scope + + + +- {{out of scope item 1}} +- {{out of scope item 2}} + +## Proposed Solution + + + +## Alternatives Considered + + + +| Alternative | Pros | Cons | Why Rejected | +|-------------|------|------|--------------| +| {{alt 1}} | | | | +| {{alt 2}} | | | | + +## Risks and Mitigations + +| Risk | Likelihood | Impact | Mitigation | +|------|------------|--------|------------| +| {{risk 1}} | Low/Medium/High | Low/Medium/High | {{mitigation}} | +| {{risk 2}} | Low/Medium/High | Low/Medium/High | {{mitigation}} | + +## Dependencies + + + +- {{dependency 1}} +- {{dependency 2}} + +## Success Metrics + + + +| Metric | Current | Target | How to Measure | +|--------|---------|--------|----------------| +| {{metric 1}} | {{value}} | {{value}} | {{method}} | + +## Open Questions + + + +- [ ] {{question 1}} +- [ ] {{question 2}} + +## References + + + +- {{reference 1}} +- {{reference 2}} diff --git a/skills/.experimental/spec-flow/templates/requirements.md.template b/skills/.experimental/spec-flow/templates/requirements.md.template new file mode 100644 index 0000000..8868048 --- /dev/null +++ b/skills/.experimental/spec-flow/templates/requirements.md.template @@ -0,0 +1,126 @@ +# {{FEATURE_NAME}} - Requirements + +> **Status**: Draft | In Review | Approved +> **Proposal**: [proposal.md](./proposal.md) +> **Last Updated**: {{DATE}} + +## Overview + + + +## Functional Requirements + + + +### Ubiquitous Requirements + + + +- **FR-001**: The system shall {{action}}. +- **FR-002**: The system shall {{action}}. + +### Event-Driven Requirements + + + +- **FR-010**: When {{trigger event}}, the system shall {{action}}. +- **FR-011**: When {{trigger event}}, the system shall {{action}}. + +### State-Driven Requirements + + + +- **FR-020**: While {{state condition}}, the system shall {{action}}. +- **FR-021**: While {{state condition}}, the system shall {{action}}. + +### Unwanted Behavior Requirements + + + +- **FR-030**: If {{error condition}}, then the system shall NOT {{prohibited action}}. +- **FR-031**: If {{error condition}}, then the system shall NOT {{prohibited action}}. + +### Optional Features + + + +- **FR-040**: Where {{feature flag}} is enabled, the system shall {{action}}. + +## Non-Functional Requirements + +### Performance + +- **NFR-001**: The system shall respond to {{operation}} within {{time}} under {{load conditions}}. +- **NFR-002**: The system shall support {{number}} concurrent {{operations}}. + +### Security + +- **NFR-010**: The system shall {{security requirement}}. +- **NFR-011**: The system shall NOT {{security prohibition}}. + +### Reliability + +- **NFR-020**: The system shall maintain {{uptime percentage}} availability. +- **NFR-021**: The system shall recover from {{failure type}} within {{time}}. + +### Scalability + +- **NFR-030**: The system shall scale to handle {{capacity}} of {{resource}}. + +### Usability + +- **NFR-040**: The system shall {{usability requirement}}. + +### Maintainability + +- **NFR-050**: The system shall {{maintainability requirement}}. + +## Constraints + + + +- **C-001**: {{constraint description}} +- **C-002**: {{constraint description}} + +## Assumptions + + + +- **A-001**: {{assumption description}} +- **A-002**: {{assumption description}} + +## Acceptance Criteria + + + +### Core Functionality + +- [ ] **AC-001**: Given {{precondition}}, when {{action}}, then {{expected result}}. +- [ ] **AC-002**: Given {{precondition}}, when {{action}}, then {{expected result}}. + +### Edge Cases + +- [ ] **AC-010**: Given {{edge case condition}}, when {{action}}, then {{expected behavior}}. +- [ ] **AC-011**: Given {{error condition}}, when {{action}}, then {{error handling behavior}}. + +### Performance + +- [ ] **AC-020**: {{operation}} completes within {{time}} for {{data size}}. + +## Traceability Matrix + + + +| Requirement | Acceptance Criteria | Test Case | +|-------------|---------------------|-----------| +| FR-001 | AC-001 | TC-001 | +| FR-010 | AC-002 | TC-002 | +| NFR-001 | AC-020 | TC-020 | + +## Glossary + + + +| Term | Definition | +|------|------------| +| {{term}} | {{definition}} | diff --git a/skills/.experimental/spec-flow/templates/steering/constitution.md.template b/skills/.experimental/spec-flow/templates/steering/constitution.md.template new file mode 100644 index 0000000..0a860c0 --- /dev/null +++ b/skills/.experimental/spec-flow/templates/steering/constitution.md.template @@ -0,0 +1,90 @@ +# Project Constitution + +> **Last Updated**: {{DATE}} +> **Maintainers**: {{TEAM/NAMES}} + +## Purpose + + + +This document defines the governance principles and decision-making guidelines for {{PROJECT_NAME}}. + +## Core Values + + + +1. **{{Value 1}}**: {{description}} +2. **{{Value 2}}**: {{description}} +3. **{{Value 3}}**: {{description}} + +## Decision-Making Principles + +### When to Write a Spec + +A spec is required when: + +- [ ] Adding a new feature that affects multiple components +- [ ] Making breaking changes to existing APIs +- [ ] Changing core architecture or data models +- [ ] Work estimated at more than {{time threshold}} + +A spec is NOT required when: + +- Bug fixes with clear scope +- Documentation updates +- Minor refactoring (no behavior change) +- Dependency updates (unless major version) + +### Approval Process + +| Change Type | Approvers | Review Time | +|-------------|-----------|-------------| +| Minor | 1 team member | 1 day | +| Standard | 2 team members | 3 days | +| Major | Tech lead + 1 | 5 days | +| Breaking | All stakeholders | 1 week | + +### Conflict Resolution + +When disagreements occur: + +1. **Data first**: Bring evidence (metrics, user feedback, benchmarks) +2. **Prototype**: Build a minimal proof-of-concept if unclear +3. **Time-box**: Set a deadline for decision +4. **Escalate**: If still blocked, {{escalation path}} + +## Quality Standards + +### Code Quality + +- [ ] All code must pass linting +- [ ] Test coverage minimum: {{percentage}}% +- [ ] No known security vulnerabilities +- [ ] Documentation for public APIs + +### Review Criteria + +- [ ] Meets acceptance criteria from spec +- [ ] No regression in existing functionality +- [ ] Performance acceptable (see tech.md for targets) +- [ ] Follows code style (see structure.md) + +## Communication Guidelines + +### Spec Updates + +- Notify stakeholders when spec status changes +- Update tasks.md daily during active development +- Archive completed specs within {{time}} of completion + +### Blocking Issues + +- Raise blockers within {{time}} of discovery +- Tag in {{communication channel}} +- Update spec with blocker status + +## Change History + +| Date | Change | Author | +|------|--------|--------| +| {{date}} | Initial constitution | {{author}} | diff --git a/skills/.experimental/spec-flow/templates/steering/product.md.template b/skills/.experimental/spec-flow/templates/steering/product.md.template new file mode 100644 index 0000000..35565cc --- /dev/null +++ b/skills/.experimental/spec-flow/templates/steering/product.md.template @@ -0,0 +1,105 @@ +# Product Vision + +> **Last Updated**: {{DATE}} +> **Product Owner**: {{NAME}} + +## Mission + + + +{{PROJECT_NAME}} exists to {{mission statement}}. + +## Vision + + + +## Target Users + +### Primary Persona + +**Name**: {{Persona Name}} + +- **Role**: {{job title/role}} +- **Goals**: {{what they want to achieve}} +- **Pain Points**: {{current frustrations}} +- **Tech Savviness**: Low / Medium / High + +### Secondary Personas + + + +## Problem Statement + + + +## Value Proposition + + + +For {{target users}} who {{need/want}}, {{product}} is a {{category}} that {{key benefit}}. Unlike {{alternatives}}, we {{differentiator}}. + +## Key Metrics + +### North Star Metric + +**Metric**: {{metric name}} +**Current**: {{value}} +**Target**: {{value}} +**Why**: {{rationale}} + +### Supporting Metrics + +| Metric | Current | Target | Owner | +|--------|---------|--------|-------| +| {{metric}} | {{value}} | {{value}} | {{name}} | + +## Product Principles + +When making trade-offs, prioritize in this order: + +1. **{{Principle 1}}**: {{description}} +2. **{{Principle 2}}**: {{description}} +3. **{{Principle 3}}**: {{description}} + +## Roadmap Themes + +### Current Quarter + +- {{Theme 1}}: {{brief description}} +- {{Theme 2}}: {{brief description}} + +### Next Quarter + +- {{Theme 1}}: {{brief description}} +- {{Theme 2}}: {{brief description}} + +### Future (Not Committed) + +- {{Theme 1}}: {{brief description}} + +## Constraints + + + +- {{Constraint 1}} +- {{Constraint 2}} + +## Competitive Landscape + +| Competitor | Strengths | Weaknesses | Our Advantage | +|------------|-----------|------------|---------------| +| {{name}} | {{strengths}} | {{weaknesses}} | {{our advantage}} | + +## Success Criteria + + + +- [ ] {{success criterion 1}} +- [ ] {{success criterion 2}} +- [ ] {{success criterion 3}} + +## Change History + +| Date | Change | Author | +|------|--------|--------| +| {{date}} | Initial product vision | {{author}} | diff --git a/skills/.experimental/spec-flow/templates/steering/structure.md.template b/skills/.experimental/spec-flow/templates/steering/structure.md.template new file mode 100644 index 0000000..6f0913b --- /dev/null +++ b/skills/.experimental/spec-flow/templates/steering/structure.md.template @@ -0,0 +1,200 @@ +# Code Structure + +> **Last Updated**: {{DATE}} +> **Maintainer**: {{NAME}} + +## Project Layout + +``` +{{project-name}}/ +├── src/ # Source code +│ ├── {{module1}}/ # {{description}} +│ ├── {{module2}}/ # {{description}} +│ └── {{module3}}/ # {{description}} +├── tests/ # Test files +│ ├── unit/ # Unit tests +│ ├── integration/ # Integration tests +│ └── e2e/ # End-to-end tests +├── docs/ # Documentation +├── scripts/ # Build/deploy scripts +├── .spec-flow/ # Spec-Driven Development files +│ ├── steering/ # Project governance +│ ├── active/ # Active specs +│ └── archive/ # Completed specs +└── {{other}}/ # {{description}} +``` + +## Module Organization + +### Naming Conventions + +| Type | Convention | Example | +|------|------------|---------| +| Files | {{convention}} | {{example}} | +| Directories | {{convention}} | {{example}} | +| Classes | {{convention}} | {{example}} | +| Functions | {{convention}} | {{example}} | +| Constants | {{convention}} | {{example}} | +| Interfaces | {{convention}} | {{example}} | + +### Import Order + +1. Standard library imports +2. Third-party imports +3. Local application imports + +```{{language}} +// Example +import {{standard library}} +import {{third party}} +import {{local module}} +``` + +## Code Patterns + +### Component Structure + + + +```{{language}} +{{component template}} +``` + +### Error Handling + + + +```{{language}} +{{error handling template}} +``` + +### Logging + + + +```{{language}} +{{logging template}} +``` + +## Testing Conventions + +### Test File Location + +- Unit tests: `tests/unit/{{module}}/` +- Integration tests: `tests/integration/` +- E2E tests: `tests/e2e/` + +### Test Naming + +``` +test_{{function_name}}_{{scenario}}_{{expected_result}} +``` + +### Test Structure + +```{{language}} +describe('{{Component}}', () => { + describe('{{method}}', () => { + it('should {{expected behavior}} when {{condition}}', () => { + // Arrange + // Act + // Assert + }); + }); +}); +``` + +## Documentation Standards + +### Code Comments + +- Use comments to explain WHY, not WHAT +- Document public APIs with docstrings +- Keep comments up-to-date with code changes + +### README Requirements + +Each module should have a README with: + +- [ ] Purpose description +- [ ] Quick start example +- [ ] API reference (or link) +- [ ] Dependencies + +## Git Workflow + +### Branch Naming + +| Type | Format | Example | +|------|--------|---------| +| Feature | `feature/{{ticket}}-{{description}}` | `feature/PROJ-123-add-auth` | +| Bugfix | `fix/{{ticket}}-{{description}}` | `fix/PROJ-456-null-check` | +| Hotfix | `hotfix/{{description}}` | `hotfix/security-patch` | +| Release | `release/{{version}}` | `release/1.2.0` | + +### Commit Messages + +``` +{{type}}({{scope}}): {{description}} + +{{body}} + +{{footer}} +``` + +Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` + +### Pull Request Template + +```markdown +## Summary +{{brief description}} + +## Changes +- {{change 1}} +- {{change 2}} + +## Testing +- [ ] Unit tests +- [ ] Integration tests +- [ ] Manual testing + +## Spec Reference +- [{{spec name}}](.spec-flow/active/{{feature}}/proposal.md) +``` + +## Dependency Management + +### Adding Dependencies + +1. Check if similar functionality exists in current deps +2. Evaluate security (npm audit / safety check) +3. Check maintenance status (last update, issues) +4. Document reason in PR + +### Version Pinning + +- Lock exact versions in production +- Allow minor updates in development +- Review major updates explicitly + +## Performance Guidelines + +### Code-Level + +- Avoid N+1 queries +- Use lazy loading for large data +- Cache expensive computations +- Profile before optimizing + +### Bundle Size (Frontend) + +- Maximum bundle size: {{size}} +- Use code splitting for routes +- Lazy load heavy components + +## Change History + +| Date | Change | Author | +|------|--------|--------| +| {{date}} | Initial structure guide | {{author}} | diff --git a/skills/.experimental/spec-flow/templates/steering/tech.md.template b/skills/.experimental/spec-flow/templates/steering/tech.md.template new file mode 100644 index 0000000..ed77921 --- /dev/null +++ b/skills/.experimental/spec-flow/templates/steering/tech.md.template @@ -0,0 +1,151 @@ +# Technology Constraints + +> **Last Updated**: {{DATE}} +> **Tech Lead**: {{NAME}} + +## Tech Stack + +### Languages + +| Purpose | Language | Version | Notes | +|---------|----------|---------|-------| +| Backend | {{language}} | {{version}} | | +| Frontend | {{language}} | {{version}} | | +| Scripts | {{language}} | {{version}} | | + +### Frameworks + +| Purpose | Framework | Version | Notes | +|---------|-----------|---------|-------| +| Web Framework | {{framework}} | {{version}} | | +| ORM | {{framework}} | {{version}} | | +| Testing | {{framework}} | {{version}} | | + +### Infrastructure + +| Component | Technology | Provider | Notes | +|-----------|------------|----------|-------| +| Database | {{tech}} | {{provider}} | | +| Cache | {{tech}} | {{provider}} | | +| Message Queue | {{tech}} | {{provider}} | | +| Hosting | {{tech}} | {{provider}} | | + +## Performance Targets + +| Metric | Target | Current | Priority | +|--------|--------|---------|----------| +| API Response Time (p50) | {{ms}} | {{ms}} | High | +| API Response Time (p99) | {{ms}} | {{ms}} | High | +| Page Load Time | {{s}} | {{s}} | High | +| Memory Usage | {{MB}} | {{MB}} | Medium | +| CPU Utilization | {{%}} | {{%}} | Medium | + +## Scalability Requirements + +- **Concurrent Users**: {{number}} +- **Requests per Second**: {{number}} +- **Data Volume**: {{size}} +- **Growth Rate**: {{percentage}} per {{period}} + +## Security Requirements + +### Authentication + +- {{authentication method}} +- {{session management}} + +### Authorization + +- {{authorization model}} +- {{role definitions}} + +### Data Protection + +- **Encryption at Rest**: {{requirement}} +- **Encryption in Transit**: {{requirement}} +- **PII Handling**: {{requirement}} + +### Compliance + +- [ ] {{compliance requirement 1}} +- [ ] {{compliance requirement 2}} + +## Dependencies + +### External Services + +| Service | Purpose | Criticality | Fallback | +|---------|---------|-------------|----------| +| {{service}} | {{purpose}} | High/Medium/Low | {{fallback}} | + +### Internal Services + +| Service | Purpose | Owner | API Docs | +|---------|---------|-------|----------| +| {{service}} | {{purpose}} | {{team}} | {{link}} | + +## Development Environment + +### Required Tools + +- {{tool 1}} (version {{version}}) +- {{tool 2}} (version {{version}}) + +### Setup + +```bash +# Clone repository +git clone {{repo}} + +# Install dependencies +{{install command}} + +# Start development server +{{start command}} +``` + +## Technical Debt + +### Known Issues + +| Issue | Impact | Priority | Plan | +|-------|--------|----------|------| +| {{issue}} | {{impact}} | High/Medium/Low | {{resolution plan}} | + +### Tech Debt Budget + +- {{percentage}}% of sprint capacity allocated to tech debt +- Major refactoring requires spec + +## Constraints + +### Must Use + + + +- {{technology}}: {{reason}} + +### Must Not Use + + + +- {{technology}}: {{reason}} + +### Prefer + + + +- {{technology}}: {{reason}} + +## Architecture Decisions Records (ADRs) + +| ADR | Title | Status | Date | +|-----|-------|--------|------| +| ADR-001 | {{title}} | Accepted | {{date}} | +| ADR-002 | {{title}} | Accepted | {{date}} | + +## Change History + +| Date | Change | Author | +|------|--------|--------| +| {{date}} | Initial tech constraints | {{author}} | diff --git a/skills/.experimental/spec-flow/templates/tasks.md.template b/skills/.experimental/spec-flow/templates/tasks.md.template new file mode 100644 index 0000000..77d5279 --- /dev/null +++ b/skills/.experimental/spec-flow/templates/tasks.md.template @@ -0,0 +1,192 @@ +# {{FEATURE_NAME}} - Tasks + +> **Status**: Not Started | In Progress | Completed +> **Design Doc**: [design.md](./design.md) +> **Started**: {{DATE}} +> **Target Completion**: {{DATE}} + +--- + +## 🎛️ Execution Modes (AI Agent MUST Read) + +**Three execution modes available:** + +| Mode | Trigger Phrases | Behavior | +|------|-----------------|----------| +| **Step Mode** (Default) | "start", "begin" | Execute one task, wait for confirmation, repeat | +| **Batch Mode** | "execute all", "batch mode" | Execute all tasks consecutively, report at end | +| **Phase Mode** | "execute phase 1", "execute setup" | Execute all tasks in one phase, then wait | + +**All modes MUST follow:** +1. ✅ Execute in order - Start from first `- [ ]` +2. ✅ Check dependencies - Ensure dependency tasks completed (`- [x]`) +3. ✅ Update status - Change `- [ ]` to `- [x]` after completion +4. ✅ Report progress - Show (N/Total) +5. ✅ Stop on error - Stop immediately on error, wait for user + +**Prohibited:** +- ❌ Skip tasks +- ❌ Execute out of order +- ❌ Do work not in task list +- ❌ Continue after error + +--- + +## Overview + +| Phase | Tasks | Completed | Progress | +|-------|-------|-----------|----------| +| Setup | {{n}} | 0 | 0% | +| Implementation | {{n}} | 0 | 0% | +| Testing | {{n}} | 0 | 0% | +| Documentation | {{n}} | 0 | 0% | +| **Total** | **{{n}}** | **0** | **0%** | + +## Task Breakdown + +### Phase 1: Setup + +- [ ] **T-001**: {{task description}} + - **Complexity**: Low + - **Files**: `{{path/to/file}}` + - **Dependencies**: None + - **Notes**: {{additional context}} + +- [ ] **T-002**: {{task description}} + - **Complexity**: Low + - **Files**: `{{path/to/file}}` + - **Dependencies**: T-001 + - **Notes**: + +### Phase 2: Core Implementation + +- [ ] **T-010**: {{task description}} + - **Complexity**: Medium + - **Files**: + - `{{path/to/file1}}` + - `{{path/to/file2}}` + - **Dependencies**: T-002 + - **Notes**: + +- [ ] **T-011**: {{task description}} + - **Complexity**: High + - **Files**: `{{path/to/file}}` + - **Dependencies**: T-010 + - **Notes**: + +- [ ] **T-012**: {{task description}} + - **Complexity**: Medium + - **Files**: `{{path/to/file}}` + - **Dependencies**: T-010 + - **Notes**: + +### Phase 3: Integration + +- [ ] **T-020**: {{task description}} + - **Complexity**: Medium + - **Files**: `{{path/to/file}}` + - **Dependencies**: T-011, T-012 + - **Notes**: + +### Phase 4: Testing + +- [ ] **T-030**: Write unit tests for {{component}} + - **Complexity**: Medium + - **Files**: `{{path/to/test/file}}` + - **Dependencies**: T-020 + - **Notes**: Target coverage: {{percentage}}% + +- [ ] **T-031**: Write integration tests + - **Complexity**: Medium + - **Files**: `{{path/to/test/file}}` + - **Dependencies**: T-030 + - **Notes**: + +- [ ] **T-032**: Manual QA testing + - **Complexity**: Low + - **Files**: N/A + - **Dependencies**: T-031 + - **Notes**: Test cases: {{list}} + +### Phase 5: Documentation + +- [ ] **T-040**: Update API documentation + - **Complexity**: Low + - **Files**: `docs/{{file}}.md` + - **Dependencies**: T-020 + - **Notes**: + +- [ ] **T-041**: Update README/changelog + - **Complexity**: Low + - **Files**: `README.md`, `CHANGELOG.md` + - **Dependencies**: T-040 + - **Notes**: + +## Progress Tracking + +| Task | Status | Assignee | Started | Completed | Notes | +|------|--------|----------|---------|-----------|-------| +| T-001 | ⏳ Pending | | | | | +| T-002 | ⏳ Pending | | | | | +| T-010 | ⏳ Pending | | | | | +| T-011 | ⏳ Pending | | | | | +| T-012 | ⏳ Pending | | | | | +| T-020 | ⏳ Pending | | | | | +| T-030 | ⏳ Pending | | | | | +| T-031 | ⏳ Pending | | | | | +| T-032 | ⏳ Pending | | | | | +| T-040 | ⏳ Pending | | | | | +| T-041 | ⏳ Pending | | | | | + +**Legend**: +- ⏳ Pending +- 🔄 In Progress +- ✅ Done +- ❌ Blocked +- ⏸️ On Hold + +## Dependency Graph + +```mermaid +graph LR + T001[T-001: Setup] --> T002[T-002: Config] + T002 --> T010[T-010: Core] + T010 --> T011[T-011: Feature A] + T010 --> T012[T-012: Feature B] + T011 --> T020[T-020: Integration] + T012 --> T020 + T020 --> T030[T-030: Unit Tests] + T030 --> T031[T-031: Integration Tests] + T031 --> T032[T-032: QA] + T020 --> T040[T-040: API Docs] + T040 --> T041[T-041: README] +``` + +## Blockers + + + +| Blocker | Blocking Tasks | Raised | Owner | Status | Resolution | +|---------|----------------|--------|-------|--------|------------| +| {{blocker description}} | T-XXX | {{date}} | {{name}} | Open/Resolved | {{resolution}} | + +## Change Log + + + +| Date | Change | Reason | +|------|--------|--------| +| {{date}} | Initial task breakdown | | +| {{date}} | {{change}} | {{reason}} | + +## Completion Checklist + +Before marking as complete: + +- [ ] All tasks marked as Done +- [ ] All tests passing +- [ ] Code reviewed +- [ ] Documentation updated +- [ ] Changelog updated +- [ ] Stakeholders notified +- [ ] Spec archived to `.spec-flow/archive/{{feature-name}}/`