Skill: echovic/spec-flow (version 0.1.0)

--- name: spec-flow description: "Spec-driven development workflow. Interactive phase-by-phase confirmation from proposal to implementation. Trigger: 'spec-flow', 'spec mode', 'need a plan', 'structured development', 'write a spec', 'feature spec', 'technical spec', '需求文档', '技术方案', '任务拆解', '规格驱动', '写个方案', '做个规划', '结构化开发', 'plan this feature', 'break this down', 'design doc'. Creates .spec-flow/ directory with proposal, requirements, design, and tasks." argument-hint: "[feature description] [--fast] [--skip-design]" --- # Spec-Flow - Structured Development Workflow Structured workflow for complex feature development. Creates living documentation that guides implementation and serves as team reference. ## Core Principles 1. **One phase at a time** — NEVER generate documents for subsequent phases in advance 2. **Mandatory confirmation** — After each phase, STOP and wait for user confirmation 3. **User-driven progression** — Only proceed when user says "continue"/"ok"/"next"/"继续"/"好" ## Parameters | 参数 | 说明 | |------|------| | `--fast` | 跳过逐阶段确认，一次性生成所有文档（最后整体确认） | | `--skip-design` | 跳过 Design 阶段（简单功能，架构显而易见时） | ## Language Rule **所有生成的 .md 文件必须使用中文。** ## Interaction Rules Load `references/interaction-rules.md` for detailed confirmation templates and prohibited behaviors. --- ## Five-Phase Workflow Copy this checklist and check off items as you complete them: ### Spec-Flow Progress: - [ ] **Phase 0: Initialize** ⚠️ REQUIRED - [ ] 0.1 Run `scripts/init-spec-flow.sh <feature-name>` or create `.spec-flow/active/<feature>/` - [ ] 0.2 Check if `.spec-flow/steering/` exists — if so, read for project context - [ ] 0.3 问自己：**这个功能的核心价值是什么？用一句话能说清吗？** - [ ] **Phase 1: Proposal** ⚠️ REQUIRED - [ ] 1.1 Create `.spec-flow/active/<feature>/proposal.md` using `templates/proposal.md.template` - [ ] 1.2 包含：Background, Goals, Non-Goals, Scope, Risks, Open Questions - [ ] 1.3 问自己：**有没有隐含的需求没写出来？** - [ ] 1.4 问自己：**Non-Goals 是否足够明确？能防止 scope creep 吗？** - [ ] 1.5 ⏸️ 确认节点 — 等待用户确认后继续 - [ ] **Phase 2: Requirements** - [ ] 2.1 Create `.spec-flow/active/<feature>/requirements.md` using `templates/requirements.md.template` - [ ] 2.2 Load `references/ears-format.md` — 使用 EARS 格式编写需求 - [ ] 2.3 包含：FR-xxx 功能需求, NFR-xxx 非功能需求, AC-xxx 验收标准 - [ ] 2.4 问自己：**每条需求都是可测试的吗？** - [ ] 2.5 问自己：**边界情况覆盖了吗？错误场景呢？** - [ ] 2.6 ⏸️ 确认节点 — 等待用户确认后继续 - [ ] **Phase 3: Design**（除非 `--skip-design`） - [ ] 3.1 Create `.spec-flow/active/<feature>/design.md` using `templates/design.md.template` - [ ] 3.2 包含：Architecture (Mermaid), Components, API, Data Model, Error Handling - [ ] 3.3 问自己：**这个设计能满足所有 requirements 吗？逐条对照** - [ ] 3.4 问自己：**有没有更简单的方案？过度设计了吗？** - [ ] 3.5 ⏸️ 确认节点 — 等待用户确认后继续 - [ ] **Phase 4: Tasks** - [ ] 4.1 Create `.spec-flow/active/<feature>/tasks.md` using `templates/tasks.md.template` - [ ] 4.2 Load `references/task-decomposition.md` — 遵循任务拆解规范 - [ ] 4.3 每个任务：1-2 tool calls 可完成，标注复杂度 Low/Medium/High - [ ] 4.4 分组：Setup → Implementation → Testing → Documentation - [ ] 4.5 问自己：**任务之间的依赖关系对吗？有没有可以并行的？** - [ ] 4.6 ⏸️ 确认节点 — 等待用户确认后继续 - [ ] **Phase 5: Implementation** - [ ] 5.1 Load `references/execution-modes.md` — 确认执行模式 - [ ] 5.2 默认 Step Mode（逐任务确认），用户可切换 Batch/Phase Mode - [ ] 5.3 每个任务执行前：读 tasks.md → 检查依赖 → 读 design.md - [ ] 5.4 每个任务执行后：更新 tasks.md 状态（`- [ ]` → `- [x]`） - [ ] 5.5 全部完成后：归档到 `.spec-flow/archive/` --- ## Directory Structure ``` .spec-flow/ ├── steering/ # 全局项目上下文（可选） │ ├── constitution.md │ ├── product.md │ ├── tech.md │ └── structure.md ├── active/ # 进行中 │ └── <feature>/ │ ├── proposal.md │ ├── requirements.md │ ├── design.md │ └── tasks.md └── archive/ # 已完成 ``` ## Steering Documents (Optional) | Document | Purpose | Template | |----------|---------|----------| | `constitution.md` | 项目治理原则 | `templates/steering/constitution.md.template` | | `product.md` | 产品愿景、目标用户 | `templates/steering/product.md.template` | | `tech.md` | 技术栈、约束 | `templates/steering/tech.md.template` | | `structure.md` | 代码组织、命名规范 | `templates/steering/structure.md.template` | ## Phase Transitions | From | To | Condition | |------|-----|-----------| | Proposal | Requirements | Proposal approved, questions resolved | | Requirements | Design | Requirements complete, testable | | Requirements | Tasks | `--skip-design`, simple feature | | Design | Tasks | Design approved | | Tasks | Implementation | Tasks confirmed | | Implementation | Done | All tasks complete → archive | ## Compatibility Works with any AI agent that supports Skills format: Claude Code, Blade, OpenClaw, Cursor, Windsurf, etc.

path: CONTRIBUTING.md
content: # Contributing to Spec-Flow

Thank you for your interest in contributing to Spec-Flow! This document provides guidelines and instructions for contributing.

## 🌟 Ways to Contribute

- **Bug Reports**: Found a bug? Open an issue with details
- **Feature Requests**: Have an idea? Share it in the issues
- **Documentation**: Improve README, examples, or references
- **Code**: Fix bugs, add features, improve templates
- **Templates**: Create new templates or improve existing ones
- **Examples**: Add real-world usage examples

## 🚀 Getting Started

### 1. Fork and Clone

```bash
# Fork the repository on GitHub, then:
git clone https://github.com/YOUR_USERNAME/spec-flow.git
cd spec-flow
```

### 2. Create a Branch

```bash
git checkout -b feature/your-feature-name
# or
git checkout -b fix/bug-description
```

### 3. Make Changes

- Follow the existing code style
- Update documentation if needed
- Test your changes with Claude Code
- Add examples if introducing new features

### 4. Commit Changes

```bash
git add .
git commit -m "feat: add support for custom templates"
# or
git commit -m "fix: resolve task dependency checking"
```

**Commit Message Format:**
- `feat:` New feature
- `fix:` Bug fix
- `docs:` Documentation changes
- `refactor:` Code refactoring
- `test:` Test updates
- `chore:` Maintenance tasks

### 5. Push and Create Pull Request

```bash
git push origin feature/your-feature-name
```

Then open a Pull Request on GitHub.

## 📋 Pull Request Guidelines

### Before Submitting

- [ ] Test your changes with Claude Code
- [ ] Update relevant documentation
- [ ] Add examples if needed
- [ ] Ensure templates follow existing format
- [ ] Check for typos and grammar

### PR Description Should Include

- **What**: What does this PR do?
- **Why**: Why is this change needed?
- **How**: How does it work?
- **Testing**: How did you test it?

### Example PR Description

```markdown
## What
Adds support for custom template directories

## Why
Users want to use their own templates instead of the defaults

## How
- Added `SPEC_FLOW_TEMPLATES` environment variable
- Modified template loading logic in SKILL.md
- Updated documentation

## Testing
- Tested with custom template directory
- Verified fallback to default templates
- Checked with both Claude Code and Blade
```

## 🎯 Development Guidelines

### Templates

- Use `.template` extension
- Include clear comments in Chinese and English
- Follow Markdown best practices
- Use Mermaid for diagrams

### Scripts

- Add shebang (`#!/bin/bash` or `#!/usr/bin/env python3`)
- Make executable (`chmod +x`)
- Include usage instructions
- Handle errors gracefully

### Documentation

- Keep README.md up to date
- Update SKILL.md for workflow changes
- Add examples for new features
- Use clear, concise language

### References

- Cite sources for methodologies (e.g., EARS)
- Include real-world examples
- Explain "why" not just "how"

## 🧪 Testing

### Manual Testing

```bash
# Install in Claude Code
cp -r spec-flow ~/.claude/skills/

# Test the skill
# 1. Start Claude Code in a project
# 2. Say "spec-flow" to trigger
# 3. Go through all phases
# 4. Verify documents are created correctly
```

### Validation Script

```bash
# Test the validation script
python3 scripts/validate-spec-flow.py
```

## 📝 Code Style

### Markdown
- Use ATX-style headers (`#`, `##`, `###`)
- Add blank lines around headers and code blocks
- Use tables for structured data
- Use emojis sparingly, only for visual hierarchy

### Shell Scripts
- Use `shellcheck` if possible
- Quote variables
- Check for command existence
- Provide helpful error messages

### Python
- Follow PEP 8
- Use type hints
- Add docstrings
- Handle exceptions

## 🐛 Reporting Issues

### Bug Reports Should Include

- **Description**: Clear description of the bug
- **Steps to Reproduce**: How to reproduce the issue
- **Expected Behavior**: What should happen
- **Actual Behavior**: What actually happens
- **Environment**: Claude Code version, OS, etc.

### Example Bug Report

```markdown
## Description
Tasks are not being marked as completed in tasks.md

## Steps to Reproduce
1. Start spec-flow workflow
2. Complete all phases
3. Execute tasks in batch mode
4. Check tasks.md

## Expected Behavior
Tasks should have `- [x]` checkmarks

## Actual Behavior
Tasks still show `- [ ]`

## Environment
- Claude Code: v1.2.3
- OS: macOS 14.0
- Skill version: v1.0.0
```

## 💬 Questions?

- **General Questions**: Open a GitHub Discussion
- **Bug Reports**: Open an Issue
- **Feature Requests**: Open an Issue with [Feature Request] label
- **Security Issues**: Email (add your email here)

## 📜 Code of Conduct

- Be respectful and inclusive
- Welcome newcomers
- Accept constructive criticism
- Focus on what's best for the community
- Show empathy towards others

## 🙏 Thank You!

Every contribution, no matter how small, makes a difference. Thank you for helping make Spec-Flow better!

---

**Happy Contributing! 🎉**


path: README.md
content: # Spec-Flow

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Spec-driven development workflow for AI coding agents**

Spec-Flow transforms complex feature development into a guided, phase-by-phase workflow with living documentation. Works with any AI agent that supports the Skills format.

## Features

- **Phase-by-Phase Workflow**: Proposal → Requirements → Design → Tasks → Implementation
- **Interactive Confirmation**: Each phase waits for your approval before proceeding
- **Living Documentation**: Creates `.spec-flow/` directory with Markdown docs that guide implementation
- **EARS Requirements**: Industry-standard Easy Approach to Requirements Syntax
- **3 Execution Modes**: Step (default), Batch, Phase — choose your speed
- **Team Collaboration**: Git-friendly, commit specs with your project

## Installation

```bash
# Claude Code
cd ~/.claude/skills && git clone https://github.com/echoVic/spec-flow.git

# OpenClaw
cd ~/.openclaw/workspace/skills && git clone https://github.com/echoVic/spec-flow.git

# Blade
cd ~/.blade/skills && git clone https://github.com/echoVic/spec-flow.git

# Or any agent's skills directory
```

## Quick Start

Trigger with: `spec-flow`, `spec mode`, `need a plan`, `structured development`, `写个方案`, `做个规划`

```
User: spec-flow — add user authentication

AI: [Creates proposal.md] → waits for confirmation
User: continue
AI: [Creates requirements.md] → waits for confirmation
User: continue
AI: [Creates design.md] → waits for confirmation
User: continue
AI: [Creates tasks.md] → waits for confirmation
User: execute all tasks
AI: [Implements everything]
```

Parameters: `--fast` (skip confirmations), `--skip-design` (simple features)

## Five-Phase Workflow

```
┌──────────┐    ┌──────────────┐    ┌────────┐    ┌───────┐    ┌────────────────┐
│ Proposal │ → │ Requirements │ → │ Design │ → │ Tasks │ → │ Implementation │
└──────────┘    └──────────────┘    └────────┘    └───────┘    └────────────────┘
    WHY              WHAT              HOW        EXECUTE         BUILD
```

| Phase | Goal | Output |
|-------|------|--------|
| Proposal | Define WHY | Background, goals, non-goals, risks |
| Requirements | Define WHAT | FR/NFR in EARS format, acceptance criteria |
| Design | Define HOW | Architecture, API, data model (Mermaid) |
| Tasks | Break down | Granular tasks with dependencies |
| Implementation | Build | Code, tests, documentation |

## Execution Modes

| Mode | Trigger | Behavior |
|------|---------|----------|
| **Step** (default) | "start implementation" | One task → confirm → next |
| **Batch** | "execute all" / "全部执行" | All tasks consecutively |
| **Phase** | "execute setup phase" | All tasks in one phase → confirm |

## Directory Structure

```
.spec-flow/
├── steering/           # Optional: global project context
│   ├── constitution.md
│   ├── product.md
│   ├── tech.md
│   └── structure.md
├── active/             # Work in progress
│   └── <feature>/
│       ├── proposal.md
│       ├── requirements.md
│       ├── design.md
│       └── tasks.md
└── archive/            # Completed features
```

## File Structure

```
spec-flow/
├── SKILL.md                              # Checklist workflow
├── references/
│   ├── ears-format.md                    # EARS requirement syntax
│   ├── task-decomposition.md             # Task breakdown patterns
│   ├── workflow.md                       # Detailed workflow guide
│   ├── interaction-rules.md              # Confirmation rules
│   ├── execution-modes.md               # Step/Batch/Phase modes
│   └── examples/
├── templates/                            # Document templates
│   ├── proposal.md.template
│   ├── requirements.md.template
│   ├── design.md.template
│   ├── tasks.md.template
│   └── steering/
└── scripts/
    ├── init-spec-flow.sh                 # Initialize spec directory
    ├── validate-spec-flow.py             # Validate completeness
    └── execute-task.sh                   # Execute a task
```

## Language

- Workflow instructions: English
- Generated documents: Chinese (中文) by default

## License

MIT


path: references/ears-format.md
content: # 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 <system> shall <action>.`

**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 <trigger>, the <system> shall <action>.`

**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 <state>, the <system> shall <action>.`

**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 <condition>, then the <system> shall NOT <action>.`

**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 <feature/option>, the <system> shall <action>.`

**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 <system> shall <action>.
EVENT-DRIVEN:  When <trigger>, the <system> shall <action>.
STATE-DRIVEN:  While <state>, the <system> shall <action>.
UNWANTED:      If <condition>, then the <system> shall NOT <action>.
OPTIONAL:      Where <feature>, the <system> shall <action>.
```


path: references/examples/feature-example.md
content: # 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": "[REDACTED_SECRET]",
  "password": "SecurePass123"
}
```

**Response (201)**:
```json
{
  "user": { "id": "uuid", "email": "[REDACTED_SECRET]" },
  "accessToken": "jwt..."
}
```

### POST /api/auth/login

**Request**:
```json
{
  "email": "[REDACTED_SECRET]",
  "password": "SecurePass123"
}
```

**Response (200)**:
```json
{
  "user": { "id": "uuid", "email": "[REDACTED_SECRET]" },
  "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


path: references/execution-modes.md
content: # 执行模式

Phase 5 实现阶段支持三种执行模式。默认 Step Mode。

## Step Mode（默认）

逐任务执行，每个任务完成后等待用户确认。

**触发词**: "start implementation", "开始执行"

**适用场景**: 复杂任务、需要仔细审查、首次使用 spec-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", "全部执行", "batch mode", "批量执行", "一口气执行完"

**适用场景**: 简单任务、信任计划、追求速度

**流程**:
```
User: execute all tasks

AI: ⚡ Batch Mode Activated

    🔄 T-001: [description] → ✅
    🔄 T-002: [description] → ✅
    🔄 T-003: [description] → ✅

    📊 Batch Complete: 10/10 tasks done
```

**规则**:
- 每个任务完成后仍需更新 tasks.md
- 任何任务失败立即停止
- 用户可用 "stop"/"暂停" 中断

## Phase Mode

按阶段批量执行（Setup → Core → Testing → Docs），每个阶段完成后等待确认。

**触发词**: "execute phase 1", "执行第一阶段", "execute setup"

**流程**:
```
User: execute setup phase

AI: 📦 Phase Mode: Setup

    🔄 T-001: [description] → ✅
    🔄 T-002: [description] → ✅

    ✅ Setup Phase Complete (2/10 total)
    Next phase: Core Implementation
    👉 Say "continue" or "execute next phase"
```

## 所有模式通用规则

### 执行前必做

1. 读取 tasks.md — 获取当前任务列表和状态
2. 确认目标任务 — 根据模式确定执行范围
3. 检查依赖 — 确保前置任务已完成（`- [x]`）
4. 读取 design.md — 查看相关设计

### 执行后必做

- 更新 tasks.md 状态（`- [ ]` → `- [x]`）
- 显示进度

### 何时停止

- 任务失败或报错
- 设计文档不完整
- 依赖缺失或被阻塞
- 任务描述模糊
- 需要 design.md 中未覆盖的决策


path: references/interaction-rules.md
content: # 交互规则

## 确认模板

每个阶段完成后，必须使用此格式请求确认：

```
📋 **[Phase Name] Complete**

Created `.spec-flow/active/<feature>/<file>.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
```

## 用户确认信号

以下表达视为确认：
- "continue", "ok", "next", "looks good", "lgtm"
- "继续", "好", "下一步", "没问题", "可以"

## ❌ 禁止行为

| 禁止 | 原因 |
|------|------|
| 一次生成多个阶段的文档 | 用户无法逐步审查 |
| 未经确认自动进入下一阶段 | 违反 phase-by-phase 原则 |
| 同一个回复中创建 proposal + requirements | 跳过了确认节点 |
| 假设用户想跳过确认 | 必须用户明确请求 fast mode |

## ✅ 正确流程

```
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

仅当用户明确请求时启用（`--fast` 或说 "generate all at once"）：
- 一次性生成所有文档
- 最后整体确认


path: references/task-decomposition.md
content: # 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


path: references/workflow.md
content: # 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


path: scripts/execute-task.sh
content: #!/bin/bash
#
# execute-task.sh - Execute spec-flow tasks with full context
#
# Usage:
#   ./execute-task.sh <feature-name>           # Show next pending task
#   ./execute-task.sh <feature-name> <task-id> # Execute specific task
#   ./execute-task.sh <feature-name> --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 <feature-name> [task-id|--status]"
    echo ""
    echo "Commands:"
    echo "  <feature-name>              Show next pending task with context"
    echo "  <feature-name> <task-id>    Execute specific task (e.g., T-003)"
    echo "  <feature-name> --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


path: scripts/init-spec-flow.sh
content: #!/bin/bash
#
# init-spec-flow.sh - Initialize a new spec-flow directory structure
#
# Usage:
#   ./init-spec-flow.sh <feature-name> [--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 <feature-name> [--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 <feature-name> [--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"


path: scripts/validate-spec-flow.py
content: #!/usr/bin/env python3
"""
validate-spec-flow.py - Validate spec-flow completeness and consistency

Usage:
    python validate-spec-flow.py <spec-flow-directory>
    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 <spec-flow-directory>")
        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()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)