---
# Stage identity per spec Section 6.1
stage: 4
stage_id: "04"
title: "Generate Specification"
workflow: specify
estimated_tokens: 2000

# Context specification
context:
  static:
    persona: "meticulous requirements analyst extracting precise requirements"
    purpose: "Create spec.md using chunked approach to handle large specifications"
  dynamic:
    - key: feature_dir
      source: cli_arg
    - key: repoix_mode
      source: tool_state

# Pre-validation checks
pre_validation:
  - check: stage_03_completed
    condition: "state.specify.current_stage == '03-branch-setup'"
    message: "Stage 03 (Branch Setup) must be completed first"
    recovery: "civyk-hatch specify --stage=3"
  - check: feature_dir_exists
    condition: "feature_dir exists"
    message: "Feature directory must exist"
    recovery: "civyk-hatch specify --stage=3"

# Execution flow with step types
execution_flow:
  - step: 1
    type: action
    name: create_template
    instruction: "Copy spec template to feature directory and do initial replacements"
  - step: 2
    type: action
    name: parse_feature
    instruction: "Extract actors, actions, data, and constraints from feature description"
  - step: 3
    type: action
    name: fill_chunk_1
    instruction: "Fill title/metadata, overview, and scope sections"
  - step: 4
    type: action
    name: fill_chunk_2
    instruction: "Fill user stories section with prioritized stories and acceptance criteria"
  - step: 5
    type: action
    name: fill_chunk_3
    instruction: "Fill functional requirements, non-functional requirements, and assumptions"
  - step: 6
    type: action
    name: fill_chunk_4
    instruction: "Fill technical context and success criteria sections"
  - step: 7
    type: action
    name: handle_ambiguities
    instruction: "Review for ambiguities, mark max 3 with [NEEDS CLARIFICATION]"
  - step: 8
    type: action
    name: final_validation
    instruction: "Verify all placeholders replaced except clarification markers"

# Guardrails
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Edit
    - Write
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Delete production source files"
    - "Modify source code outside spec directory"
  file_restrictions:
    allowed_paths:
      - "specs/**"
      - "{{feature_dir}}/**"
    forbidden_paths:
      - ".env"
      - "**/*.key"
      - "**/credentials*"
  read_only: false

# Post-validation checks
post_validation:
  - check: spec_created
    description: "spec.md file was created"
    severity: error
  - check: placeholders_replaced
    description: "All placeholders replaced (except clarification markers)"
    severity: error
  - check: user_stories_defined
    description: "User stories were defined with acceptance criteria"
    severity: warning

# Output specification
output:
  state_update:
    specify.current_stage: "04-generate-spec"
  completion_command: "civyk-hatch update-stage specify 04 --status completed"

# Next stage
next:
  stage: 5
  stage_id: "05"
  command: "civyk-hatch specify --stage=5"
  is_terminal: false
version: 1.0.0
---
{{include:ai-cache-enforcement.md}}

# Stage 4: Generate Specification

You are a {persona}.

Create spec.md using a chunked approach to handle large specifications.

---

## File Write Best Practices

**For large specifications:**

- Use chunked writing (Steps 3-6 below are already chunked)
- Keep each edit operation under 2000 characters
- If using shell commands with content, be aware of OS limits (~8000 chars on Windows)

---

## Step 1: Create Spec Template

The CLI automatically copies the spec template to the feature directory:

{{copy-template:spec-template.md:spec.md}}

Now edit `{{feature_dir}}/spec.md` with these initial replacements:

- Replace `<<FEATURE_NAME>>` with feature name
- Replace `<<DATE>>` with today's date
- Replace `<<FEATURE_BRANCH>>` with the current feature branch name
- Replace `<<ARGUMENTS>>` with the original user description
- Keep all other `<<...>>` placeholders for now

---

## Tools (if REPOIX_MODE != "none")

{{include:spec-civyk-repoix-discovery.md}}

---

## Step 2: Parse Feature Description

Extract from the feature description:

- **Actors**: Who uses this feature?
- **Actions**: What can they do?
- **Data**: What information is involved?
- **Constraints**: What limitations exist?

---

## Step 3: Fill Sections (Chunk 1 - Header & Overview)

Edit `{{feature_dir}}/spec.md` to fill:

- **Title and metadata** section
- **Overview** section (brief description)
- **Scope** section (In Scope / Out of Scope)

---

## Step 4: Fill Sections (Chunk 2 - User Stories)

Edit `{{feature_dir}}/spec.md` to fill:

- **User Stories** section with format:
  - Priority (P1/P2/P3)
  - "As a [user], I want [goal] so that [benefit]"
  - Acceptance scenarios in Given/When/Then format

**Guidelines:**

- P1 = Must have (MVP)
- P2 = Should have
- P3 = Nice to have
- Each scenario must be testable

---

## Step 5: Fill Sections (Chunk 3 - Requirements)

Edit `{{feature_dir}}/spec.md` to fill:

- **Functional Requirements** (FR-001, FR-002, etc.)
- **Non-Functional Requirements** (if applicable)
- **Assumptions** section

**Guidelines:**

- Each requirement independently testable
- Use reasonable defaults for unspecified details
- Document assumptions

---

## Step 6: Fill Sections (Chunk 4 - Technical Context)

Edit `{{feature_dir}}/spec.md` to fill:

- **Technical Context** section
- **Success Criteria** section

**Success Criteria Guidelines:**

- Measurable outcomes (time, percentage, count)
- Technology-agnostic (no frameworks, APIs)
- User-focused (business perspective)

**Good examples:**

- "Users can complete checkout in under 3 minutes"
- "System supports 10,000 concurrent users"

**Bad examples (too technical):**

- "API response time is under 200ms"
- "Redis cache hit rate above 80%"

---

## Step 7: Handle Ambiguities

Review the spec for unclear items:

**Only mark with [NEEDS CLARIFICATION] if:**

- Choice significantly impacts scope or UX
- Multiple reasonable interpretations exist
- No reasonable default applies

**LIMIT: Maximum 3 clarification markers.**

Prioritize: scope > security > user experience > technical

**Make informed guesses for:**

- Data retention (industry standard)
- Performance (standard web expectations)
- Error handling (user-friendly messages)
- Authentication (standard OAuth2/sessions)

---

## Step 8: Final Validation

Verify spec.md is complete:

```bash
# Check for remaining placeholders
grep -E '\[.*\]' {{feature_dir}}/spec.md | grep -v 'NEEDS CLARIFICATION'
```

**All placeholders must be replaced** (except [NEEDS CLARIFICATION] markers).

---

## Output

After completing all chunks:

```text
[ok] Specification generated
  - File: {{feature_dir}}/spec.md
  - User stories: [N]
  - Requirements: [N]
  - Clarifications needed: [0-3]
```

---

## NEXT

```bash
civyk-hatch specify --stage=5 --feature-dir="{FEATURE_DIR}"
```
